问:
Convert list of floats to NumPy array
I am working with Neural Nets, I want to implement it on an FPGA. I have a code working on MNIST, and I want to obtain the initial weights using float32, and then retrain the weights on the FPGA with fixed point.

I am running my simulation in python. I am looking for a way to do this conversion

```<code>from keras.datasets import mnist
from keras.layers import Dense
from keras.models import Sequential
from keras.layers import Dropout
from keras.utils import np_utils
import matplotlib.pyplot as plt
(x, y), (X, Y) = mnist.load_data()

num = x.shape[1] * x.shape[2]
x = x.reshape(x.shape[0],x.shape[1]*x.shape[2]).astype('float32')
X = X.reshape(X.shape[0],X.shape[1]*X.shape[2]).astype('float32')

x = x/255
X = X/255

y = np_utils.to_categorical(y)
Y = np_utils.to_categorical(Y)

classes = y.shape[1]

def calc():
    model = Sequential()
    model.add(Dense(num, input_dim = num, init = 'normal', activation = 'relu'))
    model.add(Dense(classes, init = 'normal', activation = 'softmax'))
    model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
    return model

model = calc()
model.fit(x, y, validation_data=(X, Y), nb_epoch=10, batch_size=200,
    verbose=2)
scores = model.evaluate(X, Y, verbose=0)
print("Accuracy: ", scores)
</code>```

答:
Pass your list to np.array with dtype=np.float32 to specify 32 bit floating point numbers as the data type:

```<code>np.array(your_list, dtype=np.float32)
</code>```

Title: Convert list of floats to NumPy array

Body:
I am working with Neural Nets, I want to implement it on an FPGA. I have a code working on MNIST, and I want to obtain the initial weights using float32, and then retrain the weights on the FPGA with fixed point.

I am running my simulation in python. I am looking for a way to do this conversion

from keras.datasets import mnist
from keras.layers import Dense
from keras.models import Sequential
from keras.layers import Dropout
from keras.utils import np_utils
import matplotlib.pyplot as plt
(x, y), (X, Y) = mnist.load_data()

num = x.shape[1] * x.shape[2]
x = x.reshape(x.shape[0],x.shape[1]*x.shape[2]).astype('float32')
X = X.reshape(X.shape[0],X.shape[1]*X.shape[2]).astype('float32')

x = x/255
X = X/255

y = np_utils.to_categorical(y)
Y = np_utils.to_categorical(Y)

classes = y.shape[1]

def calc():
    model = Sequential()
    model.add(Dense(num, input_dim = num, init = 'normal', activation = 'relu'))
    model.add(Dense(classes, init = 'normal', activation = 'softmax'))
    model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
    return model

model = calc()
model.fit(x, y, validation_data=(X, Y), nb_epoch=10, batch_size=200,
    verbose=2)
scores = model.evaluate(X, Y, verbose=0)
print("Accuracy: ", scores)

Body:
Pass your list to np.array with dtype=np.float32 to specify 32 bit floating point numbers as the data type:

np.array(your_list, dtype=np.float32)


来源: stackexchange

问:
LINQ Contains clause - more then one value in criteria
I have a collection which is filtered based on criteria for which I am using contains clause given below.
I am further creating a new collection based on filtered records and returning the same.

Issue:

If I have more then one value in "multipleCodes" which is used in contains clause.. it does not work.
If I put only 1 value... it does work.

Any idea what am I missing ? or is there any better approach to filter records and retrun only filtered resultset ?

```<code>collectionToFilter.Where(d => (d.Code.**Contains**(multipleCodes)) &&
                d.NeededDate > minNeedDate && d.NeededDate < maxNeedDate)
                    .ToList()
                    .ForEach(d => filteredCollection.Add(d));
</code>```

答:
```<code>collectionToFilter.Where(d => (multipleCodes.Any(mc=>d.Code.Contains(mc))) &&
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a collection which is filtered based on criteria for which I am using contains clause given below.
I am further creating a new collection based on filtered records and returning the same.

Issue:

If I have more then one value in "multipleCodes" which is used in contains clause.. it does not work.
If I put only 1 value... it does work.

Any idea what am I missing ? or is there any better approach to filter records and retrun only filtered resultset ?

collectionToFilter.Where(d => (d.Code.**Contains**(multipleCodes)) &&
                d.NeededDate > minNeedDate && d.NeededDate < maxNeedDate)
                    .ToList()
                    .ForEach(d => filteredCollection.Add(d));


问:
java.io.NotSerializableException: org.mybatis.spring.SqlSessionTemplate
I am getting below exception when I am doing clustering in Tomcat.

SEVERE: Unable to serialize delta request for sessionid [E67521E84EE07AB85E0243149B4DE472.jvm2]
      java.io.NotSerializableException: org.mybatis.spring.SqlSessionTemplate
              at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
              at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)

答:
The Javadoc of the exception explains the meaning of the exception:

Thrown when an instance is required to have a Serializable interface. The serialization runtime or the class of the instance can throw this exception. The argument should be the name of the class.

https://docs.oracle.com/javase/7/docs/api/java/io/NotSerializableException.html

Somehow your program tries to write an instance of SqlSessionTemplate to an object stream (aka serialization), perhaps to send it over a network to a different machine.

Normally to fix this exception, you let a class implement the Serializable interface, but since this is a library class and it's not owned by you, it cannot be changed and hence it's not meant to be serialized.


问:
pygame.time.clock() or pygame.clock.tick() error
I have a main loop in my code where it loops everything and when I run my code I get this error:

```<code>    Traceback (most recent call last):
      File "C:\Users\Javier\Documents\Python Pygame\First Game\First
    Game.py", line 17, in <module>
        clock=pygame.time.clock()
    AttributeError: module 'pygame.time' has no attribute 'clock'
</code>```

I understand what the error is: it means it can't find the 'class' clock and in another instance where I used pygame.tick.clock() I got the same error.

```<code>    #import modules here

    import pygame

    #define what colours are
    black=(0,0,0)
    white=(255,255,255)
    turquoise=(64,224,208)
    #initalise pygame
    pygame.init()
    #set up screen
    screen=pygame.display.set_mode((400,400))
    #what the screen is called and backgroud colour
    screen.fill(black)
    pygame.display.set_caption("Snake!")
    #set a variable for how quick the game runs
    clock=pygame.time.clock()

    '''making future references easier
    eval just takes code as a string and runs it
    eg:
    instead of doing print(5+8)
    you can do eval(print(5+8))'''
    def key(key):
        return pygame.ket.get_pressed()[eval("pygame.K_"+key)]
    #draw the snake
    snake=(50,150,150,50)
    #display.flip shows what has been drawn on the screen eg the snake
    while True:
        pygame.draw.rect(screen,turquoise,snake)
        pygame.display.flip()
        clock.tick(60)
</code>```

When I comment the problem code (clock.tick() and pygame.time.clock)  the window opens and displays the turquoise "snake" but it has no limiting factor that slows down the rate of the loop executing.

答:
I believe it's pygame.time.Clock and pygame.time.Clock.tick

https://www.pygame.org/docs/ref/time.html#pygame.time.Clock

As you noted, the module couldn't find the class Clock.  In Python, the convention for Classes is to capitalize them.

Body:
I have a main loop in my code where it loops everything and when I run my code I get this error:

    Traceback (most recent call last):
      File "C:\Users\Javier\Documents\Python Pygame\First Game\First
    Game.py", line 17, in <module>
        clock=pygame.time.clock()
    AttributeError: module 'pygame.time' has no attribute 'clock'

I understand what the error is: it means it can't find the 'class' clock and in another instance where I used pygame.tick.clock() I got the same error.

    #import modules here

    import pygame

    #define what colours are
    black=(0,0,0)
    white=(255,255,255)
    turquoise=(64,224,208)
    #initalise pygame
    pygame.init()
    #set up screen
    screen=pygame.display.set_mode((400,400))
    #what the screen is called and backgroud colour
    screen.fill(black)
    pygame.display.set_caption("Snake!")
    #set a variable for how quick the game runs
    clock=pygame.time.clock()

    '''making future references easier
    eval just takes code as a string and runs it
    eg:
    instead of doing print(5+8)
    you can do eval(print(5+8))'''
    def key(key):
        return pygame.ket.get_pressed()[eval("pygame.K_"+key)]
    #draw the snake
    snake=(50,150,150,50)
    #display.flip shows what has been drawn on the screen eg the snake
    while True:
        pygame.draw.rect(screen,turquoise,snake)
        pygame.display.flip()
        clock.tick(60)

When I comment the problem code (clock.tick() and pygame.time.clock)  the window opens and displays the turquoise "snake" but it has no limiting factor that slows down the rate of the loop executing.


问:
how to update a column by combining two column values into one column in MySQL using laravel
I want to update my existing column with concatenating two columns in a table using laravel migrations.

An example: I am having a column FIRSTNAME and LASTNAME and so many columns also. I want to concatenate these two columns with the name of FIRSTNAME only in between space.

So this is how it works in mysql:

```<code>SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'FIRSTNAME' FROM customer;
</code>```

How we have to do this using laravel?

Right now Firstnames are displayed in one column and lastnames are displayed in another column. I have to update both the values into single column by concatenating.

答:
You can define an accessor in your model. You can check document here . In your case the follow function need to add to your model</p>

```<code>public function getFirstNameAttribute($value)
{
    return $value. " ". $this->LASTNAME;
}
</code>```

Body:
I want to update my existing column with concatenating two columns in a table using laravel migrations.

An example: I am having a column FIRSTNAME and LASTNAME and so many columns also. I want to concatenate these two columns with the name of FIRSTNAME only in between space.

So this is how it works in mysql:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'FIRSTNAME' FROM customer;

How we have to do this using laravel?

Right now Firstnames are displayed in one column and lastnames are displayed in another column. I have to update both the values into single column by concatenating.

Body:
You can define an accessor in your model. You can check document here . In your case the follow function need to add to your model

public function getFirstNameAttribute($value)
{
    return $value. " ". $this->LASTNAME;
}


问:
How to do onClick element change in Redux a container with React.js?
I already saw a similar question from someone else here and the answer is pretty clear. Yet, if you're working with in a redux container, the states turn into props through the mapStateToProps function.

How is it then correct to proceed if I want e.g. my text-div to turn into an input, when I click or double-click on it? I don't have any code yet, I'm wondering about the theory.

答: The components get store state data passed in as props, but they can also have their own state. So in your case, your component would use it's own state to handle the toggling of div to input. If for some reason you wanted it to be saved in the store instead, you would fire off an action to toggle the view and then use the prop from the store in your render method.


问:
Two different OnClick panels in Unity Studio inspector
I have created two projects some time ago.

Probably in two different versions of unity in the beginning.

Now I am opening both in the studio version 5.6.0f3

I am trying to make Buttons onClick events, in the first one its easy, inspector looks normal to me.

In the second project looks totally different.

Why is the panel looking differently? Aren't the projects migrated when opening them in new Unity Studio? Can I update both of them somehow to same version? No idea how to add onClick in second project, did not found any tutorial with menu like mine.

Thanks.

答:
You have the Inspector set to Debug Mode in the second image.

Right click on the Inspector title tab and click Normal instead of Debug.


问:
Integrating the Google Cloud Platform API into a Flask app
I am creating a basic flask app that outputs a list of instances running on a GCP project into the browser but I'm coming across some issues when returning the result of the api call inside the browser.

My flask app looks something like this:

```<code>@app.route(API_ROOT + 'list')
def list_all_running():
    return test_list.list_all_running_instances()
</code>```

and the function I'm trying to return looks like this

```<code>def list_all_running_instances():

    request = service.instances().list(project=project, zone='europe-west1-d')
    while request is not None:
        response = request.execute()
        for instance in response['items']:
            # if instance['status'] == 'RUNNING':
            return instance
        request = service.instances().list_next(previous_request=request, previous_response=response)
</code>```

This is a shortened and adapted version of this script listed under 'python' in the examples at the bottom of the page.

The issue is when I call the function in flask it only returns the first instance running. In the original gcp api script example it uses pprint rather than return, which works fine on the console but I am unable to output the pprint results to a browser.

Can anyone recommend the best way of doing this? Is there a way you can output pprint into the browser via Flask. I realise that when returning it will only output the result of the first iteration and then stop, hence this issue.

As you can tell I'm quite new at Flask, so apologies if this seems like a silly question.

答:
The problem is the return statement which finishes execution of your list_all_running_instances function. You can do something like this:

```<code>def list_all_running_instances():

    request = service.instances().list(project=project, zone='europe-west1-d')
    all_instances = []
    while request is not None:
        response = request.execute()
        all_instances.extend(response['items'])
        request = service.instances().list_next(previous_request=request, previous_response=response)
    return {'all_instances': all_instances}
</code>```

Body:
I am creating a basic flask app that outputs a list of instances running on a GCP project into the browser but I'm coming across some issues when returning the result of the api call inside the browser.

My flask app looks something like this:

@app.route(API_ROOT + 'list')
def list_all_running():
    return test_list.list_all_running_instances()

and the function I'm trying to return looks like this

def list_all_running_instances():

    request = service.instances().list(project=project, zone='europe-west1-d')
    while request is not None:
        response = request.execute()
        for instance in response['items']:
            # if instance['status'] == 'RUNNING':
            return instance
        request = service.instances().list_next(previous_request=request, previous_response=response)

This is a shortened and adapted version of this script listed under 'python' in the examples at the bottom of the page.

The issue is when I call the function in flask it only returns the first instance running. In the original gcp api script example it uses pprint rather than return, which works fine on the console but I am unable to output the pprint results to a browser.

Can anyone recommend the best way of doing this? Is there a way you can output pprint into the browser via Flask. I realise that when returning it will only output the result of the first iteration and then stop, hence this issue.

As you can tell I'm quite new at Flask, so apologies if this seems like a silly question.

Body:
The problem is the return statement which finishes execution of your list_all_running_instances function. You can do something like this:

def list_all_running_instances():

    request = service.instances().list(project=project, zone='europe-west1-d')
    all_instances = []
    while request is not None:
        response = request.execute()
        all_instances.extend(response['items'])
        request = service.instances().list_next(previous_request=request, previous_response=response)
    return {'all_instances': all_instances}


问:
Dagger 2 with MVP, avoid creating extra presenter object on view recreation
I have an app implementing the MVP pattern with a Loader to maintain the presenter object on view recreation (there's an article about this here). I'm new to Dagger 2, trying to implement it together with the current code.

I've managed to make it work, but now my presenter is created twice. At first it was created using a factory class which was initialized in onCreateLoader, but then, when adding Dagger 2 implementation, I had two objects created (in factory class and when injecting).

Now I avoid creating a new presenter in onCreateLoader and passes the injected presenter instead. The problem is on view recreation: each time the view is destroyed and recreated, a new presenter is injected in OnCreate / OnCreateView. This is the scenario:

A new presenter is injected:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    getControllerComponent().inject(this);
    ...
}
</code>```

Initializing Loader, onCreateLoader is called if the Loader doesn't exist. Note that we pass the presenter that was injected:

```<code>@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getLoaderManager().initLoader(PRESENTER_LOADER_ID, null, this);
}

@Override
public Loader<MyPresenter> onCreateLoader(int id, Bundle args) {
    switch (id) {
        case PRESENTER_LOADER_ID:
            return new PresenterLoader<>(getContext(), presenter);
            //return new PresenterLoader<>(getContext(), new MyPresenterFactory());
    }

    return null;
}
</code>```

Assigning the presenter received from the Loader. If it was just created, we assign the same object that's already assigned so nothing happens. But, if the view was recreated, then Dagger 2 injected a new presenter and here we throw away the new presenter and replace it with the old presenter from the Loader.

```<code>@Override
public void onLoadFinished(Loader<MyPresenter> loader, MyPresenter data) {
    this.presenter = data;
}
</code>```

I want to maintain the presenter instance so it's ± what I want to happen; my problem is with creating a redundant presenter object on each view recreation. First, it's unnecessary, and additionally, the view is holding a reference to a different presenter until the load is finished. Obviously I am not using the presenter during this period (after injection and before the load is finished), but I definitely don't like it and afraid that this new presenter will be mistakenly used in the future.

Dagger 2 experts, is there a way to create the presenter the first time (before Loader is created) but avoid it on view recreation? Thanks a lot!

答:
First off I just want to mention that if you inject your presenter, you should not assign it again later from your loader.

Either use injection to provide an object, or provide it yourself. If you do both, you are just at risk to introduce bugs.

is there a way to create the presenter the first time (before Loader is created) but avoid it on view recreation?

tl;dr You need a scope for your presenter that reflects the lifetime of your component which might survive configuration changes. This scope must not keep any reference to the Activitys Context.

Components follow some lifecycle. You usually have some @Singleton annotated component that you keep within your Application and some @PerActivity or similarly scoped components that you create per Activity, which will (and should) be recreated when an activity goes through configuration changes, since those dependencies often reference the Activity context and should live and die with the Activity.

The primary problem you face here is a scoping problem.

If your presenter is unscoped, you will recreate a new presenter every time you request one, which will inadvertently lead to bugs, as soon as you inject it somewhere else. Usually presenters are kept within the activity and often scoped by some @PerActivity scope.

If your presenter is part of the @PerActivity scope it should (like all the other @PerActivity dependencies) be recreated along with all the other dependencies. If you keep the presenter, but recreate all the other objects, the old presenter will still reference the old dependencies, creating memory leaks. Scoped objects should just exist within their own scope.

Objects in the same scope can reference one another and thus keeping one scoped object alive outside of its scope will also inadvertently lead to bugs, memory leaks, etc.

So you don't want to keep this presenter in your Loader either.

If on the other hand you say No, that presenter is one step higher in the hierarchy, part of @PerScreen, where I keep longer living objects then you need to find a way to actually keep this @PerScreen component alive while your @PerActivity component will be recreated along with the activity.

Assume the following scope hierarchy:

```<code>`X > Y` read X is subcomponent of Y
@Singleton > @PerScreen > @PerActivity

@Singleton: Application wide
@PerScreen: Multiple activty lifecycles, keep alive during config changes
@PerActivity: Maybe Context dependent, recreate with every activity
</code>```

When a configuration change occurs you now can discard all of the @PerActivity objects and recreate them, while keeping the reference to your @PerScreen ones.

You might notice how I keep talking about keeping the @PerScreen component, not keeping the presenter, and that is the important part here:

On the @PerScreen scoped component, calling

```<code>myPerScreenComponent.getMyPresenter()
</code>```

will always return the same @PerScreen scoped presenter.

Now if your @PerActivty scoped component is a subcomponent of MyPerScreenComponent, injecting your activity will always give you the same @PerScreen scoped presenter, which will survive orientation changes.

To prevent memory leaks, no object from your @PerScreen scope can reference the Activity, and the presenter should only keep a WeakReference on its view (or you have to make damn sure to set the view to null on destroy).

That's what scopes are for and that's how you avoid creating extra presenter object on view recreation.

So instead of keeping your presenter in your loader you should try to keep the component in your loader to avoid unnecessary recreation of your objects.

All of this will probably introduce a lot more complexity since you now have 2 scopes per activity and more callbacks.

I have also seen other approaches where you keep your presenters as Singletons in your Application, but this introduces the same problems where you have to make sure not to keep any references to your Activity.

Personally, I would just recreate the presenters and restore the state, but if you choose to go with your approach you should make sure that you have a solid understanding of scopes and dependencies.

Body:
I have an app implementing the MVP pattern with a Loader to maintain the presenter object on view recreation (there's an article about this here). I'm new to Dagger 2, trying to implement it together with the current code.

I've managed to make it work, but now my presenter is created twice. At first it was created using a factory class which was initialized in onCreateLoader, but then, when adding Dagger 2 implementation, I had two objects created (in factory class and when injecting).

Now I avoid creating a new presenter in onCreateLoader and passes the injected presenter instead. The problem is on view recreation: each time the view is destroyed and recreated, a new presenter is injected in OnCreate / OnCreateView. This is the scenario:

A new presenter is injected:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    getControllerComponent().inject(this);
    ...
}

Initializing Loader, onCreateLoader is called if the Loader doesn't exist. Note that we pass the presenter that was injected:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getLoaderManager().initLoader(PRESENTER_LOADER_ID, null, this);
}

@Override
public Loader<MyPresenter> onCreateLoader(int id, Bundle args) {
    switch (id) {
        case PRESENTER_LOADER_ID:
            return new PresenterLoader<>(getContext(), presenter);
            //return new PresenterLoader<>(getContext(), new MyPresenterFactory());
    }

    return null;
}

Assigning the presenter received from the Loader. If it was just created, we assign the same object that's already assigned so nothing happens. But, if the view was recreated, then Dagger 2 injected a new presenter and here we throw away the new presenter and replace it with the old presenter from the Loader.

@Override
public void onLoadFinished(Loader<MyPresenter> loader, MyPresenter data) {
    this.presenter = data;
}

I want to maintain the presenter instance so it's ± what I want to happen; my problem is with creating a redundant presenter object on each view recreation. First, it's unnecessary, and additionally, the view is holding a reference to a different presenter until the load is finished. Obviously I am not using the presenter during this period (after injection and before the load is finished), but I definitely don't like it and afraid that this new presenter will be mistakenly used in the future.

Dagger 2 experts, is there a way to create the presenter the first time (before Loader is created) but avoid it on view recreation? Thanks a lot!

Body:
First off I just want to mention that if you inject your presenter, you should not assign it again later from your loader.

Either use injection to provide an object, or provide it yourself. If you do both, you are just at risk to introduce bugs.

is there a way to create the presenter the first time (before Loader is created) but avoid it on view recreation?

tl;dr You need a scope for your presenter that reflects the lifetime of your component which might survive configuration changes. This scope must not keep any reference to the Activitys Context.

Components follow some lifecycle. You usually have some @Singleton annotated component that you keep within your Application and some @PerActivity or similarly scoped components that you create per Activity, which will (and should) be recreated when an activity goes through configuration changes, since those dependencies often reference the Activity context and should live and die with the Activity.

The primary problem you face here is a scoping problem.

If your presenter is unscoped, you will recreate a new presenter every time you request one, which will inadvertently lead to bugs, as soon as you inject it somewhere else. Usually presenters are kept within the activity and often scoped by some @PerActivity scope.

If your presenter is part of the @PerActivity scope it should (like all the other @PerActivity dependencies) be recreated along with all the other dependencies. If you keep the presenter, but recreate all the other objects, the old presenter will still reference the old dependencies, creating memory leaks. Scoped objects should just exist within their own scope.

Objects in the same scope can reference one another and thus keeping one scoped object alive outside of its scope will also inadvertently lead to bugs, memory leaks, etc.

So you don't want to keep this presenter in your Loader either.

If on the other hand you say No, that presenter is one step higher in the hierarchy, part of @PerScreen, where I keep longer living objects then you need to find a way to actually keep this @PerScreen component alive while your @PerActivity component will be recreated along with the activity.

Assume the following scope hierarchy:

`X > Y` read X is subcomponent of Y
@Singleton > @PerScreen > @PerActivity

@Singleton: Application wide
@PerScreen: Multiple activty lifecycles, keep alive during config changes
@PerActivity: Maybe Context dependent, recreate with every activity

When a configuration change occurs you now can discard all of the @PerActivity objects and recreate them, while keeping the reference to your @PerScreen ones.

You might notice how I keep talking about keeping the @PerScreen component, not keeping the presenter, and that is the important part here:

On the @PerScreen scoped component, calling

myPerScreenComponent.getMyPresenter()

will always return the same @PerScreen scoped presenter.

Now if your @PerActivty scoped component is a subcomponent of MyPerScreenComponent, injecting your activity will always give you the same @PerScreen scoped presenter, which will survive orientation changes.

To prevent memory leaks, no object from your @PerScreen scope can reference the Activity, and the presenter should only keep a WeakReference on its view (or you have to make damn sure to set the view to null on destroy).

That's what scopes are for and that's how you avoid creating extra presenter object on view recreation.

So instead of keeping your presenter in your loader you should try to keep the component in your loader to avoid unnecessary recreation of your objects.

All of this will probably introduce a lot more complexity since you now have 2 scopes per activity and more callbacks.

I have also seen other approaches where you keep your presenters as Singletons in your Application, but this introduces the same problems where you have to make sure not to keep any references to your Activity.

Personally, I would just recreate the presenters and restore the state, but if you choose to go with your approach you should make sure that you have a solid understanding of scopes and dependencies.


问:
Extract string between by [" "]
how can I extract string between [" "]
I have eg: ["x"], so how can I extract just x and assign it to a
variable
I have tried this:

```<code>String str = "[x]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
</code>```

I can get x using the above code but my string is enclosed between [" "]

答:
Use the following code:</p>

```<code>public static void main(final String[] args) {
    String in = "[ABC]";

    Pattern p = Pattern.compile("\\[(.*)\\]");
    Matcher m = p.matcher(in);

    while(m.find()) {
        System.out.println(m.group(1));
    }
}
</code>```

Title: Extract string between by [" "]

Body:
how can I extract string between [" "]
I have eg: ["x"], so how can I extract just x and assign it to a
variable
I have tried this:

String str = "[x]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

I can get x using the above code but my string is enclosed between [" "]

Body:
Use the following code:

public static void main(final String[] args) {
    String in = "[ABC]";

    Pattern p = Pattern.compile("\\[(.*)\\]");
    Matcher m = p.matcher(in);

    while(m.find()) {
        System.out.println(m.group(1));
    }
}


问:
How to create python bytes object from long hex string?
I have a long sequence of hex digits in a string, such as

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

only much longer, several kilobytes.  Is there a builtin way to convert this to a bytes object in python 2.6/3?

OwnerDisplayName: recursive

ContentLicense: CC BY-SA 2.5

Body:
You can do this with the hex codec.  ie:

>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'

OwnerDisplayName: Brian


问:
Create Unit Tests is supported only within a public class or a public method VS 2015
I'm getting a Create Unit Tests is supported only within a public class or a public method when I try to create unit tests for my app.  I was trying to test a public method in a very simple app in Visual Studio 2015 Enterprise.  Here's a screenshot.

Here's the Program.cs:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Scratch
{
    public class Program    //Originally this was just class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Hello world!");

        }

        public static string TruncateOld(string value, int length)
        {
            string result = value;
            if (value != null) // Skip empty string check for elucidation
            {
                result = value.Substring(0, Math.Min(value.Length, length));
            }
            return result;
        }

        public static string Truncate(string value, int length)
        {
            return value?.Substring(0, Math.Min(value.Length, length));
        }

    }
}
</code>```

I've found this msdn article, but it doesn't really offer any suggestions on how to solve the problem.  Also, I've never installed 'ALM Rangers Generate Unit Test.'

I got rid of everything from my Program.cs except for the Main and added a new Public Class1 with the following code (I still get the error and the menu goes away):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scratch
{
    public class Class1
    {

        public Class1()
        {

        }

        public string TruncateOld(string value, int length)
        {
            string result = value;
            if (value != null) // Skip empty string check for elucidation
            {
                result = value.Substring(0, Math.Min(value.Length, length));
            }
            return result;
        }

        public string Truncate(string value, int length)
        {
            return value?.Substring(0, Math.Min(value.Length, length));
        }

    }
}
</code>```

答:
To anyone that is new to C# having this issue, you need to add the public keyword to your class.

For example,

```<code>class myProgram
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World");
    }
}
</code>```

You'd need to change the first line to public class myProgram

Body:
I'm getting a Create Unit Tests is supported only within a public class or a public method when I try to create unit tests for my app.  I was trying to test a public method in a very simple app in Visual Studio 2015 Enterprise.  Here's a screenshot.

Here's the Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Scratch
{
    public class Program    //Originally this was just class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Hello world!");

        }

        public static string TruncateOld(string value, int length)
        {
            string result = value;
            if (value != null) // Skip empty string check for elucidation
            {
                result = value.Substring(0, Math.Min(value.Length, length));
            }
            return result;
        }

        public static string Truncate(string value, int length)
        {
            return value?.Substring(0, Math.Min(value.Length, length));
        }

    }
}

I've found this msdn article, but it doesn't really offer any suggestions on how to solve the problem.  Also, I've never installed 'ALM Rangers Generate Unit Test.'

I got rid of everything from my Program.cs except for the Main and added a new Public Class1 with the following code (I still get the error and the menu goes away):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scratch
{
    public class Class1
    {

        public Class1()
        {

        }

        public string TruncateOld(string value, int length)
        {
            string result = value;
            if (value != null) // Skip empty string check for elucidation
            {
                result = value.Substring(0, Math.Min(value.Length, length));
            }
            return result;
        }

        public string Truncate(string value, int length)
        {
            return value?.Substring(0, Math.Min(value.Length, length));
        }

    }
}

Body:
To anyone that is new to C# having this issue, you need to add the public keyword to your class.

For example,

class myProgram
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World");
    }
}

You'd need to change the first line to public class myProgram


问:
modifying BIT column to ENUM in mysql/MariaDB
mysql Ver 15.1 Distrib 10.2.6-MariaDB

I have run into a problem executing an UPDATE statment in the O'Reilly book "Learning MySQL and MariaDB". The code is in chapter 5 - on pages 218 & 219 of the ebook I'm reading.

The field "endangered" in the table "birds_new" is of type bit(1).   The intent is to change it the type to ENUM.

```<code>alter table birds_new
modify column endangered
enum ('Extinct', 'Extinct in Wild', 'Threatened - Critically Endangered',
'Threatened - Endangered', 'Threatened - Vulnerable',
'Lower Risk - Conservation Dependent', 'Lower Risk - Near Threatened',
'Lower Risk - Least Concern')
after family_id;
</code>```

It fails:
ERROR 1265 (01000): Data Truncated for column 'endangered' at row 1

The data type remains bit(1).
What is wrong with the ALTER statement?

Is it simply not possible to do this with an ALTER statment?
I have made the change with two separate ALTER statements: DROP COLUMN, then ADD COLUMN.

答:
BIT(1) and ENUM are somewhat different.  I suggest you do it in multiple steps.  But first, I suggest your ENUM be NOT NULL and have and extra, first option of unknown (or some such).  Don't you also need 'Not endangered'?

```<code>ALTER TABLE birds_new
    CHANGE COLUMN endangered old_end BIT(1) ...,
    ADD COLUMN endangered ENUM
           ('unknown, 'Extinct', ..., 'Not endangered') NOT NULL;

UPDATE birds_new
    SET endangered = IF(old_end, 'unknown', 'Not endangered')

ALTER TABLE birds_new
    DROP COLUMN old_end;
</code>```

You will then need some code to turn 'unknown' into the specific level of "endangered".

Body:
mysql Ver 15.1 Distrib 10.2.6-MariaDB

I have run into a problem executing an UPDATE statment in the O'Reilly book "Learning MySQL and MariaDB". The code is in chapter 5 - on pages 218 & 219 of the ebook I'm reading.

The field "endangered" in the table "birds_new" is of type bit(1).   The intent is to change it the type to ENUM.

alter table birds_new
modify column endangered
enum ('Extinct', 'Extinct in Wild', 'Threatened - Critically Endangered',
'Threatened - Endangered', 'Threatened - Vulnerable',
'Lower Risk - Conservation Dependent', 'Lower Risk - Near Threatened',
'Lower Risk - Least Concern')
after family_id;

It fails:
ERROR 1265 (01000): Data Truncated for column 'endangered' at row 1

The data type remains bit(1).
What is wrong with the ALTER statement?

Is it simply not possible to do this with an ALTER statment?
I have made the change with two separate ALTER statements: DROP COLUMN, then ADD COLUMN.

Body:
BIT(1) and ENUM are somewhat different.  I suggest you do it in multiple steps.  But first, I suggest your ENUM be NOT NULL and have and extra, first option of unknown (or some such).  Don't you also need 'Not endangered'?

ALTER TABLE birds_new
    CHANGE COLUMN endangered old_end BIT(1) ...,
    ADD COLUMN endangered ENUM
           ('unknown, 'Extinct', ..., 'Not endangered') NOT NULL;

UPDATE birds_new
    SET endangered = IF(old_end, 'unknown', 'Not endangered')

ALTER TABLE birds_new
    DROP COLUMN old_end;

You will then need some code to turn 'unknown' into the specific level of "endangered".


问:
error: expected constructor, destructor, or type conversion before '('
I'm just working on a RFID Sniffer on Arduino but something happened that it doesnt't work anymore.

```<code>#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>

SoftwareSerial RDM630 = SoftwareSerial(2, 3); // RFID

LiquidCrystal_I2C lcd(0x3F, 16, 2);
SoftwareSerial ESP = SoftwareSerial(10, 11); // RX, TX
pinMode(13, INPUT);
char rfid;
String dx;
bool connected = false;
String connbuff;
int lf = 10;
int cnt = 0;
bool lcdWAV = false;

void setup() {
  lcd.begin(16, 2);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  Serial.begin(9600);
  RDM630.begin(9600);
  ESP.begin(9600);
  ESP.listen();
}
</code>```

The error says:

```<code>Documents/Arduino/rdm630_test/src/rdm630_test.ino:27:8: error: expected constructor, destructor, or type conversion before  '(' token
lcd.setCursor(0, 0);
^
</code>```

Now there is only the Setup routine and even this don't work. I only get the error...

答:
I forget that smth. like this:

```<code>pinMode(13, INPUT);
</code>```

Need be placed in the

```<code>setup() {
 // ...
}
</code>```

Body:
I'm just working on a RFID Sniffer on Arduino but something happened that it doesnt't work anymore.

#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>

SoftwareSerial RDM630 = SoftwareSerial(2, 3); // RFID

LiquidCrystal_I2C lcd(0x3F, 16, 2);
SoftwareSerial ESP = SoftwareSerial(10, 11); // RX, TX
pinMode(13, INPUT);
char rfid;
String dx;
bool connected = false;
String connbuff;
int lf = 10;
int cnt = 0;
bool lcdWAV = false;

void setup() {
  lcd.begin(16, 2);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  Serial.begin(9600);
  RDM630.begin(9600);
  ESP.begin(9600);
  ESP.listen();
}

The error says:

Documents/Arduino/rdm630_test/src/rdm630_test.ino:27:8: error: expected constructor, destructor, or type conversion before  '(' token
lcd.setCursor(0, 0);
^

Now there is only the Setup routine and even this don't work. I only get the error...

Body:
I forget that smth. like this:

pinMode(13, INPUT);

Need be placed in the

setup() {
 // ...
}


问:
Invalid pointer exception when closing app after upgrade from Delphi 2006 to Delphi XE
I've just upgraded a project from Delphi 2006 to Delphi XE. Everything is working as expected except I get an exception when I close my app.

It's not breaking on a code line. It breaks to the CPU window on a LEAVE command.
I've attached a Eureka log if that is any help.

```<code>EurekaLog 6.0.25

Application:
------------------------------------------------------
  1.1 Start Date      : Fri, 3 Dec 2010 10:44:17 +0100
  1.2 Name/Description: LogoTid.exe
  1.3 Version Number  :
  1.4 Parameters      :
  1.5 Compilation Date: Fri, 3 Dec 2010 10:44:15 +0100
  1.6 Up Time         : 5 seconds

Exception:
----------------------------------------------------
  2.1 Date          : Fri, 3 Dec 2010 10:44:22 +0100
  2.2 Address       : 004062A0
  2.3 Module Name   : LogoTid.exe
  2.4 Module Version:
  2.5 Type          : EInvalidPointer
  2.6 Message       : Invalid pointer operation.
  2.7 ID            : 5E21
  2.8 Count         : 1
  2.9 Status        : New
  2.10 Note         :

User:
-------------------------------------------------------
  3.1 ID        : oda
  3.2 Name      :
  3.3 Email     :
  3.4 Company   :
  3.5 Privileges: SeIncreaseQuotaPrivilege        - OFF
                  SeSecurityPrivilege             - OFF
                  SeTakeOwnershipPrivilege        - OFF
                  SeLoadDriverPrivilege           - OFF
                  SeSystemProfilePrivilege        - OFF
                  SeSystemtimePrivilege           - OFF
                  SeProfileSingleProcessPrivilege - OFF
                  SeIncreaseBasePriorityPrivilege - OFF
                  SeCreatePagefilePrivilege       - OFF
                  SeBackupPrivilege               - OFF
                  SeRestorePrivilege              - OFF
                  SeShutdownPrivilege             - OFF
                  SeDebugPrivilege                - ON
                  SeSystemEnvironmentPrivilege    - OFF
                  SeChangeNotifyPrivilege         - ON
                  SeRemoteShutdownPrivilege       - OFF
                  SeUndockPrivilege               - OFF
                  SeManageVolumePrivilege         - OFF
                  SeImpersonatePrivilege          - ON
                  SeCreateGlobalPrivilege         - ON
                  SeIncreaseWorkingSetPrivilege   - OFF
                  SeTimeZonePrivilege             - OFF
                  SeCreateSymbolicLinkPrivilege   - OFF

Active Controls:
------------------------------------------------------------------
  4.1 Form Class   : TAppBuilder
  4.2 Form Text    : LogoTid - Delphi XE - uMain [Running] [Built]
  4.3 Control Class:
  4.4 Control Text :

Computer:
------------------------------------------------------------------------------------------------
  5.1 Name          : OLE-LAPTOP
  5.2 Total Memory  : 3891 Mb
  5.3 Free Memory   : 778 Mb
  5.4 Total Disk    : 120 Gb
  5.5 Free Disk     : 57,93 Gb
  5.6 System Up Time: 1 day, 23 hours, 16 minutes, 56 seconds
  5.7 Processor     : Intel(R) Core(TM) i5 CPU       M 520  @ 2.40GHz
  5.8 Display Mode  : 1920 x 1200, 32 bit
  5.9 Display DPI   : 96
  5.10 Video Card   : Intel(R) Graphics Media Accelerator HD (driver 8.15.10.2025 - RAM 1721 MB)
  5.11 Printer      : RICOH Aficio 2232C RPCS (driver 1.0.0)

Operating System:
--------------------------------------------
  6.1 Type    : Microsoft Windows 7 (64 bit)
  6.2 Build # : 7600
  6.3 Update  :
  6.4 Language: Danish
  6.5 Charset : 0

Call Stack Information:
-------------------------------------------------------------------
|Address |Module      |Unit       |Class|Procedure/Method   |Line |
-------------------------------------------------------------------
|Running Thread: ID=5632; Priority=0; Class=; [Main]              |
|-----------------------------------------------------------------|
|00D171A1|LogoTid.exe |LogoTid.dpr|     |                   |32[5]|
|76A73675|kernel32.dll|           |     |BaseThreadInitThunk|     |
-------------------------------------------------------------------

Assembler Information:
-----------------------------------------------------------------
; System.TObject.FreeInstance
; ----------------------------
00406294  push    ebx
00406295  mov     ebx, eax
00406297  mov     eax, ebx
00406299  call    System.TObject.CleanupInstance
0040629E  mov     eax, ebx
004062A0  call    System._FreeMem                 ; <-- EXCEPTION
004062A5  pop     ebx
004062A6  ret

Registers:
-----------------------------
EAX: 02AF8058   EDI: 00000001
EBX: 004062A5   ESI: 004062A5
ECX: 0041D700   ESP: 0018FE98
EDX: 004062A5   EIP: 004062A0

Stack:               Memory Dump:
------------------   ---------------------------------------------------------------------------
0018FE98: FFFFFF02   004062A0: E8 3B E7 FF FF 5B C3 90 83 C0 CC 8B 00 C3 8B C0  .;...[..........
0018FE9C: 00404B78   004062B0: 84 D2 74 08 83 C4 F0 E8 54 05 00 00 84 D2 74 0F  ..t.....T.....t.
0018FEA0: 02B1CEC0   004062C0: E8 A3 05 00 00 64 8F 05 00 00 00 00 83 C4 0C C3  .....d..........
0018FEA4: 02B1CEC0   004062D0: E8 E3 05 00 00 84 D2 7E 05 E8 82 05 00 00 C3 90  .......~........
0018FEA8: 00404BC2   004062E0: 85 C0 74 07 B2 01 8B 08 FF 51 FC C3 53 56 57 89  ..t......Q..SVW.
0018FEAC: 02B1CEC0   004062F0: C3 89 D7 AB 8B 4B CC 31 C0 51 C1 E9 02 49 F3 AB  .....K.1.Q...I..
0018FEB0: 0018FEE8   00406300: 59 83 E1 03 F3 AA 89 D0 89 E2 8B 4B AC 85 C9 74  Y..........K...t
0018FEB4: 004062A5   00406310: 01 51 8B 5B D0 85 DB 74 04 8B 1B EB ED 39 D4 74  .Q.[...t.....9.t
0018FEB8: 03A02F01   00406320: 1D 5B 8B 0B 83 C3 04 8B 73 10 85 F6 74 06 8B 7B  .[......s...t..{
0018FEBC: 00406865   00406330: 14 89 34 07 83 C3 1C 49 75 ED 39 D4 75 E3 5F 5E  ..4....Iu.9.u._^
0018FEC0: 0045B949   00406340: 5B C3 8B C0 53 56 89 C3 89 C6 8B 36 8B 56 B4 8B  [...SV.....6.V..
0018FEC4: 03A02FA0   00406350: 76 D0 85 D2 74 07 E8 85 36 00 00 89 D8 85 F6 75  v...t...6......u
0018FEC8: 03A02F01   00406360: E9 89 D8 E8 78 06 00 00 5E 5B C3 90 87 D1 81 F9  ....x...^[......
0018FECC: 004062EB   00406370: 00 00 00 FF 73 11 81 F9 00 00 00 FE 72 07 0F BF  ....s.......r...
0018FED0: 00912606   00406380: C9 03 08 FF 21 FF E1 81 E1 FF FF FF 00 01 C1 89  ....!...........
0018FED4: 00000000   00406390: D0 8B 11 E9 A8 59 00 00 C3 8D 40 00 3B C2 0F 94  .....Y....@.;...
</code>```

--- Edit

Ok, tried turning of parts of my program until the error went away, and found the troublemaker.

It's my webservice WSDL generated proxy. If I create the proxy object without calling any functions on the service, it throws the error.

I've created a test project without any other code than the proxy object creation and it also throws the error. I've also tried with another webservice, same error. Both webservices was created with Delphi 2006 (.net 1.1).

Lastly I tried with a .net 4.0 webservice created in VS2010. No problems. So either Delphi XE is projects is not compatible with .net 1.1 webservices or Delphi 2006 webservices. Either way it's a mess.

Any thouhts on how to solve this, maybe a workaround?

答:
The log won't help here. It looks like a memory corruption issue, which can happen if your code performs indexed operations on strings (writing to string's character position, for example) and you have not fixed all code where string is casted to PChar or similar code. </p>

<p>In other words, you have to perform careful analysis of your code. Start with turning off some modules and code blocks completely until the exception disappears. Then start adding them one by one. </p>

Body:
I've just upgraded a project from Delphi 2006 to Delphi XE. Everything is working as expected except I get an exception when I close my app.

It's not breaking on a code line. It breaks to the CPU window on a LEAVE command.
I've attached a Eureka log if that is any help.

EurekaLog 6.0.25

Application:
------------------------------------------------------
  1.1 Start Date      : Fri, 3 Dec 2010 10:44:17 +0100
  1.2 Name/Description: LogoTid.exe
  1.3 Version Number  :
  1.4 Parameters      :
  1.5 Compilation Date: Fri, 3 Dec 2010 10:44:15 +0100
  1.6 Up Time         : 5 seconds

Exception:
----------------------------------------------------
  2.1 Date          : Fri, 3 Dec 2010 10:44:22 +0100
  2.2 Address       : 004062A0
  2.3 Module Name   : LogoTid.exe
  2.4 Module Version:
  2.5 Type          : EInvalidPointer
  2.6 Message       : Invalid pointer operation.
  2.7 ID            : 5E21
  2.8 Count         : 1
  2.9 Status        : New
  2.10 Note         :

User:
-------------------------------------------------------
  3.1 ID        : oda
  3.2 Name      :
  3.3 Email     :
  3.4 Company   :
  3.5 Privileges: SeIncreaseQuotaPrivilege        - OFF
                  SeSecurityPrivilege             - OFF
                  SeTakeOwnershipPrivilege        - OFF
                  SeLoadDriverPrivilege           - OFF
                  SeSystemProfilePrivilege        - OFF
                  SeSystemtimePrivilege           - OFF
                  SeProfileSingleProcessPrivilege - OFF
                  SeIncreaseBasePriorityPrivilege - OFF
                  SeCreatePagefilePrivilege       - OFF
                  SeBackupPrivilege               - OFF
                  SeRestorePrivilege              - OFF
                  SeShutdownPrivilege             - OFF
                  SeDebugPrivilege                - ON
                  SeSystemEnvironmentPrivilege    - OFF
                  SeChangeNotifyPrivilege         - ON
                  SeRemoteShutdownPrivilege       - OFF
                  SeUndockPrivilege               - OFF
                  SeManageVolumePrivilege         - OFF
                  SeImpersonatePrivilege          - ON
                  SeCreateGlobalPrivilege         - ON
                  SeIncreaseWorkingSetPrivilege   - OFF
                  SeTimeZonePrivilege             - OFF
                  SeCreateSymbolicLinkPrivilege   - OFF

Active Controls:
------------------------------------------------------------------
  4.1 Form Class   : TAppBuilder
  4.2 Form Text    : LogoTid - Delphi XE - uMain [Running] [Built]
  4.3 Control Class:
  4.4 Control Text :

Computer:
------------------------------------------------------------------------------------------------
  5.1 Name          : OLE-LAPTOP
  5.2 Total Memory  : 3891 Mb
  5.3 Free Memory   : 778 Mb
  5.4 Total Disk    : 120 Gb
  5.5 Free Disk     : 57,93 Gb
  5.6 System Up Time: 1 day, 23 hours, 16 minutes, 56 seconds
  5.7 Processor     : Intel(R) Core(TM) i5 CPU       M 520  @ 2.40GHz
  5.8 Display Mode  : 1920 x 1200, 32 bit
  5.9 Display DPI   : 96
  5.10 Video Card   : Intel(R) Graphics Media Accelerator HD (driver 8.15.10.2025 - RAM 1721 MB)
  5.11 Printer      : RICOH Aficio 2232C RPCS (driver 1.0.0)

Operating System:
--------------------------------------------
  6.1 Type    : Microsoft Windows 7 (64 bit)
  6.2 Build # : 7600
  6.3 Update  :
  6.4 Language: Danish
  6.5 Charset : 0

Call Stack Information:
-------------------------------------------------------------------
|Address |Module      |Unit       |Class|Procedure/Method   |Line |
-------------------------------------------------------------------
|Running Thread: ID=5632; Priority=0; Class=; [Main]              |
|-----------------------------------------------------------------|
|00D171A1|LogoTid.exe |LogoTid.dpr|     |                   |32[5]|
|76A73675|kernel32.dll|           |     |BaseThreadInitThunk|     |
-------------------------------------------------------------------

Assembler Information:
-----------------------------------------------------------------
; System.TObject.FreeInstance
; ----------------------------
00406294  push    ebx
00406295  mov     ebx, eax
00406297  mov     eax, ebx
00406299  call    System.TObject.CleanupInstance
0040629E  mov     eax, ebx
004062A0  call    System._FreeMem                 ; <-- EXCEPTION
004062A5  pop     ebx
004062A6  ret

Registers:
-----------------------------
EAX: 02AF8058   EDI: 00000001
EBX: 004062A5   ESI: 004062A5
ECX: 0041D700   ESP: 0018FE98
EDX: 004062A5   EIP: 004062A0

Stack:               Memory Dump:
------------------   ---------------------------------------------------------------------------
0018FE98: FFFFFF02   004062A0: E8 3B E7 FF FF 5B C3 90 83 C0 CC 8B 00 C3 8B C0  .;...[..........
0018FE9C: 00404B78   004062B0: 84 D2 74 08 83 C4 F0 E8 54 05 00 00 84 D2 74 0F  ..t.....T.....t.
0018FEA0: 02B1CEC0   004062C0: E8 A3 05 00 00 64 8F 05 00 00 00 00 83 C4 0C C3  .....d..........
0018FEA4: 02B1CEC0   004062D0: E8 E3 05 00 00 84 D2 7E 05 E8 82 05 00 00 C3 90  .......~........
0018FEA8: 00404BC2   004062E0: 85 C0 74 07 B2 01 8B 08 FF 51 FC C3 53 56 57 89  ..t......Q..SVW.
0018FEAC: 02B1CEC0   004062F0: C3 89 D7 AB 8B 4B CC 31 C0 51 C1 E9 02 49 F3 AB  .....K.1.Q...I..
0018FEB0: 0018FEE8   00406300: 59 83 E1 03 F3 AA 89 D0 89 E2 8B 4B AC 85 C9 74  Y..........K...t
0018FEB4: 004062A5   00406310: 01 51 8B 5B D0 85 DB 74 04 8B 1B EB ED 39 D4 74  .Q.[...t.....9.t
0018FEB8: 03A02F01   00406320: 1D 5B 8B 0B 83 C3 04 8B 73 10 85 F6 74 06 8B 7B  .[......s...t..{
0018FEBC: 00406865   00406330: 14 89 34 07 83 C3 1C 49 75 ED 39 D4 75 E3 5F 5E  ..4....Iu.9.u._^
0018FEC0: 0045B949   00406340: 5B C3 8B C0 53 56 89 C3 89 C6 8B 36 8B 56 B4 8B  [...SV.....6.V..
0018FEC4: 03A02FA0   00406350: 76 D0 85 D2 74 07 E8 85 36 00 00 89 D8 85 F6 75  v...t...6......u
0018FEC8: 03A02F01   00406360: E9 89 D8 E8 78 06 00 00 5E 5B C3 90 87 D1 81 F9  ....x...^[......
0018FECC: 004062EB   00406370: 00 00 00 FF 73 11 81 F9 00 00 00 FE 72 07 0F BF  ....s.......r...
0018FED0: 00912606   00406380: C9 03 08 FF 21 FF E1 81 E1 FF FF FF 00 01 C1 89  ....!...........
0018FED4: 00000000   00406390: D0 8B 11 E9 A8 59 00 00 C3 8D 40 00 3B C2 0F 94  .....Y....@.;...

--- Edit

Ok, tried turning of parts of my program until the error went away, and found the troublemaker.

It's my webservice WSDL generated proxy. If I create the proxy object without calling any functions on the service, it throws the error.

I've created a test project without any other code than the proxy object creation and it also throws the error. I've also tried with another webservice, same error. Both webservices was created with Delphi 2006 (.net 1.1).

Lastly I tried with a .net 4.0 webservice created in VS2010. No problems. So either Delphi XE is projects is not compatible with .net 1.1 webservices or Delphi 2006 webservices. Either way it's a mess.

Any thouhts on how to solve this, maybe a workaround?

Body:
The log won't help here. It looks like a memory corruption issue, which can happen if your code performs indexed operations on strings (writing to string's character position, for example) and you have not fixed all code where string is casted to PChar or similar code.

In other words, you have to perform careful analysis of your code. Start with turning off some modules and code blocks completely until the exception disappears. Then start adding them one by one.


问:
How to configure flume service on cloudera manager?
I am trying to configure a flume service in cloudera manager. I have a custom flume interceptor. Where should i place the custom built interceptor jar file?</p>

答:
If you are using CDH 5.x
You can place the custom flume jar in

```<code>/var/lib/flume-ng/plugins.d/phc/lib
</code>```

The jar needs to be in all the flume nodes processing the data.

Body:
If you are using CDH 5.x
You can place the custom flume jar in

/var/lib/flume-ng/plugins.d/phc/lib

The jar needs to be in all the flume nodes processing the data.


答:
Go figure but documenation says it's

```<code>pygame.time.Clock
</code>```

note the uppercase C in clock vs lowercase.

Title: pygame.time.clock() or pygame.clock.tick() error

Body:
I have a main loop in my code where it loops everything and when I run my code I get this error:

    Traceback (most recent call last):
      File "C:\Users\Javier\Documents\Python Pygame\First Game\First
    Game.py", line 17, in <module>
        clock=pygame.time.clock()
    AttributeError: module 'pygame.time' has no attribute 'clock'

I understand what the error is: it means it can't find the 'class' clock and in another instance where I used pygame.tick.clock() I got the same error.

    #import modules here

    import pygame

    #define what colours are
    black=(0,0,0)
    white=(255,255,255)
    turquoise=(64,224,208)
    #initalise pygame
    pygame.init()
    #set up screen
    screen=pygame.display.set_mode((400,400))
    #what the screen is called and backgroud colour
    screen.fill(black)
    pygame.display.set_caption("Snake!")
    #set a variable for how quick the game runs
    clock=pygame.time.clock()

    '''making future references easier
    eval just takes code as a string and runs it
    eg:
    instead of doing print(5+8)
    you can do eval(print(5+8))'''
    def key(key):
        return pygame.ket.get_pressed()[eval("pygame.K_"+key)]
    #draw the snake
    snake=(50,150,150,50)
    #display.flip shows what has been drawn on the screen eg the snake
    while True:
        pygame.draw.rect(screen,turquoise,snake)
        pygame.display.flip()
        clock.tick(60)

When I comment the problem code (clock.tick() and pygame.time.clock)  the window opens and displays the turquoise "snake" but it has no limiting factor that slows down the rate of the loop executing.

Body:
Go figure but documenation says it's

pygame.time.Clock

note the uppercase C in clock vs lowercase.


问:
How do you change the variable in a settings file from an external HTML form?
How do you change the variable in a settings file from an external HTML form?

So, I have a setup.html that will include all the forms. Then I have a settings.php which will save the settings and then impliment on the index.php.

How do I make so that I can update and SAVE the input from the setup.html to settings.php?

It's constructed this way:

```<code>$Color = "red";
$Name  = "Name";
</code>```

etc...

I've looked everywhere and found nothing about saving the input, thanks.

答:
If you have access to edit local files then you should consider sqlite, it comes bundled with PHP and can give you database functionality without the need to install a database.

heres a tutorial that explains how to use it

as well as the Documentation

Essentially you have a file (possibly settings.db) that serves as a database. You then open up a "connection" to that file and issue regular SQL commands to read and write your data. Just make sure that you put this file outside of your webroot, otherwise visitors would be able to download it and see all your content.

Body:
How do you change the variable in a settings file from an external HTML form?

So, I have a setup.html that will include all the forms. Then I have a settings.php which will save the settings and then impliment on the index.php.

How do I make so that I can update and SAVE the input from the setup.html to settings.php?

It's constructed this way:

$Color = "red";
$Name  = "Name";

etc...

I've looked everywhere and found nothing about saving the input, thanks.


问:
CLIPS - EnvAssertString vs EnvAssert
Is there a difference in functionality between EnvAssert and EnvAssertString?
I tried to assert a fact using both, but the related rule is activated when I assert the fact using EnvAssertString and is not activated when I assert the fact using EnvAssert!

Here is my definitions in constructs.clp file:

```<code>(deftemplate Safety
    (slot SafetyStatus (type SYMBOL) (default True) (allowed-symbols True False))
    (slot DistanceToObject (type INTEGER) (default 0))
    (slot BatteryLevel (type INTEGER) (default 0)))

(defrule r11
    ?f <- (Safety (SafetyStatus True) (BatteryLevel ?bat) (DistanceToObject ?dist))
    (test (and (> ?bat 20) (> ?dist 3)))
    =>
    (modify ?f (SafetyStatus False)))
</code>```

And this is my C++ code snippet:

```<code>// The rule is activated if I use this line
EnvAssertString(theEnv, "(Safety (BatteryLevel 100)(DistanceToObject 4))");

// The rule is not activated if I used these lines
templatePtr = EnvFindDeftemplate(theEnv, "Safety");
newFact = EnvCreateFact(theEnv, templatePtr);
if (newFact == NULL) return -1;

theValue.type = INTEGER;
theValue.value = EnvAddLong(theEnv, 100);
EnvPutFactSlot(theEnv, newFact, "BatteryLevel", &theValue);

theValue.type = INTEGER;
theValue.value = EnvAddLong(theEnv, 4);
EnvPutFactSlot(theEnv, newFact, "DistanceToObject", &theValue);

EnvAssert(theEnv, newFact);

EnvRun(theEnv, -1L);
</code>```

Calling EnvAssertString asserts the following:

```<code>==> f-1     (Safety (SafetyStatus nil) (DistanceToObject 4) (BatteryLevel 100))
</code>```

while calling EnvAssert asserts the following:

```<code>==> f-1     (Safety (SafetyStatus True) (DistanceToObject 4) (BatteryLevel 100))
</code>```

Could someone please tell me where is the problem?

答: AssertString is a wrapper for Assert. Basically it parses the string argument, creates a fact of the appropriate type, assigns the specified slot values, assigns default values to unspecified slots, and then asserts the fact. In your example using EnvAssert, you need to call "EnvAssignFactSlotDefaults(theEnv,newFact);" so that default values will be assigned to the slots you have left unspecified. This will cause the value True to be assigned to the SafetyStatus slot and allows the r11 rule to be matched.</p>

Title: CLIPS - EnvAssertString vs EnvAssert

Body:
Is there a difference in functionality between EnvAssert and EnvAssertString?
I tried to assert a fact using both, but the related rule is activated when I assert the fact using EnvAssertString and is not activated when I assert the fact using EnvAssert!

Here is my definitions in constructs.clp file:

(deftemplate Safety
    (slot SafetyStatus (type SYMBOL) (default True) (allowed-symbols True False))
    (slot DistanceToObject (type INTEGER) (default 0))
    (slot BatteryLevel (type INTEGER) (default 0)))

(defrule r11
    ?f <- (Safety (SafetyStatus True) (BatteryLevel ?bat) (DistanceToObject ?dist))
    (test (and (> ?bat 20) (> ?dist 3)))
    =>
    (modify ?f (SafetyStatus False)))

And this is my C++ code snippet:

// The rule is activated if I use this line
EnvAssertString(theEnv, "(Safety (BatteryLevel 100)(DistanceToObject 4))");

// The rule is not activated if I used these lines
templatePtr = EnvFindDeftemplate(theEnv, "Safety");
newFact = EnvCreateFact(theEnv, templatePtr);
if (newFact == NULL) return -1;

theValue.type = INTEGER;
theValue.value = EnvAddLong(theEnv, 100);
EnvPutFactSlot(theEnv, newFact, "BatteryLevel", &theValue);

theValue.type = INTEGER;
theValue.value = EnvAddLong(theEnv, 4);
EnvPutFactSlot(theEnv, newFact, "DistanceToObject", &theValue);

EnvAssert(theEnv, newFact);

EnvRun(theEnv, -1L);

Calling EnvAssertString asserts the following:

==> f-1     (Safety (SafetyStatus nil) (DistanceToObject 4) (BatteryLevel 100))

while calling EnvAssert asserts the following:

==> f-1     (Safety (SafetyStatus True) (DistanceToObject 4) (BatteryLevel 100))

Could someone please tell me where is the problem?


问:
Multiple Elements to Flat String Transform
I am looking to transform multiple elements from source xml and combine them in single target string element in comma separated text.

Conditions
Source Inputs are boolean type, only if value true it should be included in target list

E.g. XML

```<code><Root-Element>
<EnggTypes>
<Engg1>true</Engg1>
<Engg2>true</Engg2>
<Engg3>false</Engg3>
<Engg4>false</Engg4>
<Engg5>true</Engg5>
</EnggTypes>
</Root-Element>
</code>```

Expected Transform

```<code><Root-Element>
<RoleTypes>Role1,Role2,Role5</RoleTypes>
</Root-Element>
</code>```

Looking to achieve same in XSL 1.0 or 2.0

I started overthinking and tried to use a variable on a target side to see if I can do some choose/when to construct the string using previous value and concatenate but seems like that will not work as variable value cannot be changed once set!

```<code><xsl:variable name="roleVar">
<xsl:if test="Engg1/text()='true'">Role1</if>
<xsl:if test="Engg2/text()='true'">concat(roleVar,",",Role2)</if>
<xsl:if test="Engg3/text()='true'">concat(roleVar,",",Role3)</if>
<xsl:if test="Engg4/text()='true'">concat(roleVar,",",Role4)</if>
<xsl:if test="Engg5/text()='true'">concat(roleVar,",",Role5)</if>
</xsl:variable>
</code>```

Any inputs appreciated.

Thanks in advance

答:
You can select those elements and construct the value in one expression:

```<code><xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="EnggTypes">
        <xsl:copy>
            <xsl:value-of select="*[. = 'true']/concat('Role', replace(local-name(), '[^0-9]+', ''))" separator=","/>
        </xsl:copy>
    </xsl:template>

</xsl:transform>
</code>```

http://xsltransform.net/bEzjRJR/1 gives

```<code><Root-Element>
<EnggTypes>Role1,Role2,Role5</EnggTypes>
</Root-Element>
</code>```

Body:
I am looking to transform multiple elements from source xml and combine them in single target string element in comma separated text.

Conditions
Source Inputs are boolean type, only if value true it should be included in target list

E.g. XML

<Root-Element>
<EnggTypes>
<Engg1>true</Engg1>
<Engg2>true</Engg2>
<Engg3>false</Engg3>
<Engg4>false</Engg4>
<Engg5>true</Engg5>
</EnggTypes>
</Root-Element>

Expected Transform

<Root-Element>
<RoleTypes>Role1,Role2,Role5</RoleTypes>
</Root-Element>

Looking to achieve same in XSL 1.0 or 2.0

I started overthinking and tried to use a variable on a target side to see if I can do some choose/when to construct the string using previous value and concatenate but seems like that will not work as variable value cannot be changed once set!

<xsl:variable name="roleVar">
<xsl:if test="Engg1/text()='true'">Role1</if>
<xsl:if test="Engg2/text()='true'">concat(roleVar,",",Role2)</if>
<xsl:if test="Engg3/text()='true'">concat(roleVar,",",Role3)</if>
<xsl:if test="Engg4/text()='true'">concat(roleVar,",",Role4)</if>
<xsl:if test="Engg5/text()='true'">concat(roleVar,",",Role5)</if>
</xsl:variable>

Any inputs appreciated.

Thanks in advance

Body:
You can select those elements and construct the value in one expression:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="EnggTypes">
        <xsl:copy>
            <xsl:value-of select="*[. = 'true']/concat('Role', replace(local-name(), '[^0-9]+', ''))" separator=","/>
        </xsl:copy>
    </xsl:template>

</xsl:transform>

http://xsltransform.net/bEzjRJR/1 gives

<Root-Element>
<EnggTypes>Role1,Role2,Role5</EnggTypes>
</Root-Element>


问:
Python Regex to replace absolute paths in text to relative paths added in quotes
I'm new to regex and was trying to solve the below problem.

Input String -  String that has a path as /Users/MyName/moreofPath/  with additional text

Output String - String that has a path as "$relativePath/moreofPath/"  with additional text

The absolute path in the sentence is to be recognized by

1) where /Users/MyName starts

2) where last / that comes before any other special character or space ends

This should be replaced by relative path in quotes.
Can someone please help me find correct regex for this.

答:
using regex that match any path follow by username as long its not space</p>

```<code>import re
input_string = "String that has a path as /Users/MyName/moreofPath/ with additional text"
output_string = re.sub(r'/Users/MyName([^\s]*)', r'"$relativePath\1"', input_string)
# 'String that has a path as "$relativePath/moreofPath/" with additional text'
</code>```

Body:
using regex that match any path follow by username as long its not space

import re
input_string = "String that has a path as /Users/MyName/moreofPath/ with additional text"
output_string = re.sub(r'/Users/MyName([^\s]*)', r'"$relativePath\1"', input_string)
# 'String that has a path as "$relativePath/moreofPath/" with additional text'


问:
How to split on first delimiter
Say I have an array of items I want to split on (this is for a page ).

I'm trying to 'intelligently' extract out a title, but only the relevant part.

I also dont want leading/trailing spaces.

I'm not quite sure how to go about doing this though.. without putting a bunch of loops inside of other loops.

```<code>function cleanTitle(title) {
    // Extract up to first delimiter
    var delims = ['|','·','-',':'];
}
</code>```

I am using jquery.

I also put the delims array in order of what I feel is most important. Instead of searching the entire title for the first array item before moving on to the next, I think it should do the entire string one letter at a time... each letter of the string it will check if its contained within that array. If not, it moves on. I know a lot of urls might contain even 3 out of all 4 of these, and then it wouldnt really work well otherwise.

答:
All of these answers ignore the obvious and most elegant solution (although RegEx is certainly an improvement over a loop).  Just use string.split(/^(.*?)[|·\-:]/,1)  This is ECMAScript 1 so I don't see why it wouldn't be available in all browsers.

Syntax

string.split(separator, limit)

Parameters

Parameter   Description

separator                  Optional. Specifies the character, or the regular
                            expression, to use for splitting the string. If
                            omitted, the entire string will be returned (an
                            array with only one item)

limit                      Optional. An integer that specifies the number of
                            splits, items after the split limit will not be
                            included in the array

Title: How to split on first delimiter

Body:
Say I have an array of items I want to split on (this is for a page ).

I'm trying to 'intelligently' extract out a title, but only the relevant part.

I also dont want leading/trailing spaces.

I'm not quite sure how to go about doing this though.. without putting a bunch of loops inside of other loops.

function cleanTitle(title) {
    // Extract up to first delimiter
    var delims = ['|','·','-',':'];
}

I am using jquery.

I also put the delims array in order of what I feel is most important. Instead of searching the entire title for the first array item before moving on to the next, I think it should do the entire string one letter at a time... each letter of the string it will check if its contained within that array. If not, it moves on. I know a lot of urls might contain even 3 out of all 4 of these, and then it wouldnt really work well otherwise.


问:
How to delete a file with .txt extension from a directory using ruby script
I want to delete all files present in page/sanjay directory with .txt extension.

I tried the following code

```<code>Dir.glob('/page/sanjay/*.txt').each { |file| File.delete(file)}
</code>```

and got some error:

```<code>./newTrySanjay.rb: line 1: syntax error near unexpected token `'/page/sanjay/*.txt''
./newTrySanjay.rb: line 1: `Dir.glob('/page/sanjay/*.txt').each { |file| File.delete(file)}'
</code>```

答:
You can simplify this to:

```<code>File.delete(*Dir.glob('/page/sanjay/*.txt'))
</code>```

delete accepts a list of filenames, and *Dir.glob will burst the array normally returned into that list.

Body:
I want to delete all files present in page/sanjay directory with .txt extension.

I tried the following code

Dir.glob('/page/sanjay/*.txt').each { |file| File.delete(file)}

and got some error:

./newTrySanjay.rb: line 1: syntax error near unexpected token `'/page/sanjay/*.txt''
./newTrySanjay.rb: line 1: `Dir.glob('/page/sanjay/*.txt').each { |file| File.delete(file)}'

Body:
You can simplify this to:

File.delete(*Dir.glob('/page/sanjay/*.txt'))

delete accepts a list of filenames, and *Dir.glob will burst the array normally returned into that list.


问:
Making my first angular directive. 'vm' is undefined
```<code>(function () {
  'use strict';

  angular
    .module('contacts.directives')
    .directive('hotkeys', HotkeysDirective);

  HotkeysDirective.$inject = ['$resource', '$document'];

  function HotkeysDirective($resource, $document) {
    var directive = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      link: link,
      controller: 'AddManagerController',
      controllerAs: 'vm',
      scope: {},
      bindToController: {
        },
    };

    return directive;

    function link(scope, element, attrs, modelCtrl) {

      $document.bind('keypress', function (e) {
        var key = String.fromCharCode(e.which);
        if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
          scope.$broadcast('keypress', e, e.which);
        }
      });

      scope.$on('keypress', function (event, key) {
        // do stuff
        scope.$apply();
      });
    }
  }
}());
</code>```

This is the code that I think is not working...

```<code>HotkeysDirective.$inject = ['$resource', '$document'];

function HotkeysDirective($resource, $document) {
  var directive = {
    templateUrl: '/request-off-work/contacts/client/views/ui/hotkeys.ui.html',
    link: link,
    controller: 'AddManagerController',
    controllerAs: 'vm',
    scope: {},
    bindToController: {
      },
  };

  return directive;

  function link(scope, element, attrs, modelCtrl) {
</code>```

It's saying vm is undefined when I'm using controllerAs: 'vm', In the AddManagerController, it says 'var vm = this;'. Also not sure why scope: {} needs to be there, and I'll figure out bindToController eventually... I think I need to bind vm.credentials.groups to it.

Update: here's the controller

```<code>function AddManagerController($scope, $document, $rootScope, $state, $window, Authentication, ContactsService, Notification) {
  var vm = this;
  vm.authentication = Authentication;
  vm.credentials = {};
  vm.showGroups = [null, false, false, false, false, false, false];
</code>```

答: You don't need to use scope because you already bind to controller instance this.

Body:
(function () {
  'use strict';

  angular
    .module('contacts.directives')
    .directive('hotkeys', HotkeysDirective);

  HotkeysDirective.$inject = ['$resource', '$document'];

  function HotkeysDirective($resource, $document) {
    var directive = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      link: link,
      controller: 'AddManagerController',
      controllerAs: 'vm',
      scope: {},
      bindToController: {
        },
    };

    return directive;

    function link(scope, element, attrs, modelCtrl) {

      $document.bind('keypress', function (e) {
        var key = String.fromCharCode(e.which);
        if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
          scope.$broadcast('keypress', e, e.which);
        }
      });

      scope.$on('keypress', function (event, key) {
        // do stuff
        scope.$apply();
      });
    }
  }
}());

This is the code that I think is not working...

HotkeysDirective.$inject = ['$resource', '$document'];

function HotkeysDirective($resource, $document) {
  var directive = {
    templateUrl: '/request-off-work/contacts/client/views/ui/hotkeys.ui.html',
    link: link,
    controller: 'AddManagerController',
    controllerAs: 'vm',
    scope: {},
    bindToController: {
      },
  };

  return directive;

  function link(scope, element, attrs, modelCtrl) {

It's saying vm is undefined when I'm using controllerAs: 'vm', In the AddManagerController, it says 'var vm = this;'. Also not sure why scope: {} needs to be there, and I'll figure out bindToController eventually... I think I need to bind vm.credentials.groups to it.

Update: here's the controller

function AddManagerController($scope, $document, $rootScope, $state, $window, Authentication, ContactsService, Notification) {
  var vm = this;
  vm.authentication = Authentication;
  vm.credentials = {};
  vm.showGroups = [null, false, false, false, false, false, false];


问:
Fixed-Point binary unpacking in python
I am struggling with a number-format problem in Python 3.6. My goal is to convert binary data from a file into printable decimal numbers. As an example, I need to convert two little-endian bytes in the form of a byte string...

b'\x12\00'

into its big-endian binary form...

0000000000010010

and finally to its 16-bit fixed-point Q15 decimal number form...

(1 / 4096) + (1 / 16384) = 0.00030517578 (basically, we've made the 2 bytes above human-readable)

In my failed attempts, the struct.unpack function seemed promising, but my low-level / number representation experience just isn't very mature at the moment.

Failed Attempt:

```<code>struct.unpack('<h', b'\x12\x00') # Yields (18,)
</code>```

The above code gets me "18", which would be fine if the bytes represented an integer, but they do not.

Any help / advice would be appreciated. Thank you!

答:
Answered by @jasonharper in the question comments--

The bytes do represent an integer - which has been shifted by 15 bits. Divide by 32768 (2**15) to get the actual Q15 value. (This doesn't match the value you calculated, but that's because you did the math wrong - the two set bits actually have place values of 1/2048 and 1/16384.)

I achieved the proper value via the following code--

```<code>struct.unpack('<h', b'\x12\x00')[0] / (2**15)
</code>```

Title: Fixed-Point binary unpacking in python

Body:
I am struggling with a number-format problem in Python 3.6. My goal is to convert binary data from a file into printable decimal numbers. As an example, I need to convert two little-endian bytes in the form of a byte string...

b'\x12\00'

into its big-endian binary form...

0000000000010010

and finally to its 16-bit fixed-point Q15 decimal number form...

(1 / 4096) + (1 / 16384) = 0.00030517578 (basically, we've made the 2 bytes above human-readable)

In my failed attempts, the struct.unpack function seemed promising, but my low-level / number representation experience just isn't very mature at the moment.

Failed Attempt:

struct.unpack('<h', b'\x12\x00') # Yields (18,)

The above code gets me "18", which would be fine if the bytes represented an integer, but they do not.

Any help / advice would be appreciated. Thank you!

Body:
Answered by @jasonharper in the question comments--

The bytes do represent an integer - which has been shifted by 15 bits. Divide by 32768 (2**15) to get the actual Q15 value. (This doesn't match the value you calculated, but that's because you did the math wrong - the two set bits actually have place values of 1/2048 and 1/16384.)

I achieved the proper value via the following code--

struct.unpack('<h', b'\x12\x00')[0] / (2**15)


问:
Why does Eclipse sometimes ignore my breakpoints?
I'm android developer and I use Eclipse.

Sometimes, when I am debugging my apps, Eclipse doesn't stop on my breakpoints. Eclipse shows a "v" symbol on the breakpoint.  I think this symbol means that Eclipse has passed the breakpoint without problems, but I would like Eclipse to stop when it reaches the breakpoint.

Of course, I have pressed the debug button (the icon with the green bug on it.)

How can I avoid this behavior?

答: solved, it's because i have that activity in another process in the manifest... wow</p>


问:
How to reset a job status to inactive?
I have a job J1 which is dependent from the success of a job J0.
First time J0 failed so J1 is currently under status "failure".
This is fine.

Anyway I'd like now to reset its status so I can perform another test.
How to set J1's status from "FAILURE"  to "INACTIVE", in other words its initial status?

答:
You can use below command. Question been asked long back, just answering so that other people can refer it !!</p>

```<code>sendevent -E CHANGE_STATUS -s INACTIVE -J {job name}
</code>```

Title: How to reset a job status to inactive?

Body:
You can use below command. Question been asked long back, just answering so that other people can refer it !!

sendevent -E CHANGE_STATUS -s INACTIVE -J {job name}


问:
How to have powershell use a else statement to search another folder
I am trying to import some PST files into Outlook automatically, I currently am using the following script

```<code>Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
dir “$env:USERPROFILE\appdata\local\microsoft\outlook\.pst” | % {
$namespace.AddStore($_.FullName) }
</code>```

I would like to add a else statement so that if the pst file is not found in the first location then it will check in "$env:USERPROFILE\Documents\Outlook Files"

答:
For anyone curious here is my new final script

```<code>    $pathA = “$env:USERPROFILE\AppData\Local\Microsoft\*.pst”
    $pathB = “$env:USERPROFILE\Documents\Outlook Files\*.pst”

    $files = Get-ChildItem $pathA

    Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
    $outlook = new-object -comobject outlook.application
    $namespace = $outlook.GetNameSpace("MAPI")

    if($files){
    dir “$env:USERPROFILE\AppData\Local\Microsoft\*.pst” | % {
    $namespace.AddStore($_.FullName) }
    }
    else {
    dir “$env:USERPROFILE\Documents\Outlook Files\*.pst” | % {
    $namespace.AddStore($_.FullName) }
    }
</code>```

Thanks again Charlie, That was a great help!

Body:
I am trying to import some PST files into Outlook automatically, I currently am using the following script

Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
dir “$env:USERPROFILE\appdata\local\microsoft\outlook\.pst” | % {
$namespace.AddStore($_.FullName) }

I would like to add a else statement so that if the pst file is not found in the first location then it will check in "$env:USERPROFILE\Documents\Outlook Files"

Body:
For anyone curious here is my new final script

    $pathA = “$env:USERPROFILE\AppData\Local\Microsoft\*.pst”
    $pathB = “$env:USERPROFILE\Documents\Outlook Files\*.pst”

    $files = Get-ChildItem $pathA

    Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
    $outlook = new-object -comobject outlook.application
    $namespace = $outlook.GetNameSpace("MAPI")

    if($files){
    dir “$env:USERPROFILE\AppData\Local\Microsoft\*.pst” | % {
    $namespace.AddStore($_.FullName) }
    }
    else {
    dir “$env:USERPROFILE\Documents\Outlook Files\*.pst” | % {
    $namespace.AddStore($_.FullName) }
    }

Thanks again Charlie, That was a great help!


问:
Radio button adding class element
I need to create 2 radio buttons.

When a users is on the page, the radio buttons are unchecked.

Inside radio button content is the CTA button which will be greyed

The CTA button will change the color only when the user selects the radio.

I have created style for the button which I want to use rather switch back and forth when the radio button is selected.

Here's an example.

Can someone guide me on how to add and remove classes so the colors switch within jQuery?

https://codepen.io/Ambuja/pen/BZNzRx

$('input').prop('checked', false);
$('span a').css('background-color','grey')
$('input').on('change', function () {
    if ($(this).is(':checked')) {
        var dt = $(this).data('title')
        $('span a').css('background-color','grey')
        $('#' + dt).css('background-color','orange')
        console.log(dt)
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
    font-family: $verdana;
    font-size:12px;
    margin-left:13px;
    font-weight: normal;
}

}
input[type="radio"]:checked + label:before {

    text-align: center;
}
.high {
    color:yellow;
}
 </code>```

    <input type="radio" name="form-radio" id="workshops" value="high" data-title="workshopcl" checked="">
    Workshops

This is random text

    WorkShops

    <input type="radio" name="form-radio" id="courses" data-title="cou" value="option2">
    Courses

This is a random text

    Courses

```

答:
$('input').prop('checked', false);
$('span a').addClass('greyColor');
$('input').on('change', function (el) {
  debugger;
    if ($(this).is(':checked')) {
        var dt = $(this).data('title');
        //if you have only 2 radio btn, you could use the below commented code.

        //if(dt=="cou"){
          //  $('#cou').attr('href','https://www.google.com');
          //  $('#cou').addClass('orangeColor');
          //  $('#workshopcl').removeClass('orangeColor');
          //  $('#workshopcl').attr('href','#');
        //}
        //else{
          //  $('#workshopcl').addClass('orangeColor');
          //  $('#workshopcl').attr('href','https://www.gmail.com');
          //  $('#cou').removeClass('orangeColor');
          //  $('#cou').attr('href','#');
//        }

        $('span a').removeClass('orangeColor');
        $('#' + dt).addClass('orangeColor');
        $('span a').attr('href','#');
        if(dt=="cou"){
            $('#' + dt).attr('href','https://www.google.com');
        }
        else{ // if you have more than 2 radio buttons then use if-else-if statement.
            $('#' + dt).attr('href','https://www.gmail.com');
        }
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
    font-family: $verdana;
    font-size:12px;
    margin-left:13px;
    font-weight: normal;
}

input[type="radio"]:checked + label:before {

    text-align: center;
}
.high {
    color:yellow;
}

.greyColor{
  background-color:grey;
}

.orangeColor{
  background-color:orange;
}
 </code>```

    <input type="radio" name="form-radio" id="workshops" value="high" data-title="workshopcl" checked="">
Workshops

This is random text

       WorkShops

<input type="radio" name="form-radio" id="courses" data-title="cou" value="option2">
Courses

This is a random text

                        Courses

```

Title: Radio button adding class element

Body:
I need to create 2 radio buttons.

When a users is on the page, the radio buttons are unchecked.

Inside radio button content is the CTA button which will be greyed

The CTA button will change the color only when the user selects the radio.

I have created style for the button which I want to use rather switch back and forth when the radio button is selected.

Here's an example.

Can someone guide me on how to add and remove classes so the colors switch within jQuery?

https://codepen.io/Ambuja/pen/BZNzRx

$('input').prop('checked', false);
$('span a').css('background-color','grey')
$('input').on('change', function () {
    if ($(this).is(':checked')) {
        var dt = $(this).data('title')
        $('span a').css('background-color','grey')
        $('#' + dt).css('background-color','orange')
        console.log(dt)
    }
})

label {
    font-family: $verdana;
    font-size:12px;
    margin-left:13px;
    font-weight: normal;
}

}
input[type="radio"]:checked + label:before {

    text-align: center;
}
.high {
    color:yellow;
}

    <input type="radio" name="form-radio" id="workshops" value="high" data-title="workshopcl" checked="">
    Workshops

This is random text

    WorkShops

    <input type="radio" name="form-radio" id="courses" data-title="cou" value="option2">
    Courses

This is a random text

    Courses

Body:
$('input').prop('checked', false);
$('span a').addClass('greyColor');
$('input').on('change', function (el) {
  debugger;
    if ($(this).is(':checked')) {
        var dt = $(this).data('title');
        //if you have only 2 radio btn, you could use the below commented code.

        //if(dt=="cou"){
          //  $('#cou').attr('href','https://www.google.com');
          //  $('#cou').addClass('orangeColor');
          //  $('#workshopcl').removeClass('orangeColor');
          //  $('#workshopcl').attr('href','#');
        //}
        //else{
          //  $('#workshopcl').addClass('orangeColor');
          //  $('#workshopcl').attr('href','https://www.gmail.com');
          //  $('#cou').removeClass('orangeColor');
          //  $('#cou').attr('href','#');
//        }

        $('span a').removeClass('orangeColor');
        $('#' + dt).addClass('orangeColor');
        $('span a').attr('href','#');
        if(dt=="cou"){
            $('#' + dt).attr('href','https://www.google.com');
        }
        else{ // if you have more than 2 radio buttons then use if-else-if statement.
            $('#' + dt).attr('href','https://www.gmail.com');
        }
    }
})

label {
    font-family: $verdana;
    font-size:12px;
    margin-left:13px;
    font-weight: normal;
}

input[type="radio"]:checked + label:before {

    text-align: center;
}
.high {
    color:yellow;
}

.greyColor{
  background-color:grey;
}

.orangeColor{
  background-color:orange;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="medium-6 large-6 columns">
    <input type="radio" name="form-radio" id="workshops" value="high" data-title="workshopcl" checked="">
<label id="workshoping" for="workshops">Workshops</label>

                       <p>This is random text</p>

       <span><a href="#" id="workshopcl">WorkShops</a></span>
                        </div>

  <div class="medium-6 large-6 columns">
<input type="radio" name="form-radio" id="courses" data-title="cou" value="option2">
<label for="courses">Courses</label>
<br>
<p>This is a random text</p>

                        <span><a href="#" id="cou">Courses</a></span>

                        </div>

  </div>


问:
How to assign a value of 10^100 to an integer variable in C?
I was working on a problem to count number of digits in a number but according to the constraints the number should be of the range 10^100(10 to the power 100). I have tried it using limits.h but it did not work. Could anyone suggest a way to do that?</p>

```<code>int main(){

    int n=LONG_MAX;
    int count;
    scanf("%d",&n);
    while(n!=0)
    {
        n=n/10;
        count++;
    }
    printf("%d",count);
    return 0;
}
</code>```

答:
As others have said, you don't need to store it as a number. Make a character array of length 100. Initialize the values to something non-numeric. From CIN or however else you're getting the number, save it to that character array. Then count how many numbers there are before you get to a non-number.

Pseudocode:

```<code>BigNumber = new char[100];

cout << "Input the number:\n";

cin >> BigNumber;

digits = 0;
for(i = 0; i < 100; i++)
{
    if( IsNumeric(BigNumber[i]) )
    {
        digits++;
    }
    else
    {
        break;
    }
}

cout << "That number is " << digits << " digits long";
</code>```

Body:
I was working on a problem to count number of digits in a number but according to the constraints the number should be of the range 10^100(10 to the power 100). I have tried it using limits.h but it did not work. Could anyone suggest a way to do that?

int main(){

    int n=LONG_MAX;
    int count;
    scanf("%d",&n);
    while(n!=0)
    {
        n=n/10;
        count++;
    }
    printf("%d",count);
    return 0;
}

Body:
As others have said, you don't need to store it as a number. Make a character array of length 100. Initialize the values to something non-numeric. From CIN or however else you're getting the number, save it to that character array. Then count how many numbers there are before you get to a non-number.

Pseudocode:

BigNumber = new char[100];

cout << "Input the number:\n";

cin >> BigNumber;

digits = 0;
for(i = 0; i < 100; i++)
{
    if( IsNumeric(BigNumber[i]) )
    {
        digits++;
    }
    else
    {
        break;
    }
}

cout << "That number is " << digits << " digits long";


问:
pseudo selector for uppercase chars/words?
Is there a CSS pseudoselector for uppercase characters/letters/words? I want all my capitals to be a pt smaller and all the other characters the same size. A capital is not neccesarily the first character of a sentence (or word) nor the other way around.

Or maybe there's another way to find these characters in CSS? With a trick? I like tricks.

答:
Well, there's the poor-supported first-letter selector, but that's not what you want.

You could of course also pre-parse your HTML in PHP, wrapping all caps in  tags, but that's a hack.

Then of course you could always pull out the magic jQuery rabbit and alter your DOM at document load to include the spans. That's also a hack. Do you like hacks?

Let's see who else turns up with a magic trick :-)

Body:
Well, there's the poor-supported first-letter selector, but that's not what you want.

You could of course also pre-parse your HTML in PHP, wrapping all caps in <span class="capital"></span> tags, but that's a hack.

Then of course you could always pull out the magic jQuery rabbit and alter your DOM at document load to include the spans. That's also a hack. Do you like hacks?

Let's see who else turns up with a magic trick :-)


问:
How to get base url without accessing a request
How to get the base URL in AspNet core application without having a request?

I know from the Request you can get the scheme and host (ie $"{Request.Scheme}://{Request.Host}" would give something like https://localhost:5000), but is it possible to get this information from anywhere else?

In other words, if I have a service class that needs to build absolute URLs, how can I get the current URL when there is not an http request available?

UPDATE: Maybe that scenario does not even make sense since the hosting URL is totally external to the application and that's why it only makes sense to extract it from the Request host..

答:
i needed for some reason to get the base URL in Start.cs Configure, so i come up with this

var URLS = app.ServerFeatures.Get<IServerAddressesFeature>().Addresses;

ContentLicense: CC BY-SA 4.0


问:
How to set up MySQLi connection on Godaddy hosting?
Has anyone had success with MySQLi in Godaddy?
If so, are any additional steps required so that it will work?

MySQL, on the otherhand, seems to work with no problems.

```<code> define('DBHOST', 'localhost');
 define('DBUSER', 'username');
 define('DBPASS', 'pass');
 define('DBNAME', 'databasename');
 $conn = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
</code>```

答:
SOLUTION

The default php version did not include mysqli

You have to go into settings and upgrade the php to the lastest version. This version will include mysqli and allow you to use it.

Body:
Has anyone had success with MySQLi in Godaddy?
If so, are any additional steps required so that it will work?

MySQL, on the otherhand, seems to work with no problems.

 define('DBHOST', 'localhost');
 define('DBUSER', 'username');
 define('DBPASS', 'pass');
 define('DBNAME', 'databasename');
 $conn = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);