问:
Need help to understand surfarray.array2d - it seems to not save color correctly
I did a test where I converted a Surface into an array2d, and then convert it right back, like so:

```<code>fg = pygame.surfarray.make_surface(pygame.surfarray.array2d(fg))
</code>```

This is the full code (for you to copy and paste into Pygame to do a quick test if you wish):

```<code>pygame.init()

SURFACE_MAIN = pygame.display.set_mode((300, 300))
fg = pygame.Surface((300, 300))
fg.fill((70, 53, 52))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_s:
                fg = pygame.surfarray.make_surface(pygame.surfarray.array2d(fg))

    SURFACE_MAIN.blit(pygame.Surface.copy(fg), (0, 0))
    pygame.display.update()
</code>```

When you press s key, the original brown becomes green.

Old color: (70, 53, 52, 255)

New color: (85, 182, 0, 255)

The solution to this turns out to be using array3d instead, but I don't understand why this is. Could someone explain it to me? Much appreciated!

Reference: https://www.pygame.org/docs/ref/surfarray.html#pygame.surfarray.array2d

答:
The function pygame.surfarray.make_surface will convert a 2D-array to a surface with bit depth of 8 and a 3D-array to a surface with bit depth of 32. This matters because of how pygame handles bit depth.

Bit depth

The bit depth is the amount of information there is to represent a color. A bit depth of 32 allow us to represent 2^32 = 4,294,967,296 colors, which is the same as assigning each color component (Red, Green, Blue, Alpha) 8-bits each (a value between 0-255).

A bit depth of 8 allow us to represent 2^8 = 256 colors. That would be 2 bits for each color component (a value between 0-3). This is however not how pygame handles colors of this bit depth.

How pygame handles it

Pygame does not store each value for RGBA, but instead store the pixel as a single integer which can be decoded to get the values for the color components, as long as the bit depth is more than 8. When you have a lower bit depth pygame uses a color palette for the surface. Each pixel value now becomes an index to a color palette with 256 colors, instead of an encoded integer. This palette is available through the method surface.get_palette() and can be set using surface.set_palette().

It's this conversion that makes your color values weird. Here's a short program to demonstrate and to experiment with (use the console, start with a bit depth of 32 and your color by typing the values separated with comma and/or space):

```<code>import pygame
pygame.init()

screen = pygame.display.set_mode((1, 1))

depth = int(input('\nDepth size: '))
color = [int(x) for x in input('Color: ').replace(',', ' ').split()]

surface = pygame.Surface((1, 1), depth=depth)  # Valid bit depth sizes are 8, 12, 16, 24 or 32
surface.fill(color)
print('\nSurface 1 has bit depth', surface.get_bitsize(), ' | The color is: ', surface.get_at((0, 0)))

surface2 = pygame.surfarray.make_surface(pygame.surfarray.array2d(surface))
print('\nSurface 2 has bit depth', surface2.get_bitsize(), ' | The color is: ', surface2.get_at((0, 0)))
surface2.set_palette([(123, 123, 123) for _ in range(256)])  # Set whole color palette to one color
print('Surface 2 now has the color: ', surface2.get_at((0, 0)))

surface3 = pygame.surfarray.make_surface(pygame.surfarray.array3d(surface))
print('\nSurface 3 has bit depth', surface3.get_bitsize(), ' | The color is: ', surface3.get_at((0, 0)))
print('Surface 3 has no color palette since it has a bit depth greater than 8')
</code>```

Body:
I did a test where I converted a Surface into an array2d, and then convert it right back, like so:

fg = pygame.surfarray.make_surface(pygame.surfarray.array2d(fg))

This is the full code (for you to copy and paste into Pygame to do a quick test if you wish):

pygame.init()

SURFACE_MAIN = pygame.display.set_mode((300, 300))
fg = pygame.Surface((300, 300))
fg.fill((70, 53, 52))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_s:
                fg = pygame.surfarray.make_surface(pygame.surfarray.array2d(fg))

    SURFACE_MAIN.blit(pygame.Surface.copy(fg), (0, 0))
    pygame.display.update()

When you press s key, the original brown becomes green.

Old color: (70, 53, 52, 255)

New color: (85, 182, 0, 255)

The solution to this turns out to be using array3d instead, but I don't understand why this is. Could someone explain it to me? Much appreciated!

Reference: https://www.pygame.org/docs/ref/surfarray.html#pygame.surfarray.array2d

Body:
The function pygame.surfarray.make_surface will convert a 2D-array to a surface with bit depth of 8 and a 3D-array to a surface with bit depth of 32. This matters because of how pygame handles bit depth.

Bit depth

The bit depth is the amount of information there is to represent a color. A bit depth of 32 allow us to represent 2^32 = 4,294,967,296 colors, which is the same as assigning each color component (Red, Green, Blue, Alpha) 8-bits each (a value between 0-255).

A bit depth of 8 allow us to represent 2^8 = 256 colors. That would be 2 bits for each color component (a value between 0-3). This is however not how pygame handles colors of this bit depth.

How pygame handles it

Pygame does not store each value for RGBA, but instead store the pixel as a single integer which can be decoded to get the values for the color components, as long as the bit depth is more than 8. When you have a lower bit depth pygame uses a color palette for the surface. Each pixel value now becomes an index to a color palette with 256 colors, instead of an encoded integer. This palette is available through the method surface.get_palette() and can be set using surface.set_palette().

It's this conversion that makes your color values weird. Here's a short program to demonstrate and to experiment with (use the console, start with a bit depth of 32 and your color by typing the values separated with comma and/or space):

import pygame
pygame.init()

screen = pygame.display.set_mode((1, 1))

depth = int(input('\nDepth size: '))
color = [int(x) for x in input('Color: ').replace(',', ' ').split()]

surface = pygame.Surface((1, 1), depth=depth)  # Valid bit depth sizes are 8, 12, 16, 24 or 32
surface.fill(color)
print('\nSurface 1 has bit depth', surface.get_bitsize(), ' | The color is: ', surface.get_at((0, 0)))

surface2 = pygame.surfarray.make_surface(pygame.surfarray.array2d(surface))
print('\nSurface 2 has bit depth', surface2.get_bitsize(), ' | The color is: ', surface2.get_at((0, 0)))
surface2.set_palette([(123, 123, 123) for _ in range(256)])  # Set whole color palette to one color
print('Surface 2 now has the color: ', surface2.get_at((0, 0)))

surface3 = pygame.surfarray.make_surface(pygame.surfarray.array3d(surface))
print('\nSurface 3 has bit depth', surface3.get_bitsize(), ' | The color is: ', surface3.get_at((0, 0)))
print('Surface 3 has no color palette since it has a bit depth greater than 8')


来源: stackexchange

问:
injecting properties in camel route from wildfly modules
I am using SwithcYard 2.0.0.Beta1. Application server is WildFly 8.1. I want to load properties from modules.
As example I have a module /wildfly/modules/system/layers/base/org/study/configuration/test
my module.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3" name="org.study.configuration" slot="test">
    <resources>
        <resource-root path="."/>
    </resources>
</module>
</code>```

This is properties file:

```<code>user=foo
password=bar
provider=CryptoProvider
directory=domain;login:pwd@host/dir?password=pwd&preMove=backup&move=processed&moveFailed=error&charset=UTF-8
</code>```

This is how I include that module in wildfly profile:

```<code>    <subsystem xmlns="urn:jboss:domain:ee:2.0">
        <global-modules>
            <module name="org.study.configuration" slot="test"/>
        </global-modules>
</code>```

And now I want to load that properties in my camel route:

```<code>.to("smb://{{directory}}")
</code>```

or
in bean

```<code>KeyStore ks = KeyStore.getInstance("PKCS12", {{provider}});
</code>```

Is it possible? how to do this?

答:
It is possible, but as long as your properties are in the file you have to load it first.

What you define in the module - it is just a class path for your application.

If you use Java DSL:

```<code>Properties myProps = new Properties();

Stream is = this.getClass().getClassLoader().getResourceAsStream("MyAppProp.properties");
myProps.load(is);
System.getProperties().putAll(myProps);
</code>```

If you use Spring DSL just define regular Spring properties.

a. with Spring bean namespace

```<code><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>MyAppProp.properties</value>
    </property>
</bean>
</code>```

b. with Spring context namespace

```<code><context:property-placeholder location="MyAppProp.properties"/>
</code>```

Then you can use them inside Camel route as you said:

```<code>.to("smb://{{directory}}")
</code>```

PS. you have an ability to define properties directly in the module.xml as well

```<code><module xmlns="urn:jboss:module:1.3" name="org.study.configuration" slot="test">
  <properties>
    <property name="directory" value="myTestDirectory"/>
  </properties>
  ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using SwithcYard 2.0.0.Beta1. Application server is WildFly 8.1. I want to load properties from modules.
As example I have a module /wildfly/modules/system/layers/base/org/study/configuration/test
my module.xml

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3" name="org.study.configuration" slot="test">
    <resources>
        <resource-root path="."/>
    </resources>
</module>

This is properties file:

user=foo
password=bar
provider=CryptoProvider
directory=domain;login:pwd@host/dir?password=pwd&preMove=backup&move=processed&moveFailed=error&charset=UTF-8

This is how I include that module in wildfly profile:

    <subsystem xmlns="urn:jboss:domain:ee:2.0">
        <global-modules>
            <module name="org.study.configuration" slot="test"/>
        </global-modules>

And now I want to load that properties in my camel route:

.to("smb://{{directory}}")

or
in bean

KeyStore ks = KeyStore.getInstance("PKCS12", {{provider}});

Is it possible? how to do this?

Body:
It is possible, but as long as your properties are in the file you have to load it first.

What you define in the module - it is just a class path for your application.

If you use Java DSL:

Properties myProps = new Properties();

Stream is = this.getClass().getClassLoader().getResourceAsStream("MyAppProp.properties");
myProps.load(is);
System.getProperties().putAll(myProps);

If you use Spring DSL just define regular Spring properties.

a. with Spring bean namespace

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>MyAppProp.properties</value>
    </property>
</bean>

b. with Spring context namespace

<context:property-placeholder location="MyAppProp.properties"/>

Then you can use them inside Camel route as you said:

.to("smb://{{directory}}")

PS. you have an ability to define properties directly in the module.xml as well

<module xmlns="urn:jboss:module:1.3" name="org.study.configuration" slot="test">
  <properties>
    <property name="directory" value="myTestDirectory"/>
  </properties>
  ...


问:
Binding an enum to a WinForms combo box, and then setting it
a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:

```<code>comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
</code>```

But that is pretty useless without being able to set the actual value to display.

I have tried:

```<code>comboBox1.SelectedItem = MyEnum.Something; // Does not work. SelectedItem remains null
</code>```

I have also tried:

```<code>comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something); // ArgumentOutOfRangeException, SelectedIndex remains -1
</code>```

Does anyone have any ideas how to do this?

答:
Let's say you have the following enum

```<code>public enum Numbers {Zero = 0, One, Two};
</code>```

You need to have a struct to map those values to a string:

```<code>public struct EntityName
{
    public Numbers _num;
    public string _caption;

    public EntityName(Numbers type, string caption)
    {
        _num = type;
        _caption = caption;
    }

    public Numbers GetNumber()
    {
        return _num;
    }

    public override string ToString()
    {
        return _caption;
    }
}
</code>```

Now return an array of objects with all the enums mapped to a string:

```<code>public object[] GetNumberNameRange()
{
    return new object[]
    {
        new EntityName(Number.Zero, "Zero is chosen"),
        new EntityName(Number.One, "One is chosen"),
        new EntityName(Number.Two, "Two is chosen")
    };
}
</code>```

And use the following to populate your combo box:

```<code>ComboBox numberCB = new ComboBox();
numberCB.Items.AddRange(GetNumberNameRange());
</code>```

Create a function to retrieve the enum type just in case you want to pass it to a function

```<code>public Numbers GetConversionType()
{
    EntityName type = (EntityName)numberComboBox.SelectedItem;
    return type.GetNumber();
}
</code>```

and then you should be ok :)

OwnerDisplayName: Tony Miletto

ContentLicense: CC BY-SA 2.5

Body:
a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

But that is pretty useless without being able to set the actual value to display.

I have tried:

comboBox1.SelectedItem = MyEnum.Something; // Does not work. SelectedItem remains null

I have also tried:

comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something); // ArgumentOutOfRangeException, SelectedIndex remains -1

Does anyone have any ideas how to do this?

Body:
Let's say you have the following enum

public enum Numbers {Zero = 0, One, Two};

You need to have a struct to map those values to a string:

public struct EntityName
{
    public Numbers _num;
    public string _caption;

    public EntityName(Numbers type, string caption)
    {
        _num = type;
        _caption = caption;
    }

    public Numbers GetNumber()
    {
        return _num;
    }

    public override string ToString()
    {
        return _caption;
    }
}

Now return an array of objects with all the enums mapped to a string:

public object[] GetNumberNameRange()
{
    return new object[]
    {
        new EntityName(Number.Zero, "Zero is chosen"),
        new EntityName(Number.One, "One is chosen"),
        new EntityName(Number.Two, "Two is chosen")
    };
}

And use the following to populate your combo box:

ComboBox numberCB = new ComboBox();
numberCB.Items.AddRange(GetNumberNameRange());

Create a function to retrieve the enum type just in case you want to pass it to a function

public Numbers GetConversionType()
{
    EntityName type = (EntityName)numberComboBox.SelectedItem;
    return type.GetNumber();
}

and then you should be ok :)


问:
Circular iterator / generator for list of custom class items
Say I have a custom class:

```<code>public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}
</code>```

I also have a list of my custom class objects:

```<code>CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};
</code>```

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

答:
Try this.

```<code>static <T> Iterator<T> circularIterator(List<T> list, int count) {
    int size = list.size();
    return new Iterator<T>() {

        int i = 0;

        @Override
        public boolean hasNext() {
            return i < count;
        }

        @Override
        public T next() {
            return list.get(i++ % size);
        }
    };
}
</code>```

And

```<code>List<String> list = Arrays.asList("a", "b", "c");
for (Iterator<String> i = circularIterator(list, 5); i.hasNext();) {
    String s = i.next();
    System.out.println(s);
}
</code>```

result:

```<code>a
b
c
a
b
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Say I have a custom class:

public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}

I also have a list of my custom class objects:

CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Body:
Try this.

static <T> Iterator<T> circularIterator(List<T> list, int count) {
    int size = list.size();
    return new Iterator<T>() {

        int i = 0;

        @Override
        public boolean hasNext() {
            return i < count;
        }

        @Override
        public T next() {
            return list.get(i++ % size);
        }
    };
}

And

List<String> list = Arrays.asList("a", "b", "c");
for (Iterator<String> i = circularIterator(list, 5); i.hasNext();) {
    String s = i.next();
    System.out.println(s);
}

result:

a
b
c
a
b


问:
Cannot debug Swift module/framework embedded in Objective-C app

Alternative titles (to aid searching)

Cannot debug Swift 2.3 framework linked to an Objective-C app in Xcode 8

error in auto-import: failed to get module 'XYZ' from AST context Xcode 8

Xcode 8 cannot debug Swift framework

warning: Swift error in module <XYZ>

Workaround for; Xcode Debugger cannot debug apps written in Objective-C only but that link against frameworks written in Swift only. (28312362)

I have an app written in Objective-C that links against some modules (frameworks) written in Swift 2.x.

Question

Everything (debugging etc.) works fine in xcode7, however when moving to xcode8 and updating the modules to use swift2.3 I was unable to debug the modules.

LLDB reported these errors:

```<code>warning: Swift error in module XYZ.
Debug info from this module will be unavailable in the debugger.

error: in auto-import:
failed to get module 'ABC' from AST context
</code>```

This does not happen if I link the modules to an app built in Swift 2.3.

答:
I discussed this issue with an Apple engineer named Sean at WWDC 2017.

My team spent weeks trying to figure this out, and it ended up being a bug on Apple's compiler, which we could never have figured out by ourselves. Also, it has a VERY easy workaround.

There happens to be a bug with the way the compiling flags get aggregated from the frameworks and the project, and the "pure Objective-C" project "activates" it.

Solution: add one single, empty Swift file ("Whatever.swift", or whatever) in your Objective-C project, making it not-pure-objective-c anymore  (new->file->Swift file, don't create the bridging header. The file will only contain the import of Foundation).

And that's it. Problem solved.

Body:
Alternative titles (to aid searching)

Cannot debug Swift 2.3 framework linked to an Objective-C app in Xcode 8

error in auto-import: failed to get module 'XYZ' from AST context Xcode 8

Xcode 8 cannot debug Swift framework

warning: Swift error in module <XYZ>

Workaround for; Xcode Debugger cannot debug apps written in Objective-C only but that link against frameworks written in Swift only. (28312362)

I have an app written in Objective-C that links against some modules (frameworks) written in Swift 2.x.

Question

Everything (debugging etc.) works fine in xcode7, however when moving to xcode8 and updating the modules to use swift2.3 I was unable to debug the modules.

LLDB reported these errors:

warning: Swift error in module XYZ.
Debug info from this module will be unavailable in the debugger.

error: in auto-import:
failed to get module 'ABC' from AST context

This does not happen if I link the modules to an app built in Swift 2.3.


问:
How to check if pair of values in array of pairs of values in PHP
Suppose we have an object whose has the dimensions $height and $width. Rather than do this:

```<code>if(
   ($height = 500 && $width = 400)
|| ($height = 200 && $width = 380)
|| ($height = 850 && $width = 780)
|| ...
) { ...
</code>```

...is there a "shorthand" (i.e. easy for humans to read and maintain) way in PHP to check if the array [$height, $width] is in the following array of arrays?

```<code>[ [500,400], [200,380] [850, 780] ]
</code>```

答:
you can do something like this </p>

```<code> $widths=[500,200,850];
 $heights=[400,380,780];
 if(in_array($width,$widths) && in_array($height,$heights)){
 ...
 }
</code>```

Body:
Suppose we have an object whose has the dimensions $height and $width. Rather than do this:

if(
   ($height = 500 && $width = 400)
|| ($height = 200 && $width = 380)
|| ($height = 850 && $width = 780)
|| ...
) { ...

...is there a "shorthand" (i.e. easy for humans to read and maintain) way in PHP to check if the array [$height, $width] is in the following array of arrays?

[ [500,400], [200,380] [850, 780] ]

Body:
you can do something like this

 $widths=[500,200,850];
 $heights=[400,380,780];
 if(in_array($width,$widths) && in_array($height,$heights)){
 ...
 }


问:
How to get a specific value in Mongodb using Java?
In command prompt I enter the following:

```<code>db.products.insert( { item: "card", qty: 15 } )
</code>```

I wanted to know how would I be able to get the item value from java.
I want to create a variable called item and it would know the value of it which is "card".

I am currently using MongoOperations in java but I do not know how to get only one value from MongoDB.

Pojo

```<code>@Document(collection="products")
public class ValueServerModel{

    @Id
    private String id;

    String item;

    int qty;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Product(String item, int qty) {
        //super();
        this.item = item;
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
    }

}

//provided by suwal
</code>```

Long Shot Attempt

```<code>@Autowired
MongoOperations mongoOperations;

@PostConstruct
public List<SomeModel> getList() {
List<SomeModel> pmLst = mongoOperations.findAll(ServerModel.class);
//code above works I get a list of values based on mongo db

//attempting to retrieve one value, (stuck)
String value = mongoOperations.find("test", ValueServerModel.class);
</code>```

With command prompt

I am able to get a value by using the following command:

```<code>db.products.find({}, {qty:0, _id:0})
//output ("item": "card")
</code>```

I want to achieve the following:

```<code>db.products.find({}, {item})
//output should be "card".
</code>```

is it possible to do what I just did above?

答:
I get that you want to get the value, but you are not specifying based on what. That is "what is your query condition". Also not sure what ServerModel and ValueServerModel classes are, but let see if this general idea helps you.

Lets say you have following structure stored after your insert query in the collection products

```<code>{
    "_id" : ObjectId("5939d5a1d0ffa3f0209fd42f"),
    "item" : "card",
    "qty" : 15
}
</code>```

You will need a model representing the collection,

```<code>import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="products") //this is what binds this class to your collection
public class Product {

    @Id
    private String id;

    String item;

    int qty;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Product(String item, int qty) {
        //super();
        this.item = item;
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
    }

}
</code>```

Now in your code you would have something like this,

```<code>// findOne returns you single instance of an object of the specified type
    Product product = mongoOperation.findOne(
            new Query(Criteria.where("item").is("card")), Product.class);

    System.out.println(product); //Output => Product [id=5939d5a1d0ffa3f0209fd42f, item=card, qty=15]

    String value = product.getItem();

    System.out.println("value is " + value);//Output => card
</code>```

Lets say you want to get by id instead, so you would have something like this

```<code>Product product2 = mongoOperation.findOne(
            new Query(Criteria.where("_id").is("5939d5a1d0ffa3f0209fd42f")),
Product.class);

    System.out.println(product2);
</code>```

Body:
In command prompt I enter the following:

db.products.insert( { item: "card", qty: 15 } )

I wanted to know how would I be able to get the item value from java.
I want to create a variable called item and it would know the value of it which is "card".

I am currently using MongoOperations in java but I do not know how to get only one value from MongoDB.

Pojo

@Document(collection="products")
public class ValueServerModel{

    @Id
    private String id;

    String item;

    int qty;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Product(String item, int qty) {
        //super();
        this.item = item;
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
    }

}

//provided by suwal

Long Shot Attempt

@Autowired
MongoOperations mongoOperations;

@PostConstruct
public List<SomeModel> getList() {
List<SomeModel> pmLst = mongoOperations.findAll(ServerModel.class);
//code above works I get a list of values based on mongo db

//attempting to retrieve one value, (stuck)
String value = mongoOperations.find("test", ValueServerModel.class);

With command prompt

I am able to get a value by using the following command:

db.products.find({}, {qty:0, _id:0})
//output ("item": "card")

I want to achieve the following:

db.products.find({}, {item})
//output should be "card".

is it possible to do what I just did above?

Body:
I get that you want to get the value, but you are not specifying based on what. That is "what is your query condition". Also not sure what ServerModel and ValueServerModel classes are, but let see if this general idea helps you.

Lets say you have following structure stored after your insert query in the collection products

{
    "_id" : ObjectId("5939d5a1d0ffa3f0209fd42f"),
    "item" : "card",
    "qty" : 15
}

You will need a model representing the collection,

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="products") //this is what binds this class to your collection
public class Product {

    @Id
    private String id;

    String item;

    int qty;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Product(String item, int qty) {
        //super();
        this.item = item;
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
    }

}

Now in your code you would have something like this,

// findOne returns you single instance of an object of the specified type
    Product product = mongoOperation.findOne(
            new Query(Criteria.where("item").is("card")), Product.class);

    System.out.println(product); //Output => Product [id=5939d5a1d0ffa3f0209fd42f, item=card, qty=15]

    String value = product.getItem();

    System.out.println("value is " + value);//Output => card

Lets say you want to get by id instead, so you would have something like this

Product product2 = mongoOperation.findOne(
            new Query(Criteria.where("_id").is("5939d5a1d0ffa3f0209fd42f")),
Product.class);

    System.out.println(product2);


问:
Graphing Algorithm To Match Nodes
Given a directed graph, what is an algorithm I can use to find a random subset of its edges so that every node has exactly one incoming and exactly one outgoing edge?

For example, this could be the graph I am given:

And this would be a valid output graph:

This is valid because:

It contains all the nodes on the input graph

All its edges are also on the input graph

Every node has exactly one edge leaving it and one edge coming to it (and that can't be the same edge, no loops are allowed, every node has to connect to at least one other node).

If there is no possible solution that should be detected.

Is there an efficient algorithm to solve this?

Thanks!

答:
You're trying to decompose a graph into a set of cycles.

This link points you to Tarjan's algorithm for finding cycles in a graph.

After that, you'll need some search strategy (some choices of cycles may not lead to a solution given your constraints).

Title: Graphing Algorithm To Match Nodes


问:
Where do I put  in an angular-fullstack-generator project?
This should be straight forward, but I'm stuck.

I'm trying to include mobile-angular-ui in an angular-fullstack-generator project but I keep getting

```<code>Uncaught SyntaxError: Unexpected token <  mobile-angular-ui.min.js:1
</code>```

I'm adding the following at the end of the body of the _index.html, and the network tab is returning the proper 200 response.

```<code><script src="/node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.min.js"></script>
</code>```

If I use import in app.js like this

```<code>import mobileUi from '../../node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.js';
</code>```

Then I get the following error

```<code>Uncaught TypeError: Cannot read property 'documentElement' of undefined   mobile-angular-ui.js:2584
</code>```

Where am I going wrong, where am I supposed to include this?

Thanks!

答:
In angular-fullstack, all front end libraries are handled/installed through bower and all back end libraries are handled through npm.

So if you want to use mobile-angular-ui, which is a front end library, you should try installing it like this.

```<code>bower install --save mobile-angular-ui angular angular-route
</code>```

Then add the module dependency

mobile-angular-ui

in app.js of client side Then serve the project again. Now your dependency will be added automatically in your index.html file and you won't need to automatically include it in your index.html

Title: Where do I put <script src=...></script> in an angular-fullstack-generator project?

Body:
This should be straight forward, but I'm stuck.

I'm trying to include mobile-angular-ui in an angular-fullstack-generator project but I keep getting

Uncaught SyntaxError: Unexpected token <  mobile-angular-ui.min.js:1

I'm adding the following at the end of the body of the _index.html, and the network tab is returning the proper 200 response.

If I use import in app.js like this

import mobileUi from '../../node_modules/mobile-angular-ui/dist/js/mobile-angular-ui.js';

Then I get the following error

Uncaught TypeError: Cannot read property 'documentElement' of undefined   mobile-angular-ui.js:2584

Where am I going wrong, where am I supposed to include this?

Thanks!

Body:
In angular-fullstack, all front end libraries are handled/installed through bower and all back end libraries are handled through npm.

So if you want to use mobile-angular-ui, which is a front end library, you should try installing it like this.

bower install --save mobile-angular-ui angular angular-route

Then add the module dependency

mobile-angular-ui

in app.js of client side Then serve the project again. Now your dependency will be added automatically in your index.html file and you won't need to automatically include it in your index.html


问:
Mininet openflow tutorial
I am new to mininet and trying to follow the tutorial on mininet/openflow https://github.com/mininet/openflow-tutorial/wiki/Learn-Development-Tools

I have a problem with the Wireshark capture, it's only capturing TCP packets on the lo interface, no OpenFlow packets at all.

any idea what might be wrong?

Cheers,
ami

答:
I think you use openflow on port 6634 but as you can see here in wireshark documentation it expects to see OpenFlow packets on port 6633 or 6653.

I prefer to use third party controller but if you want to use mininet default controller, you can set its port with:

```<code>sudo controller ptcp:6653
</code>```

Title: Mininet openflow tutorial

Body:
I think you use openflow on port 6634 but as you can see here in wireshark documentation it expects to see OpenFlow packets on port 6633 or 6653.

I prefer to use third party controller but if you want to use mininet default controller, you can set its port with:

sudo controller ptcp:6653


答:
in_array can work with arrays:

```<code><?php
$dimensions = [[500, 400], [200, 380], [850, 780]];

$needle1 = [500, 400];
$needle2 = [500, 440];

echo "needle1 in array: ".in_array($needle1, $dimensions)."\n";
echo "needle2 in array: ".in_array($needle2, $dimensions)."\n";
</code>```

(Demo)

Title: How to check if pair of values in array of pairs of values in PHP

Body:
in_array can work with arrays:

<?php
$dimensions = [[500, 400], [200, 380], [850, 780]];

$needle1 = [500, 400];
$needle2 = [500, 440];

echo "needle1 in array: ".in_array($needle1, $dimensions)."\n";
echo "needle2 in array: ".in_array($needle2, $dimensions)."\n";

(Demo)


问:
Best practices for memory performance
I have the below code. We had an argument regarding which approach is better for memory performance. Will it make any difference at all if we don't use a separate variable and use it? It it will affect then is this the possible solution ?

```<code>    /// <summary>
    /// Treatment Point Types
    /// </summary>
    public string DWTreatment
    {
        get
        {
            StringBuilder sbStatus = new StringBuilder();
            .........

        }

        set
        {
            chkTreatSR.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.SR).ToString());
            chkTreatIT.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.IT).ToString());
            chkTreatEP.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.EP).ToString());
            chkTreatWW.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.WW).ToString());
            chkTreatQC.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.QC).ToString());

            isSelectionSetByPage = true;
        }
    }
</code>```

OR

```<code>    /// <summary>
    /// Treatment Point Types
    /// </summary>
    public string DWTreatment
    {
        get
        {
            StringBuilder sbStatus = new StringBuilder();
            .........

        }

        set
        {
            var values = value.Split(',');
            chkTreatSR.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.SR).ToString());
            chkTreatIT.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.IT).ToString());
            chkTreatEP.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.EP).ToString());
            chkTreatWW.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.WW).ToString());
            chkTreatQC.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.QC).ToString());

            isSelectionSetByPage = true;
        }
    }
</code>```

Thanks.

答:
The second example will have less memory allocation as each call to string.Split(,) will allocate a new string array.

If this is a "hot-spot" in your code, you might consider not calling string.Split at all, and instead use Regex to search for your enums.

Title: Best practices for memory performance

Body:
I have the below code. We had an argument regarding which approach is better for memory performance. Will it make any difference at all if we don't use a separate variable and use it? It it will affect then is this the possible solution ?

    ///
    /// Treatment Point Types
    ///
    public string DWTreatment
    {
        get
        {
            StringBuilder sbStatus = new StringBuilder();
            .........

        }

        set
        {
            chkTreatSR.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.SR).ToString());
            chkTreatIT.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.IT).ToString());
            chkTreatEP.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.EP).ToString());
            chkTreatWW.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.WW).ToString());
            chkTreatQC.Checked = value.Split(',').Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.QC).ToString());

            isSelectionSetByPage = true;
        }
    }

OR

    ///
    /// Treatment Point Types
    ///
    public string DWTreatment
    {
        get
        {
            StringBuilder sbStatus = new StringBuilder();
            .........

        }

        set
        {
            var values = value.Split(',');
            chkTreatSR.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.SR).ToString());
            chkTreatIT.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.IT).ToString());
            chkTreatEP.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.EP).ToString());
            chkTreatWW.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.WW).ToString());
            chkTreatQC.Checked = values.Contains(((int)AgencyListReportTemplate.SamplingPointTypesEnum.QC).ToString());

            isSelectionSetByPage = true;
        }
    }

Thanks.


问:
How to define custom CSS within the document?
According to the RStudio documentation of RPres, there's a way to add some custom CSS styles within the .Rpres document:

[I]f you prefer to include styles right within the presentation source file you can also place them at the top of the source above the title slide (any style tags included there will automatically be appended to the head element).

Am I misunderstanding something? The following should work according to that:

```<code>.reveal section del {
  color: red;
}

test
========================================================

test
========================================================

~~should be red~~
</code>```

But this produces:

Clearly, it's not being parsed as CSS. Am I missing something?

If I simply save that section separately into a like-named .css file (as mentioned is possible in the same document), it works as expected. I just don't see the point in creating a separate file do define one single custom style.

答:
The style needs to be wrapped in

```<code><style>
.reveal section del{
  color: red;
}
</style>

csstest
========================================================
author:
date:
autosize: true

test
========================================================

~~should be red~~
</code>```

I found this presentation to be a useful resource

Body:
According to the RStudio documentation of RPres, there's a way to add some custom CSS styles within the .Rpres document:

[I]f you prefer to include styles right within the presentation source file you can also place them at the top of the source above the title slide (any style tags included there will automatically be appended to the head element).

Am I misunderstanding something? The following should work according to that:

.reveal section del {
  color: red;
}

test
========================================================

test
========================================================

~~should be red~~

But this produces:

Clearly, it's not being parsed as CSS. Am I missing something?

If I simply save that section separately into a like-named .css file (as mentioned is possible in the same document), it works as expected. I just don't see the point in creating a separate file do define one single custom style.

Body:
The style needs to be wrapped in <style></style>

<style>
.reveal section del{
  color: red;
}
</style>

csstest
========================================================
author:
date:
autosize: true

test
========================================================

~~should be red~~

I found this presentation to be a useful resource


问:
How to tell if you're currently in the last row of an HTML table?
I have a keydown event that I'm using to add a blank row to a table.
But I only want the new row to be added if the keydown event happens when the cursor is in last row of the table.

This is my current jQuery event.
.glCreditValue is the class of an input textbox that resides in the last TD of the table row.
So when the user tabs out of that input, IF the TD that the input is inside of is in the last row of the table, I want to add a new row.

Being that the table data is generated dynamically, every row's final TD has an input textbox with the class .glCreditValue.

```<code>$(".glCreditValue").keydown(function(event) {
        var keycode = event.keyCode;
        if (keycode == 9) {
            //HERE i would like to make sure that i'm in the last row of the table
            AddNewRow();
        }
    });
</code>```

I'm trying to make use of the tr:last selector, but I'm not sure quite where to go from here.

答:
One way to do it without having the overhead of running a selector is to simply get the .closest() row, then go to the .next() element and test its .length property.

It will be 0 if you were on the last
.

```<code>if( !$(this).closest('tr').next().length ) {
   // was the last row
}
</code>```

Body:
I have a keydown event that I'm using to add a blank row to a table.
But I only want the new row to be added if the keydown event happens when the cursor is in last row of the table.

This is my current jQuery event.
.glCreditValue is the class of an input textbox that resides in the last TD of the table row.
So when the user tabs out of that input, IF the TD that the input is inside of is in the last row of the table, I want to add a new row.

Being that the table data is generated dynamically, every row's final TD has an input textbox with the class .glCreditValue.

$(".glCreditValue").keydown(function(event) {
        var keycode = event.keyCode;
        if (keycode == 9) {
            //HERE i would like to make sure that i'm in the last row of the table
            AddNewRow();
        }
    });

I'm trying to make use of the tr:last selector, but I'm not sure quite where to go from here.

Body:
One way to do it without having the overhead of running a selector is to simply get the .closest() row, then go to the .next() element and test its .length property.

It will be 0 if you were on the last <tr>.

if( !$(this).closest('tr').next().length ) {
   // was the last row
}


问:
How to remove value from Multidimensional Array based on Key and Value - PHP
How can I remove value "288" from "pecan" and return the updated array.

Array like so:

```<code>a: 10: {
s: 13: "Fraser Island";
a: 7: {
    i: 0;
    i: 303;
    i: 1;
    i: 34;
    i: 2;
    i: 27;
    i: 3;
    i: 291;
    i: 4;
    i: 293;
    i: 5;
    i: 37;
    i: 6;
    i: 288;
}
s: 5: "pecan";
a: 5: {
    i: 0;
    i: 34;
    i: 1;
    i: 27;
    i: 2;
    i: 291;
    i: 3;
    i: 59;
    i: 4;
    i: 288;
}
s: 11: "New Triper";
a: 3: {
    i: 0;
    i: 291;
    i: 1;
    i: 293;
    i: 2;
    i: 288;
}
</code>```

}

Which translates to this in PHP:

```<code>Array (
[0] => Array (
    [Fraser Island] => Array (
        [0] => 303
        [1] => 34
        [2] => 27
        [3] => 291
        [4] => 293
        [5] => 37
        [6] => 288
    )
    [pecan] => Array (
        [0] => 34
        [1] => 27
        [2] => 291
        [3] => 59
        [4] => 288
    )
    [New Triper!] => Array (
        [0] => 291
        [1] => 293
        [2] => 288
    )
)
</code>```

)

Delete/remove a value from a multidimensional array by finding the array column name and the value. I use this code:

```<code>// DELETE VALUE FROM ARRAY
function remove_element_by_value($arr, $val) {
    $return = array();
    foreach($arr as $k => $v) {
        if(is_array($v)) {
            $return[$k] = remove_element_by_value($v, $val); //recursion
            continue;
        }
        if($v == $val) continue;
            $return[$k] = $v;
        }
   return $return;
}
</code>```

However it removes all matching values from all array columns.

答:
Try remove_element_by_value($arr, '288', 'pecan')

```<code>   // DELETE VALUE FROM ARRAY
    function remove_element_by_value($arr, $val, $keyToSearch) {
            $keyOfValue = array_search($val, $arr[0][$keyToSearch]);
            unset($arr[0][$keyToSearch][$keyOfValue]);
            $arr[0][$keyToSearch] = array_values($arr[0][$keyToSearch]); #Reindex
            return $arr;
    }
</code>```

This way, you can delete the elements by giving it the key and value that you want to remove such as remove_element_by_value($arr, '288', 'Fraser Island') // remove 288 from Fraser Island etc

```<code>   // Code for PHPfiddle
function remove_element_by_value($arr, $val, $keyToSearch) {
        $keyOfValue = array_search($val, $arr[0][$keyToSearch]);
        unset($arr[0][$keyToSearch][$keyOfValue]);
        $arr[0][$keyToSearch] = array_values($arr[0][$keyToSearch]);
        return $arr;
}

$array = array(array('abc'=>array(1,2,3,4,5,6)));

print_r(remove_element_by_value($array, 2, 'abc'));
</code>```

Body:
How can I remove value "288" from "pecan" and return the updated array.

Array like so:

a: 10: {
s: 13: "Fraser Island";
a: 7: {
    i: 0;
    i: 303;
    i: 1;
    i: 34;
    i: 2;
    i: 27;
    i: 3;
    i: 291;
    i: 4;
    i: 293;
    i: 5;
    i: 37;
    i: 6;
    i: 288;
}
s: 5: "pecan";
a: 5: {
    i: 0;
    i: 34;
    i: 1;
    i: 27;
    i: 2;
    i: 291;
    i: 3;
    i: 59;
    i: 4;
    i: 288;
}
s: 11: "New Triper";
a: 3: {
    i: 0;
    i: 291;
    i: 1;
    i: 293;
    i: 2;
    i: 288;
}

}

Which translates to this in PHP:

Array (
[0] => Array (
    [Fraser Island] => Array (
        [0] => 303
        [1] => 34
        [2] => 27
        [3] => 291
        [4] => 293
        [5] => 37
        [6] => 288
    )
    [pecan] => Array (
        [0] => 34
        [1] => 27
        [2] => 291
        [3] => 59
        [4] => 288
    )
    [New Triper!] => Array (
        [0] => 291
        [1] => 293
        [2] => 288
    )
)

)

Delete/remove a value from a multidimensional array by finding the array column name and the value. I use this code:

// DELETE VALUE FROM ARRAY
function remove_element_by_value($arr, $val) {
    $return = array();
    foreach($arr as $k => $v) {
        if(is_array($v)) {
            $return[$k] = remove_element_by_value($v, $val); //recursion
            continue;
        }
        if($v == $val) continue;
            $return[$k] = $v;
        }
   return $return;
}

However it removes all matching values from all array columns.

Body:
Try remove_element_by_value($arr, '288', 'pecan')

   // DELETE VALUE FROM ARRAY
    function remove_element_by_value($arr, $val, $keyToSearch) {
            $keyOfValue = array_search($val, $arr[0][$keyToSearch]);
            unset($arr[0][$keyToSearch][$keyOfValue]);
            $arr[0][$keyToSearch] = array_values($arr[0][$keyToSearch]); #Reindex
            return $arr;
    }

This way, you can delete the elements by giving it the key and value that you want to remove such as remove_element_by_value($arr, '288', 'Fraser Island') // remove 288 from Fraser Island etc

   // Code for PHPfiddle
function remove_element_by_value($arr, $val, $keyToSearch) {
        $keyOfValue = array_search($val, $arr[0][$keyToSearch]);
        unset($arr[0][$keyToSearch][$keyOfValue]);
        $arr[0][$keyToSearch] = array_values($arr[0][$keyToSearch]);
        return $arr;
}

$array = array(array('abc'=>array(1,2,3,4,5,6)));

print_r(remove_element_by_value($array, 2, 'abc'));


问:
How can I view our currently active AWS services that we're actually using?
The AWS console just lists every single service that AWS offers.  Is there an easy way to make it just show the services that we're actually currently using?  I don't know why does everything with AWS seem to be far more difficult than it should be.</p>

答:
There is no way to show only the services that you are currently using. If AWS doesn't show all the services, how does AWS expect you to know about the new services. just joking.

Honestly, I started exploring the new services only after seeing them on AWS dashboard. If you consider that as an inconvenience, there is nothing you can do about it. But if you are curious to know about the services you are using, then the billing dashboard will list all the services you are using and the charges for it.  For example, to see the services used in June 2017

Note: You need certain IAM privileges to access the Billing Dashboard


问:
My Font only Showing Bold in Safari
So I'm building a site in Wordpress and my  font on my slideshow looks really bold in Safari (which I like) and looks much thinner in Firefox and Chrome. Can anyone help me out with this? I'm using the google font Raleway (bold).

The link to the page is here:
http://ardxmteam.com/ari/

答:
Put a class (let's say slidertext) on the container or the link of that text and then add this tiny CSS:

```<code>.slidertext{
  font-weight:bold !important;
}
</code>```

Title: My Font only Showing Bold in Safari

Body:
Put a class (let's say slidertext) on the container or the link of that text and then add this tiny CSS:

.slidertext{
  font-weight:bold !important;
}


问:
Simpler Alternative to Reset Password in Powershell (not using AD) for WIndows 10
I am Looking for RESETING ALL PASSWORDS ON ALL LOCAL USERS on a local windows 10 machine (NOT Server). To reset passwords for all accounts on that system NOT USING Active Directory.  I saw many posts that use AD to reset passwords.

I am not interested in that. Is there any alternatives to these? Using Powershell, Batch, That you guys use. Surely there is a simpler alternative for non servers.

I have seen this. But it uses alot of dependencies of LocalGroup module being installed And Exchange.

```<code>$newpwd = Read-Host "Enter the new password" -AsSecureString
Get-LocalUser | ForEach-Object {
    $_ | Set-LocalUser -Password $newpwd
}
</code>```

I have Seen this

```<code># Specify the OU.
$OU = [ADSI]"LDAP://ou=West,dc=MyDomain,dc=com"

# Enumerate all objects in the OU.
$arrChildren = $OU.Get_Children()
ForEach ($User In $arrChildren)
{
    # Only consider user objects.
    If ($User.Class -eq "user")
   {
       # Set password.
       $User.Invoke("SetPassword", "MyPassword")
       # Expire the password.
       $User.pwdLastSet = 0
       $User.SetInfo()
   }
}
</code>```

答:
I agree with Windos to exclude not Enabled accounts, either via Name or Enabled property.</p>

```<code>#Requires -RunAsAdministrator
$SecurePassword = Read-Host -Prompt "Enter password for all users" -AsSecureString
$Exclude="Administrator","Guest","DefaultAccount"
Get-LocalUser|
  Where Enabled -eq 'True'|
  Where {$Exclude -notcontains $_.Name}|
    Set-Localuser -Password $SecurePassword
</code>```

Body:
I am Looking for RESETING ALL PASSWORDS ON ALL LOCAL USERS on a local windows 10 machine (NOT Server). To reset passwords for all accounts on that system NOT USING Active Directory.  I saw many posts that use AD to reset passwords.

I am not interested in that. Is there any alternatives to these? Using Powershell, Batch, That you guys use. Surely there is a simpler alternative for non servers.

I have seen this. But it uses alot of dependencies of LocalGroup module being installed And Exchange.

$newpwd = Read-Host "Enter the new password" -AsSecureString
Get-LocalUser | ForEach-Object {
    $_ | Set-LocalUser -Password $newpwd
}

I have Seen this

# Specify the OU.
$OU = [ADSI]"LDAP://ou=West,dc=MyDomain,dc=com"

# Enumerate all objects in the OU.
$arrChildren = $OU.Get_Children()
ForEach ($User In $arrChildren)
{
    # Only consider user objects.
    If ($User.Class -eq "user")
   {
       # Set password.
       $User.Invoke("SetPassword", "MyPassword")
       # Expire the password.
       $User.pwdLastSet = 0
       $User.SetInfo()
   }
}

Body:
I agree with Windos to exclude not Enabled accounts, either via Name or Enabled property.

#Requires -RunAsAdministrator
$SecurePassword = Read-Host -Prompt "Enter password for all users" -AsSecureString
$Exclude="Administrator","Guest","DefaultAccount"
Get-LocalUser|
  Where Enabled -eq 'True'|
  Where {$Exclude -notcontains $_.Name}|
    Set-Localuser -Password $SecurePassword


问:
Using EventAggregator (or something else - IoC maybe) with MEF
I am currently building an MEF project so I can learn how to use it in practical applications. I have successfully imported a DataHandler module to provide database connections and other centralized database operations.

Now I am thinking about a way to provide methods to other imported modules. For instance, if a Security Module requires a connection to a database, it would be able to request a database connection. Now, I have a way for a module to detect if a DataHandler is available as the Host application makes that public. So I am wondering if there were a way to use EventAggregator to publish a type of event where the subscriber (Security Module) simply fires an event and gets a DbConnection object in return.

If EventAggregator is the answer, I could use some hints as to how. Keep in mind that I am still researching...not just asking for teh codez. If there is a better solution out there, I am interested in options.

I am currently reviewing this post by Denis Vuyka

Edit

EventAggregator looks like it might not be the right tool to use. Is there some sort of loosely coupled messaging that I can implement in my Host app? Is a Service locator or Command pattern something that can be implemented?

答:
I pass my configuration to all modules by Exporting a main app interface. You could have single instance of your db interface hosted in the main app.

The host application exports its self and all the plugins import it and have access to its interface. See my example below:

Interface:

```<code>public interface IMainApp
{
    ConfigClass Config { get; set; }
}
</code>```

Host App:

```<code>[Export(typeof(IMainApp))]
public class Host : IMainApp
{
    public Host()
    { /* Compose parts etc here..? */ }

    public ConfigClass Config { get; set; }

    [Import(typeof(IModule))]
    public List<IModule> LoadedModules { get; set; }
}
</code>```

Plug-in assembly:

```<code>[Export(typeof(IModule))]
public class Module : IModule
{
    public Module() { }

    [Import(typeof(IMainApp))]
    public IMainApp Host { get; set; }

    public void DoSomething()
    {
        Host.Config... // use config here
    }
}
</code>```

Body:
I pass my configuration to all modules by Exporting a main app interface. You could have single instance of your db interface hosted in the main app.

The host application exports its self and all the plugins import it and have access to its interface. See my example below:

Interface:

public interface IMainApp
{
    ConfigClass Config { get; set; }
}

Host App:

[Export(typeof(IMainApp))]
public class Host : IMainApp
{
    public Host()
    { /* Compose parts etc here..? */ }

    public ConfigClass Config { get; set; }

    [Import(typeof(IModule))]
    public List<IModule> LoadedModules { get; set; }
}

Plug-in assembly:

[Export(typeof(IModule))]
public class Module : IModule
{
    public Module() { }

    [Import(typeof(IMainApp))]
    public IMainApp Host { get; set; }

    public void DoSomething()
    {
        Host.Config... // use config here
    }
}


问:
on press button mass stay the color
Hi can some one please help me with this code

```<code>horse_btn_a1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      horse_btn_a1.setBackgroundColor(Color.parseColor("@drawable/ront2"));
    }
});
</code>```

and what I wanna do is when the button is pressed it must stay that color.

答:
You can have different drawables based on different states (pressed/disabled/focused) for the same view. Take a look at </p>

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_sel" android:state_selected="true" />
    <item android:drawable="@drawable/button_sel" android:state_pressed="true" />
    <item android:drawable="@drawable/button_unsel" />
</selector>
</code>```

Title: on press button mass stay the color

Body:
Hi can some one please help me with this code

horse_btn_a1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      horse_btn_a1.setBackgroundColor(Color.parseColor("@drawable/ront2"));
    }
});

and what I wanna do is when the button is pressed it must stay that color.

Body:
You can have different drawables based on different states (pressed/disabled/focused) for the same view. Take a look at

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_sel" android:state_selected="true" />
    <item android:drawable="@drawable/button_sel" android:state_pressed="true" />
    <item android:drawable="@drawable/button_unsel" />
</selector>


问:
How to get a value from the last inserted row using Codeigniter
Is there any codeigniter function to do this?</p>

答:
This will help you to get last inserted row from the table.</p>

```<code>$last = $this->db->order_by('id',"desc")->limit(1)->get('tablename')->row();
    print_r($last);
</code>```

Body:
This will help you to get last inserted row from the table.

$last = $this->db->order_by('id',"desc")->limit(1)->get('tablename')->row();
    print_r($last);


问:
Can I make a ngIf using type check (the is keyword) in AngularDart?
I have a List with 3 items: [Class1 a, Class2 b, Class3 c].

How can I make a switch or ngIf within the template to generate some html based on the type?

```<code><div *ngFor="let item of items">
    <div *ngIf="item is CoolClass”>somehtml</div>
    <div *ngIf=item is SomeOtherClass”>some other html</div>
</div>
</code>```

this doesn’t work, it says ngIfIs can not be binded

答:
Template expressions don't support is-checks.

Had to make helper functions in my component like isCoolClass and isSomeOtherClass.

Body:
I have a List with 3 items: [Class1 a, Class2 b, Class3 c].

How can I make a switch or ngIf within the template to generate some html based on the type?

somehtml

some other html

this doesn’t work, it says ngIfIs can not be binded


问:
How to define or have Typescript ignore relative ambient modules?
I'm attempting to load a json file with a custom json loader module. I have babel configured to use my loader specifically for src/routes.json, though really it could be for any json file. I've done my best to look at the docs and the multiples issues reported with similar problems of loading vendor library modules but none of the solutions I've found (which are various ways of defining the module) are working for me.

What I'm attempting to do is implement the declarative router found here: https://github.com/kriasoft/react-static-boilerplate/blob/master/docs/routing-and-navigation.md

My question is how can I have typescript understand my relative src/routes.json?

答:
You could write something like

```<code>declare module "*.json";
</code>```

in a global .ts or .d.ts file. That tells TypeScript "anything that ends in .json exists, and I shouldn't get any errors for using it."

To clarify, when I say "a global file", I mean any file that has no imports or exports.

Body:
You could write something like

declare module "*.json";

in a global .ts or .d.ts file. That tells TypeScript "anything that ends in .json exists, and I shouldn't get any errors for using it."

To clarify, when I say "a global file", I mean any file that has no imports or exports.


问:
Node can't find module but it exists in node_modules?
I've been playing with node for the past day and I've run into an issue I would really appreciate help on.

I created a new project and am trying to use a module I installed using npm, the module exists in the node_modules directory as expected and the command ran without error but node is unable to find it and throws an error (I have tried multiple packages with the same result). Below explains what I have done:

I created a new project using npm init and completed the guided package.json creation. I then created a javascript file containing this line of code.

const k = require('korbit-node');

and installed the module using npm install korbit-node then tried to run it locally using node index.js (what i called the js file) and was given this error.

```<code>$ node index.js

module.js:472
    throw err;
    ^

Error: Cannot find module 'korbit-node'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/gabe/Desktop/js_sandbox/index.js:1:73)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
</code>```

To me this seems to be a fairly straight-forward error message telling me that the package isn't installed. However my project structure looks like this:

```<code>├── index.js
├── node_modules
│   ├── debug
│   │   ├── CHANGELOG.md
│   │   ├── LICENSE
│   │   ├── Makefile
│   │   ├── README.md
│   │   ├── component.json
│   │   ├── karma.conf.js
│   │   ├── node.js
│   │   ├── package.json
│   │   └── src
│   │       ├── browser.js
│   │       ├── debug.js
│   │       ├── index.js
│   │       └── node.js
│   ├── iconv-lite
│   │   ├── Changelog.md
│   │   ├── LICENSE
│   │   ├── README.md
│   │   ├── encodings
│   │   │   ├── dbcs-codec.js
│   │   │   ├── dbcs-data.js
│   │   │   ├── index.js
│   │   │   ├── internal.js
│   │   │   ├── sbcs-codec.js
│   │   │   ├── sbcs-data-generated.js
│   │   │   ├── sbcs-data.js
│   │   │   ├── tables
│   │   │   │   ├── big5-added.json
│   │   │   │   ├── cp936.json
│   │   │   │   ├── cp949.json
│   │   │   │   ├── cp950.json
│   │   │   │   ├── eucjp.json
│   │   │   │   ├── gb18030-ranges.json
│   │   │   │   ├── gbk-added.json
│   │   │   │   └── shiftjis.json
│   │   │   ├── utf16.js
│   │   │   └── utf7.js
│   │   ├── lib
│   │   │   ├── bom-handling.js
│   │   │   ├── extend-node.js
│   │   │   ├── index.d.ts
│   │   │   ├── index.js
│   │   │   └── streams.js
│   │   └── package.json
│   ├── korbit-node
│   │   ├── README.md
│   │   ├── korbit.js
│   │   └── package.json
│   ├── lodash
│   │   ├── README.md
│   │   ├── dist
│   │   │   ├── lodash.compat.js
│   │   │   ├── lodash.compat.min.js
│   │   │   ├── lodash.js
│   │   │   ├── lodash.legacy.js
│   │   │   ├── lodash.legacy.min.js
│   │   │   ├── lodash.min.js
│   │   │   ├── lodash.mobile.js
│   │   │   ├── lodash.mobile.min.js
│   │   │   ├── lodash.underscore.js
│   │   │   └── lodash.underscore.min.js
│   │   ├── lodash.js
│   │   └── package.json
│   ├── ms
│   │   ├── index.js
│   │   ├── license.md
│   │   ├── package.json
│   │   └── readme.md
│   └── needle
│       ├── README.md
│       ├── bin
│       │   └── needle
│       ├── examples
│       │   ├── deflated-stream.js
│       │   ├── digest-auth.js
│       │   ├── download-to-file.js
│       │   ├── multipart-stream.js
│       │   ├── parsed-stream.js
│       │   ├── parsed-stream2.js
│       │   ├── stream-events.js
│       │   ├── stream-to-file.js
│       │   └── upload-image.js
│       ├── lib
│       │   ├── auth.js
│       │   ├── cookies.js
│       │   ├── decoder.js
│       │   ├── multipart.js
│       │   ├── needle.js
│       │   ├── parsers.js
│       │   └── querystring.js
│       ├── package.json
│       └── test
│           ├── basic_auth_spec.js
│           ├── compression_spec.js
│           ├── cookies_spec.js
│           ├── decoder_spec.js
│           ├── errors_spec.js
│           ├── helpers.js
│           ├── keys
│           │   ├── ssl.cert
│           │   └── ssl.key
│           ├── parsing_spec.js
│           ├── proxy_spec.js
│           ├── querystring_spec.js
│           ├── redirect_spec.js
│           ├── stream_spec.js
│           ├── url_spec.js
│           └── utils
│               ├── formidable.js
│               ├── proxy.js
│               └── test.js
└── package.json
</code>```

and I can clearly see the module in the node_modules file so I am unsure why it isn't being found.

I've seen these questions Node.js NODE_PATH environment variable
about making sure the NODE_PATH is set properly but I found that even after I explicitly pointed the path to the file it still did not work. I also of course found questions about the package not being installed but that is not the case in this situation.

Could someone please tell me why this isn't being found by node or point me to some resources about this issue/how node handles packages? I'm sure its a simple issue but everything I have found online/in the documentation has been unhelpful so far.

答:
I've run into this once before.  I made the mistake of naming the project folder the exact same as the node-module I am trying to install and require.

Is the folder your package.json file in called korbit-node?

Body:
I've been playing with node for the past day and I've run into an issue I would really appreciate help on.

I created a new project and am trying to use a module I installed using npm, the module exists in the node_modules directory as expected and the command ran without error but node is unable to find it and throws an error (I have tried multiple packages with the same result). Below explains what I have done:

I created a new project using npm init and completed the guided package.json creation. I then created a javascript file containing this line of code.

const k = require('korbit-node');

and installed the module using npm install korbit-node then tried to run it locally using node index.js (what i called the js file) and was given this error.

$ node index.js

module.js:472
    throw err;
    ^

Error: Cannot find module 'korbit-node'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/gabe/Desktop/js_sandbox/index.js:1:73)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)

To me this seems to be a fairly straight-forward error message telling me that the package isn't installed. However my project structure looks like this:

├── index.js
├── node_modules
│   ├── debug
│   │   ├── CHANGELOG.md
│   │   ├── LICENSE
│   │   ├── Makefile
│   │   ├── README.md
│   │   ├── component.json
│   │   ├── karma.conf.js
│   │   ├── node.js
│   │   ├── package.json
│   │   └── src
│   │       ├── browser.js
│   │       ├── debug.js
│   │       ├── index.js
│   │       └── node.js
│   ├── iconv-lite
│   │   ├── Changelog.md
│   │   ├── LICENSE
│   │   ├── README.md
│   │   ├── encodings
│   │   │   ├── dbcs-codec.js
│   │   │   ├── dbcs-data.js
│   │   │   ├── index.js
│   │   │   ├── internal.js
│   │   │   ├── sbcs-codec.js
│   │   │   ├── sbcs-data-generated.js
│   │   │   ├── sbcs-data.js
│   │   │   ├── tables
│   │   │   │   ├── big5-added.json
│   │   │   │   ├── cp936.json
│   │   │   │   ├── cp949.json
│   │   │   │   ├── cp950.json
│   │   │   │   ├── eucjp.json
│   │   │   │   ├── gb18030-ranges.json
│   │   │   │   ├── gbk-added.json
│   │   │   │   └── shiftjis.json
│   │   │   ├── utf16.js
│   │   │   └── utf7.js
│   │   ├── lib
│   │   │   ├── bom-handling.js
│   │   │   ├── extend-node.js
│   │   │   ├── index.d.ts
│   │   │   ├── index.js
│   │   │   └── streams.js
│   │   └── package.json
│   ├── korbit-node
│   │   ├── README.md
│   │   ├── korbit.js
│   │   └── package.json
│   ├── lodash
│   │   ├── README.md
│   │   ├── dist
│   │   │   ├── lodash.compat.js
│   │   │   ├── lodash.compat.min.js
│   │   │   ├── lodash.js
│   │   │   ├── lodash.legacy.js
│   │   │   ├── lodash.legacy.min.js
│   │   │   ├── lodash.min.js
│   │   │   ├── lodash.mobile.js
│   │   │   ├── lodash.mobile.min.js
│   │   │   ├── lodash.underscore.js
│   │   │   └── lodash.underscore.min.js
│   │   ├── lodash.js
│   │   └── package.json
│   ├── ms
│   │   ├── index.js
│   │   ├── license.md
│   │   ├── package.json
│   │   └── readme.md
│   └── needle
│       ├── README.md
│       ├── bin
│       │   └── needle
│       ├── examples
│       │   ├── deflated-stream.js
│       │   ├── digest-auth.js
│       │   ├── download-to-file.js
│       │   ├── multipart-stream.js
│       │   ├── parsed-stream.js
│       │   ├── parsed-stream2.js
│       │   ├── stream-events.js
│       │   ├── stream-to-file.js
│       │   └── upload-image.js
│       ├── lib
│       │   ├── auth.js
│       │   ├── cookies.js
│       │   ├── decoder.js
│       │   ├── multipart.js
│       │   ├── needle.js
│       │   ├── parsers.js
│       │   └── querystring.js
│       ├── package.json
│       └── test
│           ├── basic_auth_spec.js
│           ├── compression_spec.js
│           ├── cookies_spec.js
│           ├── decoder_spec.js
│           ├── errors_spec.js
│           ├── helpers.js
│           ├── keys
│           │   ├── ssl.cert
│           │   └── ssl.key
│           ├── parsing_spec.js
│           ├── proxy_spec.js
│           ├── querystring_spec.js
│           ├── redirect_spec.js
│           ├── stream_spec.js
│           ├── url_spec.js
│           └── utils
│               ├── formidable.js
│               ├── proxy.js
│               └── test.js
└── package.json

and I can clearly see the module in the node_modules file so I am unsure why it isn't being found.

I've seen these questions Node.js NODE_PATH environment variable
about making sure the NODE_PATH is set properly but I found that even after I explicitly pointed the path to the file it still did not work. I also of course found questions about the package not being installed but that is not the case in this situation.

Could someone please tell me why this isn't being found by node or point me to some resources about this issue/how node handles packages? I'm sure its a simple issue but everything I have found online/in the documentation has been unhelpful so far.


问:
Error 404 when uploading a file caused by error in update function
I'm having a hard time trying to figure out what's wrong in my code. Basically, I'm using Dropzone-js's file uploader, that uses drag and drop.  I can't upload a file because it returns me a 404 error.
I searched through my logs and found that I had a problem in my controller, in the update function.

The controller :

```<code>class ChatRoomsController < ApplicationController
before_action :authenticate_user!
before_action :set_room, only: [:index, :new, :create, :show, :edit, :signal]
before_action :set_participant, only: [:signal]

def index
  @chat_rooms = ChatRoom.all
end

def show
  # Show room messages
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:id])
  @message = Message.new

  @chat_room.participant?(current_user)

  # TODO: get participant only once
  if params[:guid]
    if @participant = User.find(params[:guid])
      @participant.joined_at = Time.now
      @chat_room.add_to_call(@participant)
    end
  elsif params[:del]
    if @participant = User.find(params[:del])
      @chat_room.remove_from_call(@participant)
    end
  end

  response = {
      room: @chat_room,
      # Get all call participants
      users: @chat_room.call_users,
      signals: deliver_signals!
  }

  respond_to do |format|
    format.html
    format.json { render json: response }
  end

end

def new
  @chat_room = ChatRoom.new
end

def edit
  # Empty
end

def create
  @chat_room = current_user.chat_rooms.build(chat_room_params)
  if @chat_room.save
    @group_room.users << current_user
    redirect_to chat_rooms_path
  else
    render 'new'
  end
end

def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  if @chat_room.update_resource(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end

def signal
  signal = signal_params
  signal[:chat_room] = @chat_room
  signal[:sender] = User.find(signal[:sender])
  signal[:recipient] = @participant
  logger.info('Signal is ' + signal.to_param)
  ChatRoomSignal.create! signal
  head 204
end

def deliver_signals!
  data = ChatRoomSignal.where recipient: @participant

  # Destroy the signals as we return them, since they have been delivered
  result = []
  data.each do |signal|
    result << {
        signal_type: signal.signal_type,
        sender_guid: signal.sender_id,
        recipient_guid: signal.recipient_id,
        data: signal.data,
        chat_room_id: signal.chat_room_id,
        timestamp: signal.created_at
    }
  end
  data.delete_all
  result
end

private

def set_participant
  @participant = User.find(params[:user_id])
rescue ActiveRecord::RecordNotFound
  # Retry with ID as GUID
  @participant = User.where(id: params[:user_id]).first
  raise unless @participant
end

def set_room
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:chat_room_id])
end

def chat_room_params
  params.require(:chat_room).permit(:title, :image)
end

def signal_params
  params.permit(:sender, :signal_type, :data)
end
</code>```

HTML code for file upload :

```<code><div class="panel-body">
  <%= form_for @chat_room, html: { multipart: true, class: "dropzone", id: "my-dropzone"} do |f| %>

    <div class="dz-message needsclick">
      <h3>Drop a file here</h3> or <strong>click</strong> to upload
    </div>

    <div class="fallback">
      <% f.file_field :image, as: :file %>
      <%= f.submit "Upload your file" %>
    </div>
 <% end %>
</div>
</code>```

The error :

```<code>[ActionCable] [test@test.com] ChatRoomsChannel is transmitting the subscription confirmation
[ActionCable] [test@test.com] ChatRoomsChannel is streaming from chat_rooms_1_channel
Started PATCH "/chat_rooms/1" for 127.0.0.1 at 2017-06-09 01:44:26 +0200
Processing by ChatRoomsController#update as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p8KEWBx7fmJmEhHgINmp5rnj+PVwGXfbPHxslSaA4Z/5zA6HIJzxeBjwcz/+GcDEQKKwPwjXNJVnBtfq7xu2qw==", "chat_rooms"=>{"image"=>#    <ActionDispatch::Http::UploadedFile:0x007f640e58f5b0 @tempfile=#<Tempfile:/tmp/RackMultipart20170609-2887-1nuat54.png>, @original_filename="Screenshot from 2017-04-12 12-47-21.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"chat_rooms[image]\"; filename=\"Screenshot from 2017-04-12 12-47-21.png\"\r\nContent-Type: image/png\r\n">}, "id"=>"1"}
  [1m[36mUser Load (0.2ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mChatRoom Load (0.2ms)[0m  [1m[34mSELECT  "chat_rooms".* FROM "chat_rooms" WHERE "chat_rooms"."id" = ? LIMIT ?[0m  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 7ms (ActiveRecord: 0.3ms)

ActiveRecord::RecordNotFound (Couldn't find ChatRoom with 'id'={:id=>nil}):

app/controllers/chat_rooms_controller.rb:62:in `update'
</code>```

Line 62 :

```<code>@chat_room = ChatRoom.find(id: params[:chat_room_id])
</code>```

So it seems like my controller is not able to find the id parameter, but i don't understand why. And this is probably the error that causes my file to return 404 error.

Thanks for the time you will take to read my post.

答:
Your params[:chat_room_id] seems to be a hash..

Try

```<code>@chat_room = ChatRoom.find(id: params[:chat_room_id][:id])
</code>```

Body:
I'm having a hard time trying to figure out what's wrong in my code. Basically, I'm using Dropzone-js's file uploader, that uses drag and drop.  I can't upload a file because it returns me a 404 error.
I searched through my logs and found that I had a problem in my controller, in the update function.

The controller :

class ChatRoomsController < ApplicationController
before_action :authenticate_user!
before_action :set_room, only: [:index, :new, :create, :show, :edit, :signal]
before_action :set_participant, only: [:signal]

def index
  @chat_rooms = ChatRoom.all
end

def show
  # Show room messages
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:id])
  @message = Message.new

  @chat_room.participant?(current_user)

  # TODO: get participant only once
  if params[:guid]
    if @participant = User.find(params[:guid])
      @participant.joined_at = Time.now
      @chat_room.add_to_call(@participant)
    end
  elsif params[:del]
    if @participant = User.find(params[:del])
      @chat_room.remove_from_call(@participant)
    end
  end

  response = {
      room: @chat_room,
      # Get all call participants
      users: @chat_room.call_users,
      signals: deliver_signals!
  }

  respond_to do |format|
    format.html
    format.json { render json: response }
  end

end

def new
  @chat_room = ChatRoom.new
end

def edit
  # Empty
end

def create
  @chat_room = current_user.chat_rooms.build(chat_room_params)
  if @chat_room.save
    @group_room.users << current_user
    redirect_to chat_rooms_path
  else
    render 'new'
  end
end

def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  if @chat_room.update_resource(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end

def signal
  signal = signal_params
  signal[:chat_room] = @chat_room
  signal[:sender] = User.find(signal[:sender])
  signal[:recipient] = @participant
  logger.info('Signal is ' + signal.to_param)
  ChatRoomSignal.create! signal
  head 204
end

def deliver_signals!
  data = ChatRoomSignal.where recipient: @participant

  # Destroy the signals as we return them, since they have been delivered
  result = []
  data.each do |signal|
    result << {
        signal_type: signal.signal_type,
        sender_guid: signal.sender_id,
        recipient_guid: signal.recipient_id,
        data: signal.data,
        chat_room_id: signal.chat_room_id,
        timestamp: signal.created_at
    }
  end
  data.delete_all
  result
end

private

def set_participant
  @participant = User.find(params[:user_id])
rescue ActiveRecord::RecordNotFound
  # Retry with ID as GUID
  @participant = User.where(id: params[:user_id]).first
  raise unless @participant
end

def set_room
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:chat_room_id])
end

def chat_room_params
  params.require(:chat_room).permit(:title, :image)
end

def signal_params
  params.permit(:sender, :signal_type, :data)
end

HTML code for file upload :

  <%= form_for @chat_room, html: { multipart: true, class: "dropzone", id: "my-dropzone"} do |f| %>

Drop a file here
 or click to upload

      <% f.file_field :image, as: :file %>
      <%= f.submit "Upload your file" %>

 <% end %>

The error :

[ActionCable] [test@test.com] ChatRoomsChannel is transmitting the subscription confirmation
[ActionCable] [test@test.com] ChatRoomsChannel is streaming from chat_rooms_1_channel
Started PATCH "/chat_rooms/1" for 127.0.0.1 at 2017-06-09 01:44:26 +0200
Processing by ChatRoomsController#update as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p8KEWBx7fmJmEhHgINmp5rnj+PVwGXfbPHxslSaA4Z/5zA6HIJzxeBjwcz/+GcDEQKKwPwjXNJVnBtfq7xu2qw==", "chat_rooms"=>{"image"=>#    <ActionDispatch::Http::UploadedFile:0x007f640e58f5b0 @tempfile=#<Tempfile:/tmp/RackMultipart20170609-2887-1nuat54.png>, @original_filename="Screenshot from 2017-04-12 12-47-21.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"chat_rooms[image]\"; filename=\"Screenshot from 2017-04-12 12-47-21.png\"\r\nContent-Type: image/png\r\n">}, "id"=>"1"}
  [1m[36mUser Load (0.2ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mChatRoom Load (0.2ms)[0m  [1m[34mSELECT  "chat_rooms".* FROM "chat_rooms" WHERE "chat_rooms"."id" = ? LIMIT ?[0m  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 7ms (ActiveRecord: 0.3ms)

ActiveRecord::RecordNotFound (Couldn't find ChatRoom with 'id'={:id=>nil}):

app/controllers/chat_rooms_controller.rb:62:in `update'

Line 62 :

@chat_room = ChatRoom.find(id: params[:chat_room_id])

So it seems like my controller is not able to find the id parameter, but i don't understand why. And this is probably the error that causes my file to return 404 error.

Thanks for the time you will take to read my post.

Body:
Your params[:chat_room_id] seems to be a hash..

Try

@chat_room = ChatRoom.find(id: params[:chat_room_id][:id])


问:
react router + express with webpack
I am working on a blog. I have an express server which has various APIs like /api/getpost , /api/newpost etc etc.

I have my react components and i am using react router 4 ,  my routes are /addpost /home etc. etc.

In my server.js i served my static files(bundel.js)

```<code>app.use(express.static(__dirname+'/dist'));
</code>```

then

```<code>app.get('*', function(res,req){
    res.sendFile(path.resolve(__dirname, 'index.html'));
});
</code>```

localhost:3000/ loads homepage properly
localhost:3000/home also loads

localhost:3000/api/getpost fails !

i couldn't find solution of this after several hours of searching

EDIT :
I am adding more details !

```<code>import { BrowserRouter as Router, Route,Redirect} from 'react-router-dom';
<Router>
 <div>
  <Route exact path="/" component ={App}>
  <Route path="/home" component ={Home}>
 </div>
</Router>
</code>```

and my server.js file

var express  = require('express');
var mongoose = require('mongoose');
    var router = require('./router');
var User = require('./app/components/data');
var path = require('path');

const app = express();

app.use(express.static(__dirname+'/dist'));

app.get('*', function(res,req){
  res.sendFile(path.resolve(__dirname ,'/dist/index.html'));
});

app.use('/api',router);

router.route('/getpost').get(function(req, res) {
   User.find(function(err,user) {
   if (err)
    res.send(err);
   res.json(user);
 });
});

 ```

 error which i got in my app :
Error: Network Error Stack trace: createError@localhost:3000/bundle.js:9088:15 handleError@localhost:3000/bundle.js:8935:14

答:
Your express file should be ordered correctly:-

Here is what you can try

```<code>var express  = require('express');
var mongoose = require('mongoose');
    var router = require('./router');
var User = require('./app/components/data');
var path = require('path');

const app = express();

app.use(express.static(__dirname+'/dist'));

app.use('/api',router);

router.route('/getpost').get(function(req, res) {
   User.find(function(err,user) {
   if (err)
    res.send(err);
   res.json(user);
 });
});

app.get('*', function(res,req){
  res.sendFile(path.resolve(__dirname ,'/dist/index.html'));
});
</code>```

Title: react router + express with webpack

Body:
I am working on a blog. I have an express server which has various APIs like /api/getpost , /api/newpost etc etc.

I have my react components and i am using react router 4 ,  my routes are /addpost /home etc. etc.

In my server.js i served my static files(bundel.js)

app.use(express.static(__dirname+'/dist'));

then

app.get('*', function(res,req){
    res.sendFile(path.resolve(__dirname, 'index.html'));
});

localhost:3000/ loads homepage properly
localhost:3000/home also loads

localhost:3000/api/getpost fails !

i couldn't find solution of this after several hours of searching

EDIT :
I am adding more details !

import { BrowserRouter as Router, Route,Redirect} from 'react-router-dom';
<Router>

  <Route exact path="/" component ={App}>
  <Route path="/home" component ={Home}>

</Router>

and my server.js file

var express  = require('express');
var mongoose = require('mongoose');
    var router = require('./router');
var User = require('./app/components/data');
var path = require('path');

const app = express();

app.use(express.static(__dirname+'/dist'));

app.get('*', function(res,req){
  res.sendFile(path.resolve(__dirname ,'/dist/index.html'));
});

app.use('/api',router);

router.route('/getpost').get(function(req, res) {
   User.find(function(err,user) {
   if (err)
    res.send(err);
   res.json(user);
 });
});

 error which i got in my app :
Error: Network Error Stack trace: createError@localhost:3000/bundle.js:9088:15 handleError@localhost:3000/bundle.js:8935:14

Body:
Your express file should be ordered correctly:-

Here is what you can try

var express  = require('express');
var mongoose = require('mongoose');
    var router = require('./router');
var User = require('./app/components/data');
var path = require('path');

const app = express();

app.use(express.static(__dirname+'/dist'));

app.use('/api',router);

router.route('/getpost').get(function(req, res) {
   User.find(function(err,user) {
   if (err)
    res.send(err);
   res.json(user);
 });
});

app.get('*', function(res,req){
  res.sendFile(path.resolve(__dirname ,'/dist/index.html'));
});


问:
Python - Using attributes to parse XML tree
There are a lot of examples on how to parse XML using tags in the tree, but what if (as in the example below) many of the tags have the same name?

```<code><SoccerFeed timestamp="20161221T144346+0000">
  <SoccerDocument Type="SQUADS Latest">
    <Team country="USA">
      <Founded>1998</Founded>
      <Name>Chicago Fire</Name>
      <Player uID="p113757">
        <Name>Patrick McLain</Name>
        <Position>Goalkeeper</Position>
        <Stat Type="first_name">Patrick</Stat>
        <Stat Type="last_name">McLain</Stat>
        <Stat Type="birth_date">1988-08-22</Stat>
        <Stat Type="birth_place">Eau Claire</Stat>
        <Stat Type="first_nationality">USA</Stat>
        <Stat Type="weight">94</Stat>
        <Stat Type="height">191</Stat>
        <Stat Type="jersey_num">23</Stat>
        <Stat Type="real_position">Goalkeeper</Stat>
        <Stat Type="real_position_side">Unknown</Stat>
        <Stat Type="join_date">2016-01-18</Stat>
        <Stat Type="country">USA</Stat>
      </Player>
    </Team>
  </SoccerDocument>
</SoccerFeed>
</code>```

If I wanted to parse only elements with a 'Stat' tag and a 'first_name' attribute, how would I do that?

答:
Using R and the xml2 library:

```<code>library("xml2")
myxml<-read_xml('<SoccerFeed timestamp="20161221T144346+0000">
<SoccerDocument Type="SQUADS Latest">
<Team country="USA">
<Founded>1998</Founded>
<Name>Chicago Fire</Name>
<Player uID="p113757">
<Name>Patrick McLain</Name>
<Position>Goalkeeper</Position>
<Stat Type="first_name">Patrick</Stat>
<Stat Type="last_name">McLain</Stat>
<Stat Type="birth_date">1988-08-22</Stat>
<Stat Type="birth_place">Eau Claire</Stat>
<Stat Type="first_nationality">USA</Stat>
<Stat Type="weight">94</Stat>
<Stat Type="height">191</Stat>
<Stat Type="jersey_num">23</Stat>
<Stat Type="real_position">Goalkeeper</Stat>
<Stat Type="real_position_side">Unknown</Stat>
<Stat Type="join_date">2016-01-18</Stat>
<Stat Type="country">USA</Stat>
</Player>
</Team>
</SoccerDocument>
</SoccerFeed>')

#get all of the Stat nodes
statnodes<-xml_nodes(myxml, "Stat")
#filter for first_name node
firstname<- statnodes[xml_attr(statnodes, "Type" )== "first_name"]
#get text value
xml_text(firstname)
</code>```

Body:
There are a lot of examples on how to parse XML using tags in the tree, but what if (as in the example below) many of the tags have the same name?

<SoccerFeed timestamp="20161221T144346+0000">
  <SoccerDocument Type="SQUADS Latest">
    <Team country="USA">
      <Founded>1998</Founded>
      <Name>Chicago Fire</Name>
      <Player uID="p113757">
        <Name>Patrick McLain</Name>
        <Position>Goalkeeper</Position>
        <Stat Type="first_name">Patrick</Stat>
        <Stat Type="last_name">McLain</Stat>
        <Stat Type="birth_date">1988-08-22</Stat>
        <Stat Type="birth_place">Eau Claire</Stat>
        <Stat Type="first_nationality">USA</Stat>
        <Stat Type="weight">94</Stat>
        <Stat Type="height">191</Stat>
        <Stat Type="jersey_num">23</Stat>
        <Stat Type="real_position">Goalkeeper</Stat>
        <Stat Type="real_position_side">Unknown</Stat>
        <Stat Type="join_date">2016-01-18</Stat>
        <Stat Type="country">USA</Stat>
      </Player>
    </Team>
  </SoccerDocument>
</SoccerFeed>

If I wanted to parse only elements with a 'Stat' tag and a 'first_name' attribute, how would I do that?

Body:
Using R and the xml2 library:

library("xml2")
myxml<-read_xml('<SoccerFeed timestamp="20161221T144346+0000">
<SoccerDocument Type="SQUADS Latest">
<Team country="USA">
<Founded>1998</Founded>
<Name>Chicago Fire</Name>
<Player uID="p113757">
<Name>Patrick McLain</Name>
<Position>Goalkeeper</Position>
<Stat Type="first_name">Patrick</Stat>
<Stat Type="last_name">McLain</Stat>
<Stat Type="birth_date">1988-08-22</Stat>
<Stat Type="birth_place">Eau Claire</Stat>
<Stat Type="first_nationality">USA</Stat>
<Stat Type="weight">94</Stat>
<Stat Type="height">191</Stat>
<Stat Type="jersey_num">23</Stat>
<Stat Type="real_position">Goalkeeper</Stat>
<Stat Type="real_position_side">Unknown</Stat>
<Stat Type="join_date">2016-01-18</Stat>
<Stat Type="country">USA</Stat>
</Player>
</Team>
</SoccerDocument>
</SoccerFeed>')

#get all of the Stat nodes
statnodes<-xml_nodes(myxml, "Stat")
#filter for first_name node
firstname<- statnodes[xml_attr(statnodes, "Type" )== "first_name"]
#get text value
xml_text(firstname)


问:
python how to get name of the enum
I have an enum like this

```<code>class testEnum(Enum):
   Code_1 = "successful response"
   Code_2 = "failure response"
</code>```

Then I have a method that takes the enum key name Code_1 and enum key value successful response as inputs.

If I send testEnum.Code_1 then that resolves to successful response and not Code_1.

I checked some documentation online that suggests to use testEnum.Code_1.name but that throws an error saing that 'name' doesn't exist for the enum item.

Does anyone know how to get the name of the enum key ?

答:
You can start your investigation with the __dict__ that comes with your object. Interesting reading is found with

```<code>print(testEnum.__dict__)
</code>```

In that dict you will see a good start which you can test with the following:

```<code>print(testEnum._member_names_)
</code>```

which, indeed, yields

```<code>['Code_1', 'Code_2']
</code>```

Title: python how to get name of the enum

Body:
I have an enum like this

class testEnum(Enum):
   Code_1 = "successful response"
   Code_2 = "failure response"

Then I have a method that takes the enum key name Code_1 and enum key value successful response as inputs.

If I send testEnum.Code_1 then that resolves to successful response and not Code_1.

I checked some documentation online that suggests to use testEnum.Code_1.name but that throws an error saing that 'name' doesn't exist for the enum item.

Does anyone know how to get the name of the enum key ?

Body:
You can start your investigation with the __dict__ that comes with your object. Interesting reading is found with

print(testEnum.__dict__)

In that dict you will see a good start which you can test with the following:

print(testEnum._member_names_)

which, indeed, yields

['Code_1', 'Code_2']