问:
unresolved external to typeinfo and dynamic_cast
The problem I have is very similar to the one discussed here:
g++ undefined reference to typeinfo

Even so, I believe I so not have the same issue, and the answers to that topi do not really help me.
What i have is :

```<code>class Base
{
    virtual ~Base() {}
    virtual void foo() = 0;
    // some other pure virtual behaviors
};

class Derived : public Base
{
    void foo() {/* do stuff */}
    // override for all other virtual behaviors
};
</code>```

then in different functions I have :

```<code>void bar( Base * base )
{
    Derived * derived = dynamic_cast<Derived *>(base);
}

void foobar( const Base & base1, const Base & base2 )
{
    if ( typeid(base1) == typeid(base2) )
        /* do something */;
}
</code>```

So I'm sure the function is either pure virtual or defined (even though the object can never be Base). This should not give any problems, and it is different from the quoted
discussion because i'm sure i override the virtual function.
Even so, when compiling with clang++, it issues an unresolved external for both typeid and dynamic_cast when used on Derived, while it doesn't do so for other classes that inherit from Base, and override the same foo behaviors.
Why does it do so?

here the errors:

```<code>error LNK2019: unresolved external symbol __imp___RTDynamicCast
error LNK2019: unresolved external symbol __imp___RTtypeid
</code>```

Am i just missing something silly, or misinterpreting these errors?

Edit

I realized the code examples I first gave were not descriptive enough :

```<code>class Base
{
public:
    virtual ~Base() {}
};

class Interface : public Base
{
public:
    virtual void foo() = 0;
    // some other pure virtual behaviors
};

class Derived : public Interface
{
public:
    void foo() {/* do stuff */}
    // override for all other virtual behaviors
};
</code>```

and

```<code>void bar()
{
    Base * base = new Derived;
    Interface * interface = dynamic_cast<Interface *>(base);
    interface->foo()
}
</code>```

fit better to what i'm trying to do.

答:
I got this problem using Clang 5.0 Platform Toolset LLVM-VS2014 on Visual studio and also on CodeBlocks.

I added msvcrt.lib to provide the missing __imp____RTDynamicCast.

How one is supposed to deduce this, I have yet to understand :-(

Body:
The problem I have is very similar to the one discussed here:
g++ undefined reference to typeinfo

Even so, I believe I so not have the same issue, and the answers to that topi do not really help me.
What i have is :

class Base
{
    virtual ~Base() {}
    virtual void foo() = 0;
    // some other pure virtual behaviors
};

class Derived : public Base
{
    void foo() {/* do stuff */}
    // override for all other virtual behaviors
};

then in different functions I have :

void bar( Base * base )
{
    Derived * derived = dynamic_cast<Derived *>(base);
}

void foobar( const Base & base1, const Base & base2 )
{
    if ( typeid(base1) == typeid(base2) )
        /* do something */;
}

So I'm sure the function is either pure virtual or defined (even though the object can never be Base). This should not give any problems, and it is different from the quoted
discussion because i'm sure i override the virtual function.
Even so, when compiling with clang++, it issues an unresolved external for both typeid and dynamic_cast when used on Derived, while it doesn't do so for other classes that inherit from Base, and override the same foo behaviors.
Why does it do so?

here the errors:

error LNK2019: unresolved external symbol __imp___RTDynamicCast
error LNK2019: unresolved external symbol __imp___RTtypeid

Am i just missing something silly, or misinterpreting these errors?

Edit

I realized the code examples I first gave were not descriptive enough :

class Base
{
public:
    virtual ~Base() {}
};

class Interface : public Base
{
public:
    virtual void foo() = 0;
    // some other pure virtual behaviors
};

class Derived : public Interface
{
public:
    void foo() {/* do stuff */}
    // override for all other virtual behaviors
};

and

void bar()
{
    Base * base = new Derived;
    Interface * interface = dynamic_cast<Interface *>(base);
    interface->foo()
}

fit better to what i'm trying to do.


来源: stackexchange

问:
Firebase transaction not working
I am calling from an angular app, using angularfire2, this.afDb.database is the db instance

```<code>const downloadsRef = this.afDb.database.ref('research_reports-published/' + rrid + '/' + field);
downloadsRef.transaction(function(fieldval) {
  if (fieldval) {
    fieldval = fieldval + 1;
  }
  return fieldval;
},
function(error, committed, snapshot) {
  if (error) {
    console.log('Transaction failed abnormally!', error);
  } else if (!committed) {
    console.log('We aborted the transaction (because ada already exists).');
  } else {
    console.log('User ada added!');
  }
  console.log('Adas data: ', snapshot.val());
}).then(function() {
    console.log('Transaction successfully committed!');
}).catch(function(error) {
    console.log('Transaction failed: ', error);
});
</code>```

The code just silently prints

```<code>Adas data: oldvalue
Transaction successfully committed
</code>```

and exits

答:
Found the issue in above code. It should be

```<code>if (fieldval != null) {
  fieldval = fieldval + 1;
}
</code>```

as fieldval=0 also makes it false

ContentLicense: CC BY-SA 3.0

Title: Firebase transaction not working

Body:
I am calling from an angular app, using angularfire2, this.afDb.database is the db instance

const downloadsRef = this.afDb.database.ref('research_reports-published/' + rrid + '/' + field);
downloadsRef.transaction(function(fieldval) {
  if (fieldval) {
    fieldval = fieldval + 1;
  }
  return fieldval;
},
function(error, committed, snapshot) {
  if (error) {
    console.log('Transaction failed abnormally!', error);
  } else if (!committed) {
    console.log('We aborted the transaction (because ada already exists).');
  } else {
    console.log('User ada added!');
  }
  console.log('Adas data: ', snapshot.val());
}).then(function() {
    console.log('Transaction successfully committed!');
}).catch(function(error) {
    console.log('Transaction failed: ', error);
});

The code just silently prints

Adas data: oldvalue
Transaction successfully committed

and exits

Body:
Found the issue in above code. It should be

if (fieldval != null) {
  fieldval = fieldval + 1;
}

as fieldval=0 also makes it false


问:
Xcode 7 - Code coverage data generation failed
When I run my tests I get an error:

Code coverage data generation failed.

  Unable to retrieve the profile data files from 'UIDevice'.

On console was printed warning:

Timed out waiting 120 seconds for simulator to boot, current state is 1.

What is the reason?

答:
Using Xcode 9.1 with multiple build targets and standard compiler we were working on UI tests and I started seeing this problem.  So, you will probably hate me for this answer, and I fully expect it to be downvoted, BUT this actually worked for me: I had to completely remove Xcode and my project from my machine to make this error disappear.

I tried every single suggestion in this thread, some multiple times, tried clearing cache files, deleting derived data, tinkering with build settings, updating podfiles, cleaning, rebuilding after each attempt, cleaning the simulator, manually recreating the simulators in 'manage devices'. After hours and hours of frustration it was still a complete mystery why this machine was failing to build our UI test.  It seemed to work fine on other machines and on our CI.  In addition to the items in this thread I manually modified the pbxproj file to set all options related to code coverage to "NO".

Finally, I was 1 step away from reformatting the entire machine.  I decided to completely remove Xcode following the suggestions here: Stackoverflow: How to completely uninstall Xcode.

Specifically, I trashed our workspace, quit all programs, deleted all of the files listed, cleared content and settings from the simulator, deleted the simulator, turned the machine off for 20 minutes, came back, reinstalled Xcode, cloned the repository, and voila! No error.

Hope that solves the issue for someone.  It's the 'nuclear' option, and you should never ever have to do this, but like I said, this is the only thing that worked for me.


问:
sbt scala language server server crashed 5 times in last 3 minutes. The server will not be restarted
I have installed Visual Studio code 1.18.1 on my mac book pro.

I also installed the Scala (SBT) plugin as instructed in this blog.

https://developer.lightbend.com/blog/2017-11-30-sbt-1-1-0-RC1-sbt-server/

Now when I restart visual studio code. I get an error

```<code>The sbt Scala Language Server server crashed 5 times in the last 3 minutes. The server will not be restarted.
</code>```

Has anyone got it to work at all?

BTW, I followed this blog

http://eed3si9n.com/sbt-server-with-sublime-text3

and the SBT server worked perfectly in Sublime. So I want to know if the same can work in VSCode or not.

答:
OK. I asked for help on the sbt gitter channel and found the solution.

My SBT server was already running when VSCode was run. I restarted both of them and that solved the problem.

Body:
I have installed Visual Studio code 1.18.1 on my mac book pro.

I also installed the Scala (SBT) plugin as instructed in this blog.

https://developer.lightbend.com/blog/2017-11-30-sbt-1-1-0-RC1-sbt-server/

Now when I restart visual studio code. I get an error

The sbt Scala Language Server server crashed 5 times in the last 3 minutes. The server will not be restarted.

Has anyone got it to work at all?

BTW, I followed this blog

http://eed3si9n.com/sbt-server-with-sublime-text3

and the SBT server worked perfectly in Sublime. So I want to know if the same can work in VSCode or not.


问:
Generating and submitting a dynamic number of objects in a form with Django
I want to be able to update a dynamic number of objects within a single form using Django and I'm wondering what the best way to do this would be. An example of a similar situation may help.

Model:

```<code>class Customer(Model.models):
    name = models.CharField(max_length=100)
    active = models.BooleanField()
</code>```

Form (I know I'm mixing view and template code here which doesn't work but this is a general idea for what the form is supposed to do):

```<code>customers = Customer.objects.all()
for c in customers:
    print <li> {{ c.name }} <input type="checkbox" value="{{ c.active }}" name="?" />
</code>```

How would I go about submitting a list of these objects? Would the best bet be to attach the id of the customer into each 'row' and then process based on the id? Is there a mechanism for submitting a list of tuples? What would be the ideal solution?

答:
Formsets!

Also, the equivalent for forms generated directly models are model formsets.

OwnerDisplayName: Josh Smeaton

ContentLicense: CC BY-SA 2.5

Body:
I want to be able to update a dynamic number of objects within a single form using Django and I'm wondering what the best way to do this would be. An example of a similar situation may help.

Model:

class Customer(Model.models):
    name = models.CharField(max_length=100)
    active = models.BooleanField()

Form (I know I'm mixing view and template code here which doesn't work but this is a general idea for what the form is supposed to do):

customers = Customer.objects.all()
for c in customers:
    print
 {{ c.name }} <input type="checkbox" value="{{ c.active }}" name="?" />

How would I go about submitting a list of these objects? Would the best bet be to attach the id of the customer into each 'row' and then process based on the id? Is there a mechanism for submitting a list of tuples? What would be the ideal solution?

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Van Gale

LastEditorDisplayName: Van Gale


问:
React - passing refs as a prop

I am trying to manage a checkbox with react. The following code works well enough, but I want to refactor out the code in the render method so that it uses a Component. I want to pass the ref to that component, but I cant figure out how to do it.

```<code>export default class AreRefsAwesomeCheckbox extends Component {
    constructor(props) {
        super(props);
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange() {
        let data = {
            isFeatured: this.refs.check_me.checked
        };
        postJSON('/some/url', data);
    }

    componentDidMount() {
        const data = getJSON('/some/url');
        data.then(object => {
                this.refs.check_me.checked = object.will_i_have_a_nice_checkbox;
            }
        )
    }

    render() {
        return (
            <div>
                <label>
                    <input ref="check_me" type="checkbox"
                           onChange={this.handleInputChange}/>
                    <div>Are refs good?</div>
                </label>

            </div>
        );
    }
}
</code>```

I was thinking about some thing like this

```<code>const Checkbox = ({myRef, changeInput, checkboxText}) => {
    return (
        <label>
            <input type="checkbox" ref={myRef} onChange={(event) => changeInput(event)}/>
            <div> {checkboxText} </div>
        </label>)
};
</code>```

And then putting this snippet in the render method

```<code><Checkbox myRef="check_me" changeInput={this.handleInputChange} checkboxText="Are refs good?"/>
</code>```

This obviously doesnt work. How do I do this?

答:
Pass a callback ref into the Component, like that:

```<code><Checkbox myRef={ref => (this.checkbox = ref)} />
</code>```

Oh, and by the way, please always use callback refs. Read more here.

One more idea to consider for you: Move the checked value of the checkbox fully into the state of the AreRefsAwesomeCheckbox component and use a fully controlled component. That's always better than a ref with bigger predictability and less surprises.

Full code:

```<code>const Checkbox = ({myRef, changeInput, checkboxText}) => {
  return (
    <label>
      <input
        type="checkbox"
        ref={myRef}
        onChange={event => changeInput(event)}
      />
      <div> {checkboxText} </div>
    </label>
  )
}

export default class AreRefsAwesomeCheckbox extends Component {
  constructor(props) {
    super(props)
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  handleInputChange() {
    let data = {
      isFeatured: this.refs.check_me.checked,
    }

    postJSON('/some/url', data)
  }

  componentDidMount() {
    const data = getJSON('/some/url')
    data.then(object => {
      // this.checkbox is the reference to the checkbox element you need
      this.checkbox.checked = object.will_i_have_a_nice_checkbox
    })
  }

  render() {
    return (
      <div>
        <label>
          <Checkbox myRef={ref => (this.checkbox = ref)} />

          <div>Are refs good?</div>
        </label>
      </div>
    )
  }
}
</code>```

Title: React - passing refs as a prop

Body:
I am trying to manage a checkbox with react. The following code works well enough, but I want to refactor out the code in the render method so that it uses a Component. I want to pass the ref to that component, but I cant figure out how to do it.

export default class AreRefsAwesomeCheckbox extends Component {
    constructor(props) {
        super(props);
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange() {
        let data = {
            isFeatured: this.refs.check_me.checked
        };
        postJSON('/some/url', data);
    }

    componentDidMount() {
        const data = getJSON('/some/url');
        data.then(object => {
                this.refs.check_me.checked = object.will_i_have_a_nice_checkbox;
            }
        )
    }

    render() {
        return (

                    <input ref="check_me" type="checkbox"
                           onChange={this.handleInputChange}/>

Are refs good?

        );
    }
}

I was thinking about some thing like this

const Checkbox = ({myRef, changeInput, checkboxText}) => {
    return (

            <input type="checkbox" ref={myRef} onChange={(event) => changeInput(event)}/>

 {checkboxText}

        )
};

And then putting this snippet in the render method

<Checkbox myRef="check_me" changeInput={this.handleInputChange} checkboxText="Are refs good?"/>

This obviously doesnt work. How do I do this?

Body:
Pass a callback ref into the Component, like that:

<Checkbox myRef={ref => (this.checkbox = ref)} />

Oh, and by the way, please always use callback refs. Read more here.

One more idea to consider for you: Move the checked value of the checkbox fully into the state of the AreRefsAwesomeCheckbox component and use a fully controlled component. That's always better than a ref with bigger predictability and less surprises.

Full code:

const Checkbox = ({myRef, changeInput, checkboxText}) => {
  return (
    <label>
      <input
        type="checkbox"
        ref={myRef}
        onChange={event => changeInput(event)}
      />
      <div> {checkboxText} </div>
    </label>
  )
}

export default class AreRefsAwesomeCheckbox extends Component {
  constructor(props) {
    super(props)
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  handleInputChange() {
    let data = {
      isFeatured: this.refs.check_me.checked,
    }

    postJSON('/some/url', data)
  }

  componentDidMount() {
    const data = getJSON('/some/url')
    data.then(object => {
      // this.checkbox is the reference to the checkbox element you need
      this.checkbox.checked = object.will_i_have_a_nice_checkbox
    })
  }

  render() {
    return (
      <div>
        <label>
          <Checkbox myRef={ref => (this.checkbox = ref)} />

          <div>Are refs good?</div>
        </label>
      </div>
    )
  }
}


问:
Fixing PlatformNotSupportedException when referencing System.Data.SqlClient from C# Azure Function
I am creating an Azure Function in C# using a target framework of netstandard2.0 in a Windows 10 environment. The function calls a method that's in another class library and that method creates an instance of SqlConnection. When I run the function I get the following exception:

Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception
  while executing function: Functions.RefreshImages --->
  System.Reflection.TargetInvocationException : Exception has been
  thrown by the target of an invocation. --->
  System.PlatformNotSupportedException : System.Data.SqlClient is not
  supported on this platform. at
  System.Data.SqlClient.SqlConnection..ctor(String connectionString)......

Obviously SqlConnection is supported on Windows so I assume there's something else going on here.

答: It looks like this is related to loading a SQL connection via reflection in .NET core (you are running on netstandard2.0 but the principle should still be the same).


问:
TSQL - How to URL Encode
Looking for a bug free tested sql script that i could use in a UDF to encode a url through sql.  Function would take in a URL and pass out a URL Encoded URL.  I have seen a few, but all i have come across seem to have some flaws.</p>

答:
Daniel Hutmacher from SQL Sunday has provided a nice function.

https://sqlsunday.com/2013/04/07/url-encoding-function/

```<code>CREATE FUNCTION dbo.fn_char2hex(@char char(1))
RETURNS char(2)
AS BEGIN

    DECLARE @hex char(2), @dec int;
    SET @dec=ASCII(@char);
    SET @hex= --- First hex digit:
             SUBSTRING('0123456789ABCDEF', 1+(@dec-@dec%16)/16, 1)+
              --- Second hex digit:
             SUBSTRING('0123456789ABCDEF', 1+(     @dec%16)   , 1);
    RETURN(@hex);
END

CREATE FUNCTION dbo.fn_UrlEncode(@string varchar(max))
RETURNS varchar(max)
AS BEGIN
    DECLARE @offset int, @char char(1);
    SET @string = REPLACE(@string, '%', '%' + dbo.fn_Char2Hex('%'));
    SET @offset=PATINDEX('%[^A-Z0-9.\-\%]%', @string);
    WHILE (@offset!=0) BEGIN;
        SET @char = SUBSTRING(@string, @offset, 1);
        SET @string = REPLACE(@string, @char, '%' + dbo.fn_Char2Hex(@char));
        SET @offset = PATINDEX('%[^A-Z0-9.\-\%]%', @string);
    END
    RETURN @string;
END;
</code>```

Title: TSQL - How to URL Encode

Body:
Daniel Hutmacher from SQL Sunday has provided a nice function.

https://sqlsunday.com/2013/04/07/url-encoding-function/

CREATE FUNCTION dbo.fn_char2hex(@char char(1))
RETURNS char(2)
AS BEGIN

    DECLARE @hex char(2), @dec int;
    SET @dec=ASCII(@char);
    SET @hex= --- First hex digit:
             SUBSTRING('0123456789ABCDEF', 1+(@dec-@dec%16)/16, 1)+
              --- Second hex digit:
             SUBSTRING('0123456789ABCDEF', 1+(     @dec%16)   , 1);
    RETURN(@hex);
END

CREATE FUNCTION dbo.fn_UrlEncode(@string varchar(max))
RETURNS varchar(max)
AS BEGIN
    DECLARE @offset int, @char char(1);
    SET @string = REPLACE(@string, '%', '%' + dbo.fn_Char2Hex('%'));
    SET @offset=PATINDEX('%[^A-Z0-9.\-\%]%', @string);
    WHILE (@offset!=0) BEGIN;
        SET @char = SUBSTRING(@string, @offset, 1);
        SET @string = REPLACE(@string, @char, '%' + dbo.fn_Char2Hex(@char));
        SET @offset = PATINDEX('%[^A-Z0-9.\-\%]%', @string);
    END
    RETURN @string;
END;

ContentLicense: CC BY-SA 4.0


问:
When we have page fault in demand paging , where do we get the faulty page from? From the Backing store or from the virtual memory?
I'm confused between the difference of backing store and virtual memory. Currently studying memory management in OS</p>

答:
Generally, the term "backing store" refers to bitmapped displays. I've never seen it used with virtual memory.

In a virtual memory system, every page of the process address space region has a disk mapping somewhere. That is a prerequisite. That disk image of the process is the "virtual memory." That is where the page is loaded from.


问:
GemFire PDX Serialization not working with OQL in Pulse or with REST APIs?
We are using Spring as client to work with GemFire. Our data is getting saved to Regions of our running GemFire instances.

We are able to get data via Spring when we make get request.

Have done all configuration for Auto PDX serialization, However when we try to query data via OQL in Pulse or with GemFire REST Apis we get ClassNotFoundException:

```<code>{"message" : "Server has encountered while executing Adhoc query!", "stackTrace" : "com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException: Server has encountered while executing Adhoc query!
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:672)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:82)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.gemstone.gemfire.SerializationException: A ClassNotFoundException was thrown while trying to deserialize cached value.
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1561)
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1546)
at com.gemstone.gemfire.internal.cache.VMCachedDeserializable.getDeserializedValue(VMCachedDeserializable.java:124)
at com.gemstone.gemfire.internal.cache.LocalRegion.getDeserialized(LocalRegion.java:1275)
at com.gemstone.gemfire.internal.cache.LocalRegion$NonTXEntry.getValue(LocalRegion.java:9140)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.moveNext(EntriesSet.java:183)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.<init>(EntriesSet.java:121)
at com.gemstone.gemfire.internal.cache.EntriesSet.iterator(EntriesSet.java:85)
at com.gemstone.gemfire.cache.query.internal.ResultsCollectionWrapper.iterator(ResultsCollectionWrapper.java:181)
at com.gemstone.gemfire.cache.query.internal.QRegion.iterator(QRegion.java:225)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doNestedIterations(CompiledSelect.java:712)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doIterationEvaluate(CompiledSelect.java:577)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.evaluate(CompiledSelect.java:284)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.executeUsingContext(DefaultQuery.java:529)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:365)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:303)
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:180)
... 40 more
Caused by: java.lang.ClassNotFoundException: in.cycorax.User
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
</code>```

答:
It looks like the query is trying to deserialize in.cycorax.User object, but that class is not present in the server's classpath.

What is your query? With PDX you should be able to query fields of your values without the objects needing to be deserialized on the server.

But if your query invokes a method on your object or tries to read a field that isn't part of the PDX serialized data (maybe even a misspelled field!), then gemfire will try to deserialize your object and see if it can invoke that method or find that field on the object.

So, you can either change your query so that it doesn't require deserialization, or you can add your classes to the server's classpath.

Body:
We are using Spring as client to work with GemFire. Our data is getting saved to Regions of our running GemFire instances.

We are able to get data via Spring when we make get request.

Have done all configuration for Auto PDX serialization, However when we try to query data via OQL in Pulse or with GemFire REST Apis we get ClassNotFoundException:

{"message" : "Server has encountered while executing Adhoc query!", "stackTrace" : "com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException: Server has encountered while executing Adhoc query!
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:672)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:82)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.gemstone.gemfire.SerializationException: A ClassNotFoundException was thrown while trying to deserialize cached value.
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1561)
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1546)
at com.gemstone.gemfire.internal.cache.VMCachedDeserializable.getDeserializedValue(VMCachedDeserializable.java:124)
at com.gemstone.gemfire.internal.cache.LocalRegion.getDeserialized(LocalRegion.java:1275)
at com.gemstone.gemfire.internal.cache.LocalRegion$NonTXEntry.getValue(LocalRegion.java:9140)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.moveNext(EntriesSet.java:183)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.<init>(EntriesSet.java:121)
at com.gemstone.gemfire.internal.cache.EntriesSet.iterator(EntriesSet.java:85)
at com.gemstone.gemfire.cache.query.internal.ResultsCollectionWrapper.iterator(ResultsCollectionWrapper.java:181)
at com.gemstone.gemfire.cache.query.internal.QRegion.iterator(QRegion.java:225)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doNestedIterations(CompiledSelect.java:712)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doIterationEvaluate(CompiledSelect.java:577)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.evaluate(CompiledSelect.java:284)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.executeUsingContext(DefaultQuery.java:529)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:365)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:303)
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:180)
... 40 more
Caused by: java.lang.ClassNotFoundException: in.cycorax.User
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)


问:
How are people handling user authentication for web services?
I'm creating a web service to expose some data via publicly accessible APIs. At a high level, what mechanisms are people using to secure their APIs to ensure that a valid, authenticated user is making the call?

The service will be C#, the consumer could be anything (Facebook or iPhone app as well as a website) so Microsoft only solutions are out.

It's not a new problem so I assume there are some standard practices in place to deal with it but my google-fu is failing me on this one. Can the collective point me to any resources? Thanks.

答:
You can still use Membership authentication: have a web service method Login(username, password), inside that method validate user:

```<code>[WebMethod]
public bool Login( string username, string password)
{
    bool isValid = Membership.ValidateUser(username, password);
    if (isValid)
    {
        FormsAuthentication.SetAuthCookie(username, true);
        return true;
    }
    return false;
}
</code>```

And that should do it - it will create a cookie that travels with requests and in each method you can check HttpContext.Current.User.IsAuthenticated.

```<code>void SomeWebMethodThatRequiresAuthentication(someparameter)
{
    if (HttpContect.Current.User.IsAuthenticated)
    {
        ... do whatever you need - user is logged in ...
    }
    else
    {
        .... optionally let user know he is not logged in ...
    }
}
</code>```

I believe it can work with different consumers that support cookies because all it needs to work is for consumer to send the auth cookie along with the request to your web server.

Body:
You can still use Membership authentication: have a web service method Login(username, password), inside that method validate user:

[WebMethod]
public bool Login( string username, string password)
{
    bool isValid = Membership.ValidateUser(username, password);
    if (isValid)
    {
        FormsAuthentication.SetAuthCookie(username, true);
        return true;
    }
    return false;
}

And that should do it - it will create a cookie that travels with requests and in each method you can check HttpContext.Current.User.IsAuthenticated.

void SomeWebMethodThatRequiresAuthentication(someparameter)
{
    if (HttpContect.Current.User.IsAuthenticated)
    {
        ... do whatever you need - user is logged in ...
    }
    else
    {
        .... optionally let user know he is not logged in ...
    }
}

I believe it can work with different consumers that support cookies because all it needs to work is for consumer to send the auth cookie along with the request to your web server.


问:
How to change jQuery panel href?
I have an  record with an href to a panel. In differing states, I would like the button to open different panels.  I've tried changing the href, but that doesn't appear to be enough, as the button always opens the original panel.

The a record is defined like this ...

```<code>  <li><a href="#panel1" id="Xpanel" class="icon fa-crop"> </a>
</code>```

When clicked, panel1 is displayed and works great ...

I'm changing the href for the a record like so ...

```<code>   var id = document.getElementById('Xpanel');
   $(id).attr('href', "#panel2");
</code>```

In the Safari debugger, I can see that all is changing, but the button always opens the original #panel1.

Do I need to rebind the  records href somehow ???

答:
try this way:</p>

```<code>var id = $('#XPanel');
id.attr('href', "#panel2");
</code>```

Title: How to change jQuery panel href?

Body:
I have an  record with an href to a panel. In differing states, I would like the button to open different panels.  I've tried changing the href, but that doesn't appear to be enough, as the button always opens the original panel.

The a record is defined like this ...

When clicked, panel1 is displayed and works great ...

I'm changing the href for the a record like so ...

   var id = document.getElementById('Xpanel');
   $(id).attr('href', "#panel2");

In the Safari debugger, I can see that all is changing, but the button always opens the original #panel1.

Do I need to rebind the  records href somehow ???

Body:
try this way:

var id = $('#XPanel');
id.attr('href', "#panel2");


问:
convert nsbezierpath to cgpath in xamarin
Does anyone know how to get a CGPath from a NSBezierPath in Xamarin c#? There is a method to do the conversion in ObjC or Swift, but I believe there might be some issue in Xamarin since I couldn't find the mutablepath class.

```<code>private CGPath QuartzPath(NSBezierPath nsPath){
        nint j, numElements;
        CGPath immutablePath = null;
        numElements = nsPath.ElementCount;

        if(numElements > 0){
            CGPath path = new CGPath();
            CGPoint[] points = new CGPoint[] { new CGPoint(0.0f, 0.0f),new CGPoint(0.0f, 0.0f),new CGPoint(0.0f, 0.0f) };
            bool didClosePath = true;

            for (j = 0; j < numElements; j++){
                switch (nsPath.ElementAt(j)){
                    case NSBezierPathElement.MoveTo:
                        path.MoveToPoint(points[0].X, points[0].Y);
                        break;
                    case NSBezierPathElement.LineTo:
                        path.AddLineToPoint(points[0].X, points[0].Y);
                        didClosePath = false;
                        break;
                    case NSBezierPathElement.CurveTo:
                        path.AddCurveToPoint(points[0].X, points[0].Y, points[1].X, points[1].Y, points[2].X, points[2].Y);
                        didClosePath = false;
                        break;
                    case NSBezierPathElement.ClosePath:
                        path.CloseSubpath();
                        didClosePath = true;
                        break;
                }
            }
            if(!didClosePath){
                path.CloseSubpath();
            }
            immutablePath = path.Copy();
        }
        return immutablePath;
    }
</code>```

this is basically my translation. In the original version, "path" variable was declared as mutablepath, but I couldn't find a corresponding class in xamarin. So is it ok to just use ordinary CGPath?

答:
```<code>public static CGPath ToCGPath(this NSBezierPath nsPath)
{
    var cgPath = new CGPath();
    var points = null as CGPoint[];

    for (int i = 0; i < nsPath.ElementCount; i++)
    {
        var type = nsPath.ElementAt(i, out points);

        switch (type)
        {
            case NSBezierPathElement.MoveTo:
                cgPath.MoveToPoint(points[0]);
                break;

            case NSBezierPathElement.LineTo:
                cgPath.AddLineToPoint(points[0]);
                break;

            case NSBezierPathElement.CurveTo:
                cgPath.AddCurveToPoint(cp1: points[0], cp2: points[1], point: points[2]);
                break;

            case NSBezierPathElement.ClosePath:
                cgPath.CloseSubpath();
                break;
        }
    }

    return cgPath;
}
</code>```

Body:
Does anyone know how to get a CGPath from a NSBezierPath in Xamarin c#? There is a method to do the conversion in ObjC or Swift, but I believe there might be some issue in Xamarin since I couldn't find the mutablepath class.

private CGPath QuartzPath(NSBezierPath nsPath){
        nint j, numElements;
        CGPath immutablePath = null;
        numElements = nsPath.ElementCount;

        if(numElements > 0){
            CGPath path = new CGPath();
            CGPoint[] points = new CGPoint[] { new CGPoint(0.0f, 0.0f),new CGPoint(0.0f, 0.0f),new CGPoint(0.0f, 0.0f) };
            bool didClosePath = true;

            for (j = 0; j < numElements; j++){
                switch (nsPath.ElementAt(j)){
                    case NSBezierPathElement.MoveTo:
                        path.MoveToPoint(points[0].X, points[0].Y);
                        break;
                    case NSBezierPathElement.LineTo:
                        path.AddLineToPoint(points[0].X, points[0].Y);
                        didClosePath = false;
                        break;
                    case NSBezierPathElement.CurveTo:
                        path.AddCurveToPoint(points[0].X, points[0].Y, points[1].X, points[1].Y, points[2].X, points[2].Y);
                        didClosePath = false;
                        break;
                    case NSBezierPathElement.ClosePath:
                        path.CloseSubpath();
                        didClosePath = true;
                        break;
                }
            }
            if(!didClosePath){
                path.CloseSubpath();
            }
            immutablePath = path.Copy();
        }
        return immutablePath;
    }

this is basically my translation. In the original version, "path" variable was declared as mutablepath, but I couldn't find a corresponding class in xamarin. So is it ok to just use ordinary CGPath?


问:
Converting user input to uppercase
I am attempting to create a program in Unix that accesses a data file, adding, deleting, and searching within the file for names and usernames. With this if statement, I am attempting to allow the user to search for data in the file by the first field.

All of the data in the file uses uppercase letters, so I first must convert any text the user input from lowercase to uppercase letters. For some reason, this code is not working with both converting to uppercase and searching and printing the data.

How can I fix it?

```<code>if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        tput cup 3 12
        echo "Enter the first name of the user you would like to search for: "
        tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
        echo "$search"
        awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }'
        capstonedata.txt
fi
</code>```

答:
This: read search | tr '[a-z]' '[A-Z]' will not assign anything to variable search.

It should be something like

```<code>read input
search=$( echo "$input" | tr '[a-z]' '[A-Z]' )
</code>```

and it is better to use parameter expansion for case modification:

```<code>read input
search=${input^^}
</code>```

Title: Converting user input to uppercase

Body:
I am attempting to create a program in Unix that accesses a data file, adding, deleting, and searching within the file for names and usernames. With this if statement, I am attempting to allow the user to search for data in the file by the first field.

All of the data in the file uses uppercase letters, so I first must convert any text the user input from lowercase to uppercase letters. For some reason, this code is not working with both converting to uppercase and searching and printing the data.

How can I fix it?

if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        tput cup 3 12
        echo "Enter the first name of the user you would like to search for: "
        tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
        echo "$search"
        awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }'
        capstonedata.txt
fi

Body:
This: read search | tr '[a-z]' '[A-Z]' will not assign anything to variable search.

It should be something like

read input
search=$( echo "$input" | tr '[a-z]' '[A-Z]' )

and it is better to use parameter expansion for case modification:

read input
search=${input^^}


问:
why cannot I get the value from the dictionary?
There is a dictionary called garden.fruit

```<code>garden.fruits = {"fruit" : "apple"}
</code>```

And now I want to get the value of the key "fruit" from dictionary.
The code is below

```<code>#!/usr/bin/python
#-*-coding:utf-8 -*-
garden.fruits = {"fruit" : "apple"}
print garden.fruits['fruit']
</code>```

But I get a name error

```<code>NameError: name 'garden' is not defined
</code>```

I know the variation name should not include the dot, but what if I want use this variation name and get the value from the dictionary? Thanks

答:
The . would only be used if you had previously imported the file or package garden into the current namespace. For instance:

In garden.py:

```<code>fruits = {"fruit" : "apple"}
</code>```

In main.py:

```<code>import garden
print garden.fruits['fruit']
</code>```

However, if you are not importing the file or package garden, you cannot use .. Instead, declare fruits:

```<code>fruits = {"fruit" : "apple"}
print(fruits['fruit'])
</code>```

Body:
There is a dictionary called garden.fruit

garden.fruits = {"fruit" : "apple"}

And now I want to get the value of the key "fruit" from dictionary.
The code is below

#!/usr/bin/python
#-*-coding:utf-8 -*-
garden.fruits = {"fruit" : "apple"}
print garden.fruits['fruit']

But I get a name error

NameError: name 'garden' is not defined

I know the variation name should not include the dot, but what if I want use this variation name and get the value from the dictionary? Thanks

Body:
The . would only be used if you had previously imported the file or package garden into the current namespace. For instance:

In garden.py:

fruits = {"fruit" : "apple"}

In main.py:

import garden
print garden.fruits['fruit']

However, if you are not importing the file or package garden, you cannot use .. Instead, declare fruits:

fruits = {"fruit" : "apple"}
print(fruits['fruit'])


问:
Errors "Undefined offset" and "invalid byte sequence for encoding UTF8" while managing data with PHP fgetcsv() function
I need to read some data from a .csv file encoded as ISO-8859-1 and putting it's content in a PostgreSQL database encoded as UTF-8, and I'm getting two errors, depending on the row of the file I'm dealing.

I'm getting data from the file using fgetcsv() function:

```<code>while (($line = fgetcsv($handle,0,';','"')) !== false) {
</code>```

The errors are "Undefined offset" on a line where I call a function like this:

```<code>$foo = my_function($file_line[$index]);
</code>```

The error "invalid byte sequence for encoding UTF8" occurs when I try to insert data into my PostgreSQL table.

The file contains complex data, including date fields, number fields and multi-line text fields with special characters and accents and all lines have all fields even if empty.

答:
The error "undefined offset" was happenig because the array didn't have the index informed. But it should have (all file lines has all fields).

The real problem was in the fgetcsv function, I didn't set an "escape character" and in the text there was a slash (the default escape character) in the end of a field, this was making the fgetcsv function not to consider the delimiter character, messing up with the array data.

This was solved by setting an unusual  character as "escape chararcter", like this:

```<code>while (($line = fgetcsv($handle,0,';','"','')) !== false) {
</code>```

The "invalid byte sequence for encoding UTF8" error was solved by removing all unconventional characters from data and then convert to UTF-8 with these commands:

```<code>$field_content = preg_replace('/[^\x{0020}-\x{007E}\x{00c0}-\x{00fd}\x{000a}\x{0009}]/', '',$field_content);
$field_content = utf8_encode($field_content);
</code>```

Body:
I need to read some data from a .csv file encoded as ISO-8859-1 and putting it's content in a PostgreSQL database encoded as UTF-8, and I'm getting two errors, depending on the row of the file I'm dealing.

I'm getting data from the file using fgetcsv() function:

while (($line = fgetcsv($handle,0,';','"')) !== false) {

The errors are "Undefined offset" on a line where I call a function like this:

$foo = my_function($file_line[$index]);

The error "invalid byte sequence for encoding UTF8" occurs when I try to insert data into my PostgreSQL table.

The file contains complex data, including date fields, number fields and multi-line text fields with special characters and accents and all lines have all fields even if empty.

Body:
The error "undefined offset" was happenig because the array didn't have the index informed. But it should have (all file lines has all fields).

The real problem was in the fgetcsv function, I didn't set an "escape character" and in the text there was a slash (the default escape character) in the end of a field, this was making the fgetcsv function not to consider the delimiter character, messing up with the array data.

This was solved by setting an unusual  character as "escape chararcter", like this:

while (($line = fgetcsv($handle,0,';','"','')) !== false) {

The "invalid byte sequence for encoding UTF8" error was solved by removing all unconventional characters from data and then convert to UTF-8 with these commands:

$field_content = preg_replace('/[^\x{0020}-\x{007E}\x{00c0}-\x{00fd}\x{000a}\x{0009}]/', '',$field_content);
$field_content = utf8_encode($field_content);


问:
No output on screen. When I'm reading file it's not giving output
```<code>import time

name = open('list.txt','a+')
print ("When file was opened the pointer was at", name.tell())
name.write('It\'s all about mindset.')
time.sleep(2)
print ("Writing your script.... Wait for some time...")
name.close()
name = open('list.txt','r')
string = name.read(0)
print('Final output is:'`
print (string)
name.close()
</code>```

I am currently learning python file operations. The above code is not working properly. It's not reading the file.

答:
Just remove 0 from string = name.read(0) to show all or write a number bigger than 0.
that's the length of characters should be shown.

Body:
import time

name = open('list.txt','a+')
print ("When file was opened the pointer was at", name.tell())
name.write('It\'s all about mindset.')
time.sleep(2)
print ("Writing your script.... Wait for some time...")
name.close()
name = open('list.txt','r')
string = name.read(0)
print('Final output is:'`
print (string)
name.close()

I am currently learning python file operations. The above code is not working properly. It's not reading the file.


问:
Rails scan for forward slash
I am looking to find forward slash tags in posts to my website. How can I use scan in Rails to do this? This should get the / then the words following. For instance it would be "This is my message /slash" and I am looking to scan for /slash.

```<code>@forward_slashes ||= message.scan( )
</code>```

答:
what about:</p>

```<code>"This is my message /slash".split('/')
</code>```

Title: Rails scan for forward slash

Body:
I am looking to find forward slash tags in posts to my website. How can I use scan in Rails to do this? This should get the / then the words following. For instance it would be "This is my message /slash" and I am looking to scan for /slash.

@forward_slashes ||= message.scan( )

Body:
what about:

"This is my message /slash".split('/')


问:
I filtered an NSMutableArray of Dictionaries and then I want to filter for a Key again
```<code>var str = "Hello, playground"
var dataArray : NSMutableArray = []
var sum = 0.00

func addNewIncomeRecord(_ id: String, date: String, description: String, amount: Double, currency: String, category: String, notes: String) {
    let dict = ["id" : id, "date" : date, "description" : description, "amount" : amount, "currency" : currency, "category" : category, "notes" : notes] as [AnyHashable : Any]

    dataArray.add(dict)
}

addNewIncomeRecord("1", date: "11-25", description: "Money", amount: 20.00, currency: "EUR", category: "Home", notes: "More Money")
addNewIncomeRecord("2", date: "11-25", description: "Rent", amount: 50.00, currency: "EUR", category: "Home", notes: "Rent Money")
addNewIncomeRecord("3", date: "11-25", description: "Hair", amount: 10.00, currency: "EUR", category: "Medical"  ,notes: "HairCut")

let homeValue = NSPredicate(format: "category == %@", "Home")
let filteredArray = (dataArray as NSMutableArray).filtered(using: homeValue)
print(filteredArray)
</code>```

I filtered all Arrays of the "Home" category. But now I want filter the filteredArray again for the amounts. So that only the amounts of the two (Home Arrays) be in an extra Array.

答:
Don't use NSArray or NSMutableArray in Swift. Use Swift native arrays (and dictionaries).

Once you do that, there is no need for NSPredicate. Use the filter method.

Don't use a dictionary to hold your data. Create a struct with the needed fields.

First, without creating a struct, here's a simply solution using native arrays:

```<code>var dataArray = [[String:Any]]()
var sum = 0.00

func addNewIncomeRecord(_ id: String, date: String, description: String, amount: Double, currency: String, category: String, notes: String) {
    let dict: [String:Any] = ["id" : id, "date" : date, "description" : description, "amount" : amount, "currency" : currency, "category" : category, "notes" : notes]

    dataArray.append(dict)
}

addNewIncomeRecord("1", date: "11-25", description: "Money", amount: 20.00, currency: "EUR", category: "Home", notes: "More Money")
addNewIncomeRecord("2", date: "11-25", description: "Rent", amount: 50.00, currency: "EUR", category: "Home", notes: "Rent Money")
addNewIncomeRecord("3", date: "11-25", description: "Hair", amount: 10.00, currency: "EUR", category: "Medical"  ,notes: "HairCut")

let filteredArray = dataArray.filter { $0["category"] as? String == "Home" }
let amounts = filteredArray.flatMap { $0["amount"] as? Double }
print(amounts)
</code>```

Here's the solution making use of a struct.

```<code>struct Income {
    let id: String
    let date: String
    let description: String
    let amount: Double
    let currency: String
    let category: String
    let notes: String
}

var dataArray = [Income]()
var sum = 0.00

func addNewIncomeRecord(_ id: String, date: String, description: String, amount: Double, currency: String, category: String, notes: String) {
    let income = Income(id: id, date: date, description: description, amount: amount, currency: currency, category: category, notes: notes)

    dataArray.append(income)
}

addNewIncomeRecord("1", date: "11-25", description: "Money", amount: 20.00, currency: "EUR", category: "Home", notes: "More Money")
addNewIncomeRecord("2", date: "11-25", description: "Rent", amount: 50.00, currency: "EUR", category: "Home", notes: "Rent Money")
addNewIncomeRecord("3", date: "11-25", description: "Hair", amount: 10.00, currency: "EUR", category: "Medical"  ,notes: "HairCut")

let filteredArray = dataArray.filter { $0.category == "Home" }
let amounts = filteredArray.map { $0.amount }
print(amounts)
</code>```

Using a struct has many advantages. It's type safe for each field. You can make it Codable which makes it a lot easier to save and read from a file.

Body:
var str = "Hello, playground"
var dataArray : NSMutableArray = []
var sum = 0.00

func addNewIncomeRecord(_ id: String, date: String, description: String, amount: Double, currency: String, category: String, notes: String) {
    let dict = ["id" : id, "date" : date, "description" : description, "amount" : amount, "currency" : currency, "category" : category, "notes" : notes] as [AnyHashable : Any]

    dataArray.add(dict)
}

addNewIncomeRecord("1", date: "11-25", description: "Money", amount: 20.00, currency: "EUR", category: "Home", notes: "More Money")
addNewIncomeRecord("2", date: "11-25", description: "Rent", amount: 50.00, currency: "EUR", category: "Home", notes: "Rent Money")
addNewIncomeRecord("3", date: "11-25", description: "Hair", amount: 10.00, currency: "EUR", category: "Medical"  ,notes: "HairCut")

let homeValue = NSPredicate(format: "category == %@", "Home")
let filteredArray = (dataArray as NSMutableArray).filtered(using: homeValue)
print(filteredArray)

I filtered all Arrays of the "Home" category. But now I want filter the filteredArray again for the amounts. So that only the amounts of the two (Home Arrays) be in an extra Array.

Body:
Don't use NSArray or NSMutableArray in Swift. Use Swift native arrays (and dictionaries).

Once you do that, there is no need for NSPredicate. Use the filter method.

Don't use a dictionary to hold your data. Create a struct with the needed fields.

First, without creating a struct, here's a simply solution using native arrays:

var dataArray = [[String:Any]]()
var sum = 0.00

func addNewIncomeRecord(_ id: String, date: String, description: String, amount: Double, currency: String, category: String, notes: String) {
    let dict: [String:Any] = ["id" : id, "date" : date, "description" : description, "amount" : amount, "currency" : currency, "category" : category, "notes" : notes]

    dataArray.append(dict)
}

addNewIncomeRecord("1", date: "11-25", description: "Money", amount: 20.00, currency: "EUR", category: "Home", notes: "More Money")
addNewIncomeRecord("2", date: "11-25", description: "Rent", amount: 50.00, currency: "EUR", category: "Home", notes: "Rent Money")
addNewIncomeRecord("3", date: "11-25", description: "Hair", amount: 10.00, currency: "EUR", category: "Medical"  ,notes: "HairCut")

let filteredArray = dataArray.filter { $0["category"] as? String == "Home" }
let amounts = filteredArray.flatMap { $0["amount"] as? Double }
print(amounts)

Here's the solution making use of a struct.

struct Income {
    let id: String
    let date: String
    let description: String
    let amount: Double
    let currency: String
    let category: String
    let notes: String
}

var dataArray = [Income]()
var sum = 0.00

func addNewIncomeRecord(_ id: String, date: String, description: String, amount: Double, currency: String, category: String, notes: String) {
    let income = Income(id: id, date: date, description: description, amount: amount, currency: currency, category: category, notes: notes)

    dataArray.append(income)
}

addNewIncomeRecord("1", date: "11-25", description: "Money", amount: 20.00, currency: "EUR", category: "Home", notes: "More Money")
addNewIncomeRecord("2", date: "11-25", description: "Rent", amount: 50.00, currency: "EUR", category: "Home", notes: "Rent Money")
addNewIncomeRecord("3", date: "11-25", description: "Hair", amount: 10.00, currency: "EUR", category: "Medical"  ,notes: "HairCut")

let filteredArray = dataArray.filter { $0.category == "Home" }
let amounts = filteredArray.map { $0.amount }
print(amounts)

Using a struct has many advantages. It's type safe for each field. You can make it Codable which makes it a lot easier to save and read from a file.


问:
JQuery cycle plugin not working
I am trying to add jquery Cycle slideshow plugin to my page with 'fade' transition effect. But still I couldn't make it to work.

This is my html :

```<code><div class="container">
    <div class="slide1">
         <blockquote>
            <span class="leftquotes">“</span> He promptly completed the task at hand and communicates really well till the project reaches the finishing line. I was pleased with his creative design and will definitely be hiring him again. <span class="rightquotes">„ </span>
         </blockquote>
         <img src="images/profile.jpg" width="120" height="100" />
         <h2>Steve Kruger</h2>
         <h6>UI/UX Designer at Woof Design Studio</h6>
         <div class="slide1bottom"></div>
    </div>

    <div class="slide2">
        <blockquote>
            <span class="leftquotes">“</span> Till the project reaches the finishing line. I recommend him to anyone who wants their work done professionally. project reaches the finishing line. I recommend him to anyone who wants their work done professionally. The project ... <a href="#"> read more</a><span class="rightquotes">„ </span>
        </blockquote>
        <img src="images/images.jpg" width="120" height="100" />
        <h2>John Doe</h2>
        <h6>Developer Relations at Woof Studios</h6>
        <div class="slide2bottom"></div>
    </div>

    <div class="slide3">
        <blockquote>
            <span class="leftquotes "> “</span> He promptly completed the task at hand and communicates really well till the project reaches the finishing line. I was pleased with his creative design and will definitely be hiring him again. <span class="rightquotes">„ </span>
        </blockquote>
        <img src="images/summer_school.png" width="120" height="100" />
        <h2>Steve Stevenson</h2>
        <h6>CEO Woof Web Design Studios</h6>
        <div class="slide3bottom"></div>
    </div>
</div>
</code>```

This is my JQuery :

```<code>$(function() {
    $('#container').cycle();
});
</code>```

I have imported JQuery plugin, cycle plugin and easing plugin to my page properly.

```<code><script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery.color.js"></script>
<script type="text/javascript" src="js/jquery.cycle.all.min.js"></script>
<script type="text/javascript" src="jscript/jquery.easing.1.3.js"></script>
</code>```

This is my fiddle : http://jsfiddle.net/kRZ5r/

答:
In the html code you mention a container as a class. but in the JQuery you use # to define it as a id. </p>

```<code><div class="container">
</div>

$(function() {
    $('.container').cycle();
});
</code>```

Title: JQuery cycle plugin not working

Body:
I am trying to add jquery Cycle slideshow plugin to my page with 'fade' transition effect. But still I couldn't make it to work.

This is my html :

            “ He promptly completed the task at hand and communicates really well till the project reaches the finishing line. I was pleased with his creative design and will definitely be hiring him again. „

Steve Kruger

UI/UX Designer at Woof Design Studio

            “ Till the project reaches the finishing line. I recommend him to anyone who wants their work done professionally. project reaches the finishing line. I recommend him to anyone who wants their work done professionally. The project ...  read more„

John Doe

Developer Relations at Woof Studios

             “ He promptly completed the task at hand and communicates really well till the project reaches the finishing line. I was pleased with his creative design and will definitely be hiring him again. „

Steve Stevenson

CEO Woof Web Design Studios

This is my JQuery :

$(function() {
    $('#container').cycle();
});

I have imported JQuery plugin, cycle plugin and easing plugin to my page properly.

This is my fiddle : http://jsfiddle.net/kRZ5r/

Body:
In the html code you mention a container as a class. but in the JQuery you use # to define it as a id.

<div class="container">
</div>

$(function() {
    $('.container').cycle();
});


问:
Firebase Rules with facebook Authentication and Unique IDs
I'm looking for some advice or a possible solution with tightening up my firebase rules.

This is my user tree in Firebase:

```<code>users
    |_male
         |_uid

    |_female
         |_uid
</code>```

The UID will be an epoch timestamp when the account is created which will be a signed integer.

These are the firebase rules which basically ensures the user has logged in and authenticated with Facebook before they can read or write to users:

```<code>"users": {
       "male":{
          ".indexOn": ["uid"]
       },
       "female":{
         ".indexOn": ["uid"]
       },
       ".read": "auth != null  && auth.provider === 'facebook'",
       ".write": "auth != null && auth.provider === 'facebook'"
},
</code>```

I only want users to read/write to their tree, for example:

```<code>users->male->uid->1233254...
</code>```

I'm afraid with my rules above, they could potentially read and write from/to another users tree.

It would be great if I could compare the app UID with the Facebook UID.
I do capture this detail in another tree on the database e.g:

```<code>user_fbuid
         |_fbuid
               |_facebook:a1244dxs
                                 |_uid
</code>```

I do have better rules here that check against auth.uid:

```<code>"user_fbuid": {
      "fbuid":{
        "$fbuid": {
          ".indexOn": ["fbuid"],
          ".read": "$fbuid === auth.uid && auth.provider === 'facebook'",
          ".write": "$fbuid === auth.uid && auth.provider === 'facebook'"
       }
   },
},
</code>```

If anyone has any ideas, I'd love to hear. Thanks

答:
I ended up using the facebook id attribute as my own uid and the rules below:</p>

```<code>"$uid": {
          // only the user can read and write to their tree
          ".read": "auth != null  && auth.provider === 'facebook' && auth.token.firebase.identities['facebook.com'][0] === $uid",
            ".write": "auth != null  && auth.provider === 'facebook' && auth.token.firebase.identities['facebook.com'][0] === $uid"
        },
</code>```

Body:
I'm looking for some advice or a possible solution with tightening up my firebase rules.

This is my user tree in Firebase:

users
    |_male
         |_uid

    |_female
         |_uid

The UID will be an epoch timestamp when the account is created which will be a signed integer.

These are the firebase rules which basically ensures the user has logged in and authenticated with Facebook before they can read or write to users:

"users": {
       "male":{
          ".indexOn": ["uid"]
       },
       "female":{
         ".indexOn": ["uid"]
       },
       ".read": "auth != null  && auth.provider === 'facebook'",
       ".write": "auth != null && auth.provider === 'facebook'"
},

I only want users to read/write to their tree, for example:

users->male->uid->1233254...

I'm afraid with my rules above, they could potentially read and write from/to another users tree.

It would be great if I could compare the app UID with the Facebook UID.
I do capture this detail in another tree on the database e.g:

user_fbuid
         |_fbuid
               |_facebook:a1244dxs
                                 |_uid

I do have better rules here that check against auth.uid:

"user_fbuid": {
      "fbuid":{
        "$fbuid": {
          ".indexOn": ["fbuid"],
          ".read": "$fbuid === auth.uid && auth.provider === 'facebook'",
          ".write": "$fbuid === auth.uid && auth.provider === 'facebook'"
       }
   },
},

If anyone has any ideas, I'd love to hear. Thanks

Body:
I ended up using the facebook id attribute as my own uid and the rules below:

"$uid": {
          // only the user can read and write to their tree
          ".read": "auth != null  && auth.provider === 'facebook' && auth.token.firebase.identities['facebook.com'][0] === $uid",
            ".write": "auth != null  && auth.provider === 'facebook' && auth.token.firebase.identities['facebook.com'][0] === $uid"
        },


问:
Monitor a process and capture output with python
I am writing a benchmarking utility using python.  I would like my python program to execute a program and capture the output as well as get its max resource usage.  The following code runs a command and gets its memory and processor usage once per second, but how do I also access the output inside python?  Here is my current setup:</p>

```<code>pid = psutil.Popen(cmd_args, shell=False, stdout=subprocess.PIPE)

p = psutil.Process(pid=pid.pid)
x = 0
cpu_util = []
mem_util = []

while p.status() != "zombie":
    if x % 10 == 0:
        with p.oneshot():
            cpu_util.append(p.cpu_percent())
            mem_util.append(p.memory_percent())
    x += 1
    time.sleep(0.1)

max_cpu_load = max(cpu_util)
max_mem_load = max(mem_util)

#What I would like to do, but don't understand
print(pid.stdout)
</code>```

答:
Assuming you have a Unix box, and you can get the file descriptors of relevant stdin, stdout, ..., you may use the select.select function to monitor the activity on these streams.

https://docs.python.org/3/library/select.html#select.select

Body:
I am writing a benchmarking utility using python.  I would like my python program to execute a program and capture the output as well as get its max resource usage.  The following code runs a command and gets its memory and processor usage once per second, but how do I also access the output inside python?  Here is my current setup:

pid = psutil.Popen(cmd_args, shell=False, stdout=subprocess.PIPE)

p = psutil.Process(pid=pid.pid)
x = 0
cpu_util = []
mem_util = []

while p.status() != "zombie":
    if x % 10 == 0:
        with p.oneshot():
            cpu_util.append(p.cpu_percent())
            mem_util.append(p.memory_percent())
    x += 1
    time.sleep(0.1)

max_cpu_load = max(cpu_util)
max_mem_load = max(mem_util)

#What I would like to do, but don't understand
print(pid.stdout)


问:
mock external system working through websphere mq
I'm developing integration solution with message broker. Solution communicates with the back-end system using websphere mq. During development process I don't have an access to the real back-end service so I have to mock it somehow. Mock implementation has to read message from queue, perform simple transformation, and put message back to queue. To achieve that, I've considered creating separate message flow but what I'm actually looking for is ready-made solution which I could leverage these tasks to.

Does anybody know any tool that might be useful for that purpose?

答:
There are tools that allow for mocking or simulating systems communicating via IBM Websphere MQ.

You can use for example Traffic Parrot. It will read a message from a request queue, do the transformations (using its extensions) and put a response message on a response queue. Have a look at this video that demonstrates how to do it.

Have a look at other API simulation tools, just make sure you choose one that supports IBM MQ.


问:
500 Internal Server Error while using Cloud Firestore in HTTPS Trigger in Cloud Functions

I'm trying to post a piece of data to a certain location in my Cloud Firestore. The Cloud Function itself is toggled via HTTPS. For the request.body I am using the bodyParser.json method.

```<code>notifull.post('/postNote', (request, response) => {

    // grab variables and files from body and query strings
    var subject = request.body.subject;
    var category = request.body.category;
    var subcategory = request.body.subcategory;

    var title = request.body.title;
    var id = request.body.id;
    var userID = request.body.userID;

    // add data to collection
    var referenceString = `${subject}/${category}/${subcategory}/${id}`;

    var reference = admin.firestore().doc(referenceString);

    reference.set({
        "title": title,
        "id": id,
        "userID": userID,
        "timestamp": Date.now(),
        "upvotes": 0
    });

    // update user posts???

});
</code>```

I expect to have a little document in the reference.

Instead what returns is a 500 Internal Server Error.

The error in the the log is "TypeError: admin.firestore is not a function".  I'm using firebase-admin version 4.2.1.

答:
You're using an old version of firebase-admin.  Firestore support wasn't added until very recently.  Install the latest version:

```<code>npm install firebase-admin@latest
</code>```

Also, every HTTPS function should return a response to the client for every possible code path, and only after all the work is complete in the function.

```<code>reference.set({
    "title": title,
    "id": id,
    "userID": userID,
    "timestamp": Date.now(),
    "upvotes": 0
})
.then(() => {
    response.send("OK")
})
.catch(error => {
    response.status(500).send(error)
})
</code>```

Body:
I'm trying to post a piece of data to a certain location in my Cloud Firestore. The Cloud Function itself is toggled via HTTPS. For the request.body I am using the bodyParser.json method.

notifull.post('/postNote', (request, response) => {

    // grab variables and files from body and query strings
    var subject = request.body.subject;
    var category = request.body.category;
    var subcategory = request.body.subcategory;

    var title = request.body.title;
    var id = request.body.id;
    var userID = request.body.userID;

    // add data to collection
    var referenceString = `${subject}/${category}/${subcategory}/${id}`;

    var reference = admin.firestore().doc(referenceString);

    reference.set({
        "title": title,
        "id": id,
        "userID": userID,
        "timestamp": Date.now(),
        "upvotes": 0
    });

    // update user posts???

});

I expect to have a little document in the reference.

Instead what returns is a 500 Internal Server Error.

The error in the the log is "TypeError: admin.firestore is not a function".  I'm using firebase-admin version 4.2.1.

Body:
You're using an old version of firebase-admin.  Firestore support wasn't added until very recently.  Install the latest version:

npm install firebase-admin@latest

Also, every HTTPS function should return a response to the client for every possible code path, and only after all the work is complete in the function.

reference.set({
    "title": title,
    "id": id,
    "userID": userID,
    "timestamp": Date.now(),
    "upvotes": 0
})
.then(() => {
    response.send("OK")
})
.catch(error => {
    response.status(500).send(error)
})


问:
Linking a ComboBox with an ObservableCollection
I am trying to link a combobox with my ObservableCollection, however this does not seem to work, I have looked around and tried other ways that the internet is saying, but I can't seem to get it to work

```<code>public class UserData
{
    public string Key { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Application
    {
        get
        {
            return Text;
        }
    }
    public string Text { get; set; }
    public override string ToString()
    {
        return Text;
    }
}

private static ObservableCollection<UserData> _userdata = new ObservableCollection<UserData>();
    public static ObservableCollection<UserData> Userdata
    {
        get { return _userdata; }
        set { _userdata = value; }
    }
}
</code>```

XAML

```<code><ComboBox
   HorizontalAlignment="Left"
   Height="24"
   Margin="5,3,0,0"
   VerticalAlignment="Top"
   Width="112"
   x:Name="cbApplications"
   DropDownClosed="cbApplications_DropDownClosed"
   ItemsSource="{Binding Path=Userdata}"/>
</code>```

Would anyone be able to support me in this matter?

答:
Get rid of the static, is there a reason for that?
Implement INotifyPropertyChanged in you class.
Then add in your

```<code>set { _userdata = value; OnPropertyChanged("Userdata"); }
</code>```

Also, for cleanliness you should move your Closed command to binding or ICommand unless you are needing to do something UI specific only that has no data content associated.

Let me know if that doesn't fix you.

Also a lot of times I like to make a base class to handle this.

```<code> public abstract class BaseViewModel : INotifyPropertyChanged
{
    //MEMBERS
    public event PropertyChangedEventHandler PropertyChanged;

    //PROPERTIES
    public void OnPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}
</code>```

Then you can call it from your setter like:

OnPropertyChanged();
without any params.

Body:
I am trying to link a combobox with my ObservableCollection, however this does not seem to work, I have looked around and tried other ways that the internet is saying, but I can't seem to get it to work

public class UserData
{
    public string Key { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Application
    {
        get
        {
            return Text;
        }
    }
    public string Text { get; set; }
    public override string ToString()
    {
        return Text;
    }
}

private static ObservableCollection<UserData> _userdata = new ObservableCollection<UserData>();
    public static ObservableCollection<UserData> Userdata
    {
        get { return _userdata; }
        set { _userdata = value; }
    }
}

XAML

<ComboBox
   HorizontalAlignment="Left"
   Height="24"
   Margin="5,3,0,0"
   VerticalAlignment="Top"
   Width="112"
   x:Name="cbApplications"
   DropDownClosed="cbApplications_DropDownClosed"
   ItemsSource="{Binding Path=Userdata}"/>

Would anyone be able to support me in this matter?

Body:
Get rid of the static, is there a reason for that?
Implement INotifyPropertyChanged in you class.
Then add in your

set { _userdata = value; OnPropertyChanged("Userdata"); }

Also, for cleanliness you should move your Closed command to binding or ICommand unless you are needing to do something UI specific only that has no data content associated.

Let me know if that doesn't fix you.

Also a lot of times I like to make a base class to handle this.

 public abstract class BaseViewModel : INotifyPropertyChanged
{
    //MEMBERS
    public event PropertyChangedEventHandler PropertyChanged;

    //PROPERTIES
    public void OnPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

Then you can call it from your setter like:

OnPropertyChanged();
without any params.


问:
Ramda - R.Both with functions taking different number of params
Just learning Ramda and find I keep running into this same scenario.   I have 2 conditional functions that I want to evaluate with R.both.   The twist is that 1 function will require an extra parameter.   Something like:

const condition1 = (y) => y===1;

const condition2 = (x, y) => x===y;

const validator = R.both(condition1, condition2)

Notice that the parms for condition2 are switched.   If I know that x will be applied first this works fine.  But what if it isn't?

Do I:

1)  alter condition1 like const conditionAltered = () => condition1

2)  use some Ramda function to do the same (not sure what that would be)

3)  ????

Looking for a "best practice" type answer.

OK, so as it turns out I completely misunderstood how the R.both operated.   First I thought it would auto-curry the passed in conditions and second I didn't realize it short-circuited.

Given that my (1) should read const conditionAltered = (x, y) => condition1(y)

答:
As Vipin Kumar demonstrates, you can flip the arguments of one function, but if that has the order you would prefer, then you can alter the other function.

```<code>const evenWidth = (width) => width % 2 === 0
const tall = (height, width) => height > width

// (width, height) => boolean
const evenTall = both(evenWidth, flip(tall))

// (height, width) => boolean
const tallEven = both(tall, (_, width) => evenWidth(width))
</code>```

If you really wanted a point-free version of the latter, you could do this instead:

```<code>const tallEven = both(tall, compose(evenWidth, nthArg(1)))
</code>```

But I find the original easier to read.

Body:
As Vipin Kumar demonstrates, you can flip the arguments of one function, but if that has the order you would prefer, then you can alter the other function.

const evenWidth = (width) => width % 2 === 0
const tall = (height, width) => height > width

// (width, height) => boolean
const evenTall = both(evenWidth, flip(tall))

// (height, width) => boolean
const tallEven = both(tall, (_, width) => evenWidth(width))

If you really wanted a point-free version of the latter, you could do this instead:

const tallEven = both(tall, compose(evenWidth, nthArg(1)))

But I find the original easier to read.


问:
How to make a function wait for another to stop executing(Simon Game) javascript
I’m making a Simon Game and I’ve already added the logic but I don’t know how to pause an execution until the player has pressed on a tile. I’ve made a function called user() that records users input and pushes it to the userSeq array. Then I made a function checkTurn() to check who’s turn is next (the computer or the user). If it’s the user’s turn then I want in the else to wait for the user() function to finish and then call the callcheckClicks() to check if user’s input is the same as computer’s and then continue to the new level. Please help!

Here’s a link: https://codepen.io/Teo03/pen/yPvbwY

$(document).ready(function() {
  var green = document.getElementById("green");
  var red = document.getElementById("red");
  var yellow = document.getElementById("yellow");
  var blue = document.getElementById("blue");
  var tile = document.getElementsByClassName("tile");
  //audio for every click
  var audio = [
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3")
  ];
  // record the round
  var round = 0;
  // record the random presses
  var compSeq = [];
  //record user clicks
  var userSeq = [];
  //if it's false computer moves
  var turn = false;
  //round number
  var round = 0;
  //count how many moves user does
  var playerIndex = 0;

  //start
  $(".start").click(function() {
    round++;
    turn = false;
    $("#round")
      .html("Round: " + round)
      .show();
    $(".start, .reset").hide();
    checkTurn();
  });

  function addNewRandomNumber() {
    var random = Math.floor(Math.random() * 4) + 1;
    computer(random);
    console.log("random" + random);
  }

  // call the computer to make an action
  function callComp() {
    addNewRandomNumber();
    enableClicks();
    turn = true;
    checkTurn();
  }

  function callCheckClicks() {
    checkClicks();
  }

  //check every time the user clicks if the user clicks are the same as the computer's
  function checkClicks() {
    console.log("random clicks: " + compSeq);
    //if user guess is correct
    if (userSeq[playerIndex] == compSeq[playerIndex]) {
      if (userSeq[playerIndex].length == compSeq[playerIndex].length) {
        // if they are then it's computer's turn
        callComp();
      } else {
        playerIndex += 1;
        $(".start")
          .html("Next")
          .show();
        // user is right, he can continue inputting another clicks if the sequence has
        checkTurn();
      }
    } else {
      resetUserVariables(); // user is wrong
    }
  }
  //reset playerIndex
  function resetUserVariables() {
    playerIndex = 0;
  }
  //press a random button
  function computer(ran) {
    switch (ran) {
      case 1:
        blink(green);
        audio[0].play();
        compSeq.push(1);
        break;
      case 2:
        blink(red);
        audio[1].play();
        compSeq.push(2);
        break;
      case 3:
        blink(blue);
        audio[2].play();
        compSeq.push(3);
        break;
      case 4:
        blink(yellow);
        audio[3].play();
        compSeq.push(4);
        break;
      default:
        return;
    }
    console.log("random clicks: " + compSeq);
    enableClicks();
    turn = true;
    checkTurn();
  }
  //blink a tile
  function blink(tile) {
    $(tile).fadeOut("slow", function() {
      $(this).fadeIn("slow", function() {
        return;
      });
    });
  }

  //user input
  function user() {
    if ($(this).is("#green")) {
      userSeq.push(1);
      audio[0].play();
      blink(green);
      playerIndex++;
    } else if ($(this).is("#red")) {
      userSeq.push(2);
      audio[1].play();
      blink(red);
      playerIndex++;
    } else if ($(this).is("#blue")) {
      userSeq.push(3);
      audio[2].play();
      blink(blue);
      playerIndex++;
    } else if ($(this).is("#yellow")) {
      userSeq.push(4);
      audio[3].play();
      blink(yellow);
      playerIndex++;
    }
    turn = false;
    checkTurn();
    console.log("user clicks: " + userSeq);
  }

  //add an event listener for user clicks
  function enableClicks() {
    for (var i = 0; i < tile.length; i++) {
      tile[i].addEventListener("click", user, false);
    }
  }
  //disable clicks when is computer's turn
  function disableClicks() {
    for (var i = 0; i < tile.length; i++) {
      tile[i].removeEventListener("click", user, false);
    }
  }
  //check who's turn is next
  function checkTurn() {
    if (turn === false) {
      //call computer
      callComp();
    } else {
      callCheckClicks();
    }
  }
  //document.ready().
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html * {
  text-align: center;
  background-color: #d3d3d3;
}

h1 {
  font-size: 60px;
  padding-bottom: 10px;
}

h3 {
  display: none;
  padding-bottom: 30px;
}

.circle {
  background: #d3d3d3;
  width: 320px;
  height: 320px;
  border-radius: 50%;
  border: 10px solid gray;
  margin: auto;
}

.tile {
  height: 150px;
  width: 150px;
  float: left;
  cursor: pointer;
}

#red {
  background-color: red;
  border-top-right-radius: 100%;
}

#green {
  background-color: green;
  border-top-left-radius: 100%;
}

#blue {
  background-color: blue;
  border-bottom-right-radius: 100%;
}

#yellow {
  background-color: yellow;
  border-bottom-left-radius: 100%;
}

btn {
  padding-top: 40px;
}</code>```

Simon Game

Round:

  Start
  Reset

```

答:
I believe what you are looking for is setTimeout()

This takes 2 parameters, your function and the number of milliseconds.

For example if you want to execute a function after three seconds of an onclick event...

```<code><button onclick="setTimeout(myFunction, 3000);">Try it</button>

<script>
function myFunction() {
    alert('Hello');
}
</script>
</code>```

Then use a promise like explained here:
Javascript - Wait the true ending of a function that uses setTimeout

Another thing to note is the flow of the program.  Currently you are using a checkTurn method that calls a callCheckClicks method that calls a checkClicks and checkClicks calls checkTurn again.  With this your program will end up crashing as it continuously loops forever.  In order to do this you need to activate your if/else within your checkClicks to have

```<code>turn = true;
checkTurn();
</code>```

To look like

```<code>function checkClicks() {
  console.log("random clicks: " + compSeq);
  //if user guess is correct
  if (userSeq[playerIndex] == compSeq[playerIndex]) {
    if (userSeq[playerIndex].length == compSeq[playerIndex].length) {
      // if they are then it's computer's turn
      callComp();
    } else {
      playerIndex += 1;
      $(".start")
        .html("Next")
        .show();

      // user is right, he can continue inputting another clicks if the sequence has
      turn=true;

      checkTurn();

    }
  } else {
    resetUserVariables(); // user is wrong
  }
}
</code>```

Hope this is what you're looking for.

Body:
I’m making a Simon Game and I’ve already added the logic but I don’t know how to pause an execution until the player has pressed on a tile. I’ve made a function called user() that records users input and pushes it to the userSeq array. Then I made a function checkTurn() to check who’s turn is next (the computer or the user). If it’s the user’s turn then I want in the else to wait for the user() function to finish and then call the callcheckClicks() to check if user’s input is the same as computer’s and then continue to the new level. Please help!

Here’s a link: https://codepen.io/Teo03/pen/yPvbwY

$(document).ready(function() {
  var green = document.getElementById("green");
  var red = document.getElementById("red");
  var yellow = document.getElementById("yellow");
  var blue = document.getElementById("blue");
  var tile = document.getElementsByClassName("tile");
  //audio for every click
  var audio = [
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
    new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3")
  ];
  // record the round
  var round = 0;
  // record the random presses
  var compSeq = [];
  //record user clicks
  var userSeq = [];
  //if it's false computer moves
  var turn = false;
  //round number
  var round = 0;
  //count how many moves user does
  var playerIndex = 0;

  //start
  $(".start").click(function() {
    round++;
    turn = false;
    $("#round")
      .html("Round: " + round)
      .show();
    $(".start, .reset").hide();
    checkTurn();
  });

  function addNewRandomNumber() {
    var random = Math.floor(Math.random() * 4) + 1;
    computer(random);
    console.log("random" + random);
  }

  // call the computer to make an action
  function callComp() {
    addNewRandomNumber();
    enableClicks();
    turn = true;
    checkTurn();
  }

  function callCheckClicks() {
    checkClicks();
  }

  //check every time the user clicks if the user clicks are the same as the computer's
  function checkClicks() {
    console.log("random clicks: " + compSeq);
    //if user guess is correct
    if (userSeq[playerIndex] == compSeq[playerIndex]) {
      if (userSeq[playerIndex].length == compSeq[playerIndex].length) {
        // if they are then it's computer's turn
        callComp();
      } else {
        playerIndex += 1;
        $(".start")
          .html("Next")
          .show();
        // user is right, he can continue inputting another clicks if the sequence has
        checkTurn();
      }
    } else {
      resetUserVariables(); // user is wrong
    }
  }
  //reset playerIndex
  function resetUserVariables() {
    playerIndex = 0;
  }
  //press a random button
  function computer(ran) {
    switch (ran) {
      case 1:
        blink(green);
        audio[0].play();
        compSeq.push(1);
        break;
      case 2:
        blink(red);
        audio[1].play();
        compSeq.push(2);
        break;
      case 3:
        blink(blue);
        audio[2].play();
        compSeq.push(3);
        break;
      case 4:
        blink(yellow);
        audio[3].play();
        compSeq.push(4);
        break;
      default:
        return;
    }
    console.log("random clicks: " + compSeq);
    enableClicks();
    turn = true;
    checkTurn();
  }
  //blink a tile
  function blink(tile) {
    $(tile).fadeOut("slow", function() {
      $(this).fadeIn("slow", function() {
        return;
      });
    });
  }

  //user input
  function user() {
    if ($(this).is("#green")) {
      userSeq.push(1);
      audio[0].play();
      blink(green);
      playerIndex++;
    } else if ($(this).is("#red")) {
      userSeq.push(2);
      audio[1].play();
      blink(red);
      playerIndex++;
    } else if ($(this).is("#blue")) {
      userSeq.push(3);
      audio[2].play();
      blink(blue);
      playerIndex++;
    } else if ($(this).is("#yellow")) {
      userSeq.push(4);
      audio[3].play();
      blink(yellow);
      playerIndex++;
    }
    turn = false;
    checkTurn();
    console.log("user clicks: " + userSeq);
  }

  //add an event listener for user clicks
  function enableClicks() {
    for (var i = 0; i < tile.length; i++) {
      tile[i].addEventListener("click", user, false);
    }
  }
  //disable clicks when is computer's turn
  function disableClicks() {
    for (var i = 0; i < tile.length; i++) {
      tile[i].removeEventListener("click", user, false);
    }
  }
  //check who's turn is next
  function checkTurn() {
    if (turn === false) {
      //call computer
      callComp();
    } else {
      callCheckClicks();
    }
  }
  //document.ready().
});

html * {
  text-align: center;
  background-color: #d3d3d3;
}

h1 {
  font-size: 60px;
  padding-bottom: 10px;
}

h3 {
  display: none;
  padding-bottom: 30px;
}

.circle {
  background: #d3d3d3;
  width: 320px;
  height: 320px;
  border-radius: 50%;
  border: 10px solid gray;
  margin: auto;
}

.tile {
  height: 150px;
  width: 150px;
  float: left;
  cursor: pointer;
}

#red {
  background-color: red;
  border-top-right-radius: 100%;
}

#green {
  background-color: green;
  border-top-left-radius: 100%;
}

#blue {
  background-color: blue;
  border-bottom-right-radius: 100%;
}

#yellow {
  background-color: yellow;
  border-bottom-left-radius: 100%;
}

btn {
  padding-top: 40px;
}

Simon Game

Round:

  Start
  Reset

Body:
I believe what you are looking for is setTimeout()

This takes 2 parameters, your function and the number of milliseconds.

For example if you want to execute a function after three seconds of an onclick event...

<button onclick="setTimeout(myFunction, 3000);">Try it</button>

<script>
function myFunction() {
    alert('Hello');
}
</script>

Then use a promise like explained here:
Javascript - Wait the true ending of a function that uses setTimeout

Another thing to note is the flow of the program.  Currently you are using a checkTurn method that calls a callCheckClicks method that calls a checkClicks and checkClicks calls checkTurn again.  With this your program will end up crashing as it continuously loops forever.  In order to do this you need to activate your if/else within your checkClicks to have

turn = true;
checkTurn();

To look like

function checkClicks() {
  console.log("random clicks: " + compSeq);
  //if user guess is correct
  if (userSeq[playerIndex] == compSeq[playerIndex]) {
    if (userSeq[playerIndex].length == compSeq[playerIndex].length) {
      // if they are then it's computer's turn
      callComp();
    } else {
      playerIndex += 1;
      $(".start")
        .html("Next")
        .show();

      // user is right, he can continue inputting another clicks if the sequence has
      turn=true;

      checkTurn();

    }
  } else {
    resetUserVariables(); // user is wrong
  }
}

Hope this is what you're looking for.