问:
Pointer memory representation and Inheritance casting
I was playing around single/multiple inheritance when I noticed that the reinterpret cast works just as well as static cast when downcasting a pointer to an object higher up in the class hierarchy to a pointer to its underlying type.

I'm not very good with words so to see what I'm trying to say, consider the following code:

```<code>#include <iostream>
#include <string>

class A {
public:
  A (void) {
  }
  virtual ~A (void) noexcept {
  }
  virtual void ABehaviour (void) const {
    std::cout << "Behaviour of Object A implemented in Object A.\n";
  }
};

class B : public A {
public:
  B (void)
    : A () {
  }
  ~B (void) noexcept override {
  }
  void ABehaviour (void) const override {
    std::cout << "Behaviour of Object A implemented in Object B.\n";
  }
  void BBehaviour (void) const {
    std::cout << "Behaviour of Object B implemented in Object B.\n";
  }
};

int main (int arg_count, char* arg_vector[]) {
  B* b_object1 = new B (); // Create an object B.
  b_object1->ABehaviour (); // This line works fine.
  b_object1->BBehaviour (); // This line works fine.

  A* a_object1 = b_object1 // Implicit Upcast to Object A.
  a_object1->ABehaviour (); // This line works fine.
  a_object1->BBehaviour (); // This is a compile time error.

  B* b_object2 = reinterinpret_cast <B*> (a_object1);
  b_object2->ABehaviour (); // This line works fine.
  b_object2->BBehaviour (); // This line works fine.

  delete b_object1;
  b_object1 = nullptr;
  a_object1 = nullptr;
  b_object2 = nullptr;

  return 0;
}
</code>```

Intuitively, the above cast should work as it is similar to calling:

```<code>B* b_object2 = static_cast <B*> (static_cast <void*> (a_object1));
</code>```

From what I've read, reinterpret_cast is a compiler directive that tells the compiler to interpret the object-being-casted's sequence of bits to a sequence of bits of the object-being-casted-to's. In the above case A* is being reinterpreted as B*.

From what I've understood when I took an introductory course in C++ a long time ago is that pointers are variables themselves that contains addresses to other variables. Hence, when the above reinterpret cast is executed, the compiler is told to interpret the pointer to A's sequence of bits as if it was a pointer to B's sequence of bits (not their content themselves).

So my question is, are my intuitions right or does the internal working of a pointer when casting a little bit different. If I was wrong would anyone care to explain how are pointers stored in the memory and how does their casting work (both up and down) internally?

Sorry about the wall of text and thank you guys in advance!

答:
a_object1 is a pointer pointing to an object of type A. So it only has access to A's methods.

Your understanding of pointers is right too. Pointers just hold the address of the object it is pointing to. So the pointer in itself doesn't have a type. When I say a pointer of type A, I mean a pointer that points to A (or a subclass of A).

A* a_object1 = b_object1 is the same as doing static_cast (b_object1).

If you want call BBehaviour() a_object1, you'll have to do static_cast(a_object1)->BBehaviour(). It'll work in this case because though a_object1 is of type A* it points to an object with runtime-type B*.

Code like static_cast(a_object1)->BBehaviour() is a sign of bad design BTW, so you want to avoid that. (If you need to do it, you'll use dynamic_cast here.)

reinterpret_cast<>() can, on the other hand, change any object to any other unrelated object. For example:

```<code>std::string str = reinterpret_cast<std::string>(a_object1)
</code>```

will compile fine, but you'll have problems while running it.

Body:
I was playing around single/multiple inheritance when I noticed that the reinterpret cast works just as well as static cast when downcasting a pointer to an object higher up in the class hierarchy to a pointer to its underlying type.

I'm not very good with words so to see what I'm trying to say, consider the following code:

#include <iostream>
#include <string>

class A {
public:
  A (void) {
  }
  virtual ~A (void) noexcept {
  }
  virtual void ABehaviour (void) const {
    std::cout << "Behaviour of Object A implemented in Object A.\n";
  }
};

class B : public A {
public:
  B (void)
    : A () {
  }
  ~B (void) noexcept override {
  }
  void ABehaviour (void) const override {
    std::cout << "Behaviour of Object A implemented in Object B.\n";
  }
  void BBehaviour (void) const {
    std::cout << "Behaviour of Object B implemented in Object B.\n";
  }
};

int main (int arg_count, char* arg_vector[]) {
  B* b_object1 = new B (); // Create an object B.
  b_object1->ABehaviour (); // This line works fine.
  b_object1->BBehaviour (); // This line works fine.

  A* a_object1 = b_object1 // Implicit Upcast to Object A.
  a_object1->ABehaviour (); // This line works fine.
  a_object1->BBehaviour (); // This is a compile time error.

  B* b_object2 = reinterinpret_cast  (a_object1);
  b_object2->ABehaviour (); // This line works fine.
  b_object2->BBehaviour (); // This line works fine.

  delete b_object1;
  b_object1 = nullptr;
  a_object1 = nullptr;
  b_object2 = nullptr;

  return 0;
}

Intuitively, the above cast should work as it is similar to calling:

B* b_object2 = static_cast  (static_cast <void*> (a_object1));

From what I've read, reinterpret_cast is a compiler directive that tells the compiler to interpret the object-being-casted's sequence of bits to a sequence of bits of the object-being-casted-to's. In the above case A* is being reinterpreted as B*.

From what I've understood when I took an introductory course in C++ a long time ago is that pointers are variables themselves that contains addresses to other variables. Hence, when the above reinterpret cast is executed, the compiler is told to interpret the pointer to A's sequence of bits as if it was a pointer to B's sequence of bits (not their content themselves).

So my question is, are my intuitions right or does the internal working of a pointer when casting a little bit different. If I was wrong would anyone care to explain how are pointers stored in the memory and how does their casting work (both up and down) internally?

Sorry about the wall of text and thank you guys in advance!

Body:
a_object1 is a pointer pointing to an object of type A. So it only has access to A's methods.

Your understanding of pointers is right too. Pointers just hold the address of the object it is pointing to. So the pointer in itself doesn't have a type. When I say a pointer of type A, I mean a pointer that points to A (or a subclass of A).

A* a_object1 = b_object1 is the same as doing static_cast<A*> (b_object1).

If you want call BBehaviour() a_object1, you'll have to do static_cast<B*>(a_object1)->BBehaviour(). It'll work in this case because though a_object1 is of type A* it points to an object with runtime-type B*.

Code like static_cast<B*>(a_object1)->BBehaviour() is a sign of bad design BTW, so you want to avoid that. (If you need to do it, you'll use dynamic_cast here.)

reinterpret_cast<>() can, on the other hand, change any object to any other unrelated object. For example:

std::string str = reinterpret_cast<std::string>(a_object1)

will compile fine, but you'll have problems while running it.


来源: stackexchange

问:
Is there a way to prevent usage of any
Is there a way that Typescript can be made to throw an error an not compile if a variable/ function is defined without the correct types or if type any is used? i.e.</p>

```<code>let var1 = 0;  --> Throw error
let var2: any; --> Throw error
let var3: number = 3;  --> OK

getNumber() {  --> Throw error
  return var3;
}

getNumber(): number {  --> OK
  return var3;
}
</code>```

答: If you use TSLint in your project you can turn on following rule: https://palantir.github.io/tslint/rules/no-any</p>

ContentLicense: CC BY-SA 3.0

Title: Is there a way to prevent usage of any

Body:
Is there a way that Typescript can be made to throw an error an not compile if a variable/ function is defined without the correct types or if type any is used? i.e.

let var1 = 0;  --> Throw error
let var2: any; --> Throw error
let var3: number = 3;  --> OK

getNumber() {  --> Throw error
  return var3;
}

getNumber(): number {  --> OK
  return var3;
}


问:
Xcode NSKeyedUnarchiver Memory Leak SKNode Extension
After days and days of researching and trying my best, I have not found a solution to a memory leak problem. I have already tried very many ideas I found in this forum but nothing seemed to help me out.

I load my GameScene.sks with this code like everyone else does:

```<code>extension SKNode {

class func unarchiveFromFile(file:String) -> SKNode? {
    if let path = Bundle.main.path(forResource: file, ofType: "sks") {
        let url = URL(fileURLWithPath: path)
        do {
            let sceneData = try Data(contentsOf: url, options: .mappedIfSafe)
            let archiver = NSKeyedUnarchiver(forReadingWith: sceneData)
            archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
            let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKNode
            archiver.finishDecoding()
            return scene
        } catch {
            print(error.localizedDescription)
            return nil
        }
    } else {
        return nil
    }
}
</code>```

and i am using it in my code here:

```<code>func load(level: String) {
    if let levelNode = SKNode.unarchiveFromFile(file: level) {
        mapNode = levelNode
        mapNode.name = "MapNode"
        self.worldLayer.addChild(mapNode)
        loadTileMap()
    }
}
</code>```

If I leave out the line self.worldLayer.addChild(mapNode) everything works perfectly and the memory usage will never rise. But if I use it (I need it!), memory keeps climbing and climbing.

With use of Instruments it says that the line with let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKNode causes all the memory leaks.

Unfortunately I do not get it and have not managed to remove my leaks.

I appreciate all help. Thanks in advance.

答: Well, I still couldn´t fix the issue but I found out some things. I can put everything I want in the scene editor (.sks) file and I will not get any memory leaks. Even Tile Maps. But as soon as I put only one tile in some tilemap memory leaks are rising very high again. How can one single tile cause all those issues?</p>

Body:
After days and days of researching and trying my best, I have not found a solution to a memory leak problem. I have already tried very many ideas I found in this forum but nothing seemed to help me out.

I load my GameScene.sks with this code like everyone else does:

extension SKNode {

class func unarchiveFromFile(file:String) -> SKNode? {
    if let path = Bundle.main.path(forResource: file, ofType: "sks") {
        let url = URL(fileURLWithPath: path)
        do {
            let sceneData = try Data(contentsOf: url, options: .mappedIfSafe)
            let archiver = NSKeyedUnarchiver(forReadingWith: sceneData)
            archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
            let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKNode
            archiver.finishDecoding()
            return scene
        } catch {
            print(error.localizedDescription)
            return nil
        }
    } else {
        return nil
    }
}

and i am using it in my code here:

func load(level: String) {
    if let levelNode = SKNode.unarchiveFromFile(file: level) {
        mapNode = levelNode
        mapNode.name = "MapNode"
        self.worldLayer.addChild(mapNode)
        loadTileMap()
    }
}

If I leave out the line self.worldLayer.addChild(mapNode) everything works perfectly and the memory usage will never rise. But if I use it (I need it!), memory keeps climbing and climbing.

With use of Instruments it says that the line with let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKNode causes all the memory leaks.

Unfortunately I do not get it and have not managed to remove my leaks.

I appreciate all help. Thanks in advance.


答: Luckily after messing around, I was able to find a solution. For anyone else who is in the same boat, switch from Cycles to Blender Renderer. </p>

Title: Blender export to JSON for THREE.js missing Materials

Body:
Good day,

I am trying to export a model I've made in Blender to JSON format so that I can use it in my THREE.js web application. Everything works fine except for the fact that it doesn't seem to export the materials correctly. In Blender, my model is colored, but when viewed in the web browser with THREE.js, the model is grey.

Here is what both outputs look like:
https://i.stack.imgur.com/4zIMG.png

This is the code for loading the JSON file into the program:

var loader = new THREE.JSONLoader();
loader.load("../tankSingleObject2.json", addModel );
function addModel(geometry, materials) {
    var mesh = new THREE.Mesh (geometry, materials);
    scene.add(mesh);
    mesh.position.z = -2;
}

And here is what the JSON file looks like:

{
"vertices":[0.202124,0.554841,0.275849,0.402124,0.554841,0.275849,0.202124,0.554841,0.0758486,0.402124,0.554841,0.0758486,-0.404745,0.554792,0.279759,-0.204745,0.554792,0.279759,-0.404745,0.554792,0.0797591,-0.204745,0.554792,0.0797591,-0.61,0.0287037,0.321036,-0.61,0.528704,0.321036,-0.61,0.0287037,0.0030361,-0.61,0.528704,0.00303607,0.61,0.0287037,0.321036,0.61,0.528704,0.321036,0.61,0.0287037,0.0030361,0.61,0.528704,0.00303607,-0.594359,0.529223,0.305839,-0.594359,0.529223,0.0182327,0.594359,0.529223,0.0182327,0.594359,0.529223,0.305839,-0.594359,0.0387877,0.30584,-0.594359,0.0387877,0.0182327,0.594359,0.0387877,0.0182327,0.594359,0.0387877,0.30584,0,0.118215,0.0370853,0,0.318215,0.137085,0.019509,0.118215,0.0390067,0.0382684,0.118215,0.0446973,0.055557,0.118215,0.0539383,0.0707107,0.118215,0.0663746,0.083147,0.118215,0.0815282,0.0923879,0.118215,0.0988169,0.0980785,0.118215,0.117576,0.1,0.118215,0.137085,0.0980785,0.118215,0.156594,0.092388,0.118215,0.175354,0.083147,0.118215,0.192642,0.0707107,0.118215,0.207796,0.055557,0.118215,0.220232,0.0382683,0.118215,0.229473,0.019509,0.118215,0.235164,-2.98023e-08,0.118215,0.237085,-0.0195091,0.118215,0.235164,-0.0382684,0.118215,0.229473,-0.0555571,0.118215,0.220232,-0.0707107,0.118215,0.207796,-0.083147,0.118215,0.192642,-0.092388,0.118215,0.175354,-0.0980785,0.118215,0.156594,-0.1,0.118215,0.137085,-0.0980785,0.118215,0.117576,-0.0923879,0.118215,0.0988168,-0.0831469,0.118215,0.0815281,-0.0707106,0.118215,0.0663745,-0.0555569,0.118215,0.0539382,-0.0382682,0.118215,0.0446972,-0.0195089,0.118215,0.0390067,0.612,0.5154,-8.9407e-08,-0.612,0.5154,2.98023e-08,0.612,0.5514,-8.9407e-08,-0.612,0.5514,2.98023e-08,0.612,0.515076,0.327056,-0.612,0.515076,0.327056,0.612,0.551076,0.327056,-0.612,0.551076,0.327056,0.612,0,-5.96046e-08,-0.612,0,5.96046e-08,0.612,0.036,-5.96046e-08,-0.612,0.036,5.96046e-08,0.612,-0.000323951,0.327056,-0.612,-0.000323951,0.327056,0.612,0.035676,0.327056,-0.612,0.035676,0.327056],
"faces":[3,0,1,3,2,0,3,4,5,7,6,0,3,8,9,11,10,1,3,10,11,15,14,1,3,14,15,13,12,1,3,12,13,9,8,1,3,10,14,12,8,1,3,13,15,18,19,1,3,19,18,22,23,1,3,11,9,16,17,1,3,9,13,19,16,1,3,15,11,17,18,1,3,22,21,20,23,1,3,17,16,20,21,1,3,16,19,23,20,1,3,18,17,21,22,1,2,24,25,26,2,2,26,25,27,2,2,27,25,28,2,2,28,25,29,2,2,29,25,30,2,2,30,25,31,2,2,31,25,32,2,2,32,25,33,2,2,33,25,34,2,2,34,25,35,2,2,35,25,36,2,2,36,25,37,2,2,37,25,38,2,2,38,25,39,2,2,39,25,40,2,2,40,25,41,2,2,41,25,42,2,2,42,25,43,2,2,43,25,44,2,2,44,25,45,2,2,45,25,46,2,2,46,25,47,2,2,47,25,48,2,2,48,25,49,2,2,49,25,50,2,2,50,25,51,2,2,51,25,52,2,2,52,25,53,2,2,53,25,54,2,2,54,25,55,2,2,55,25,56,2,2,56,25,24,2,2,56,24,26,2,2,26,27,28,2,2,28,29,30,2,2,30,31,32,2,2,32,33,34,2,2,34,35,36,2,2,36,37,38,2,2,38,39,40,2,2,40,41,42,2,2,42,43,44,2,2,44,45,46,2,2,46,47,48,2,2,48,49,50,2,2,50,51,52,2,2,52,53,54,2,2,54,55,56,2,2,56,26,28,2,2,28,30,32,2,2,32,34,36,2,2,36,38,40,2,2,40,42,44,2,2,44,46,48,2,2,48,50,52,2,2,52,54,56,2,2,56,28,32,2,2,32,36,40,2,2,40,44,48,2,2,48,52,56,2,2,56,32,40,2,2,40,48,56,2,3,57,58,60,59,3,3,61,62,64,63,3,3,57,59,63,61,3,3,60,58,62,64,3,3,65,66,68,67,3,3,69,70,72,71,3,3,65,67,71,69,3,3,68,66,70,72,3],
"metadata":{
    "generator":"io_three",
    "version":3,
    "type":"Geometry",
    "materials":4,
    "faces":86,
    "vertices":73
},
"materials":[{
    "depthTest":true,
    "DbgIndex":0,
    "wireframe":false,
    "opacity":1,
    "blending":1,
    "shading":"phong",
    "doubleSided":false,
    "DbgName":"Material.007",
    "specularCoef":50,
    "colorEmissive":[0,0,0],
    "depthWrite":true,
    "transparent":false,
    "colorSpecular":[0.5,0.5,0.5],
    "DbgColor":15658734,
    "colorDiffuse":[0.64,0.64,0.64],
    "visible":true
},{
    "depthTest":true,
    "DbgIndex":1,
    "wireframe":false,
    "opacity":1,
    "blending":1,
    "shading":"phong",
    "doubleSided":false,
    "DbgName":"Material.006",
    "specularCoef":50,
    "colorEmissive":[0,0,0],
    "depthWrite":true,
    "transparent":false,
    "colorSpecular":[0.5,0.5,0.5],
    "DbgColor":15597568,
    "colorDiffuse":[0.64,0.64,0.64],
    "visible":true
},{
    "depthTest":true,
    "DbgIndex":2,
    "wireframe":false,
    "opacity":1,
    "blending":1,
    "shading":"phong",
    "doubleSided":false,
    "DbgName":"Material.005",
    "specularCoef":50,
    "colorEmissive":[0,0,0],
    "depthWrite":true,
    "transparent":false,
    "colorSpecular":[0.5,0.5,0.5],
    "DbgColor":60928,
    "colorDiffuse":[0.64,0.64,0.64],
    "visible":true
},{
    "depthTest":true,
    "DbgIndex":3,
    "wireframe":false,
    "opacity":1,
    "blending":1,
    "shading":"phong",
    "doubleSided":false,
    "DbgName":"Material",
    "specularCoef":50,
    "colorEmissive":[0,0,0],
    "depthWrite":true,
    "transparent":false,
    "colorSpecular":[0.5,0.5,0.5],
    "DbgColor":238,
    "colorDiffuse":[0.64,0.64,0.64],
    "visible":true
}]}

The Blender file can be viewed here: https://www.dropbox.com/s/q9u7kr6rqqciknh/tankSingleObject1.blend?dl=0

Thanks in advance for the help!


问:
Is it possoble to run 'Generate Local Resources Tool' programmatically?
Is it possible to run Visual Studio tool: 'Generate Local Resources' programmatically?</p>

答:
From a macro in VS2010 you can do this:</p>

```<code>Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module Module1

    Public Sub test()
        DTE.ExecuteCommand("Tools.GenerateLocalResource")
    End Sub

End Module
</code>```

ContentLicense: CC BY-SA 2.5

Body:
From a macro in VS2010 you can do this:

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module Module1

    Public Sub test()
        DTE.ExecuteCommand("Tools.GenerateLocalResource")
    End Sub

End Module


问:
CSS - Fonts Render Differently in Firefox and Chrome
I'm using Google Fonts and CSS's @import method to include fonts onto my website.

Chrome displays the fonts beautifully; they have even weights and are crisp to view. Firefox does not replicate this rendering. See below:

On the left you can see Firefox. The font weight of the title is not consistent. You can see that the smaller descriptive text has some additional weight than the Chrome counterpart.

Chrome is on the right, and as you can see, the fonts are respectfully weighted.

I am using the following CSS in an attempt to fix this issue:

```<code>@import url('https://fonts.googleapis.com/css?family=Muli|Source+Code+Pro');

* {
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
</code>```

How can I resolve this issue and have Firefox displaying my fonts with proper weights?

Firefox Version: 57.0.1 (64 bit) [Most recent]

Chrome Version: 62.0.3202.94 (64 bit) [Most recent]

Many thanks.

答:
I have been testing a few things out, and I've found some way to make sure that Firefox doesn't show an inconsistent font weight.

I can use some jQuery to detect the browser, and from there I can add browser-specific styles. In this case, I've added a font-weight to the title block so that it has a lighter font-weight, which creates a cleaner look:

On the left is Firefox with font-weight: 400, and on the right, Chrome with font-weight: 600. See below for my browser-detecting jQuery.

```<code>if (navigator.userAgent.search("Firefox") >= 0) {
    $('body').addClass('firefox');
}
</code>```

My CSS is as follows:

```<code>body.firefox h1 {
     font-weight: 400;
}
</code>```

It's not necessarily a fix, however it removes the choppy-ness of the font weighting.

Please feel free to comment about any better ways of doing this, or with a more practical solution to the question.

Many thanks.

Body:
I'm using Google Fonts and CSS's @import method to include fonts onto my website.

Chrome displays the fonts beautifully; they have even weights and are crisp to view. Firefox does not replicate this rendering. See below:

On the left you can see Firefox. The font weight of the title is not consistent. You can see that the smaller descriptive text has some additional weight than the Chrome counterpart.

Chrome is on the right, and as you can see, the fonts are respectfully weighted.

I am using the following CSS in an attempt to fix this issue:

@import url('https://fonts.googleapis.com/css?family=Muli|Source+Code+Pro');

* {
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

How can I resolve this issue and have Firefox displaying my fonts with proper weights?

Firefox Version: 57.0.1 (64 bit) [Most recent]

Chrome Version: 62.0.3202.94 (64 bit) [Most recent]

Many thanks.

Body:
I have been testing a few things out, and I've found some way to make sure that Firefox doesn't show an inconsistent font weight.

I can use some jQuery to detect the browser, and from there I can add browser-specific styles. In this case, I've added a font-weight to the title block so that it has a lighter font-weight, which creates a cleaner look:

On the left is Firefox with font-weight: 400, and on the right, Chrome with font-weight: 600. See below for my browser-detecting jQuery.

if (navigator.userAgent.search("Firefox") >= 0) {
    $('body').addClass('firefox');
}

My CSS is as follows:

body.firefox h1 {
     font-weight: 400;
}

It's not necessarily a fix, however it removes the choppy-ness of the font weighting.

Please feel free to comment about any better ways of doing this, or with a more practical solution to the question.

Many thanks.


问:
React router v4 with redux protected routes and auth
I'm using react router v4 with redux and i want to make use of private and protected route to redirect if user is not logged in.

i have this Routes component:

```<code>class Routes extends Component {

render() {
    const { auth } = this.props;
    // so checks against isAuthenticated can pass
    if (auth.isAuthenticated !== undefined) {
        return (
            <div>
                <Route exact component={() => <Home />} />
                <PublicRoute
                    authed={() => auth.isAuthenticated}
                    path="/login"
                    component={(routerProps) => <Login {...routerProps} />}
                />
                <PublicRoute
                    authed={() => auth.isAuthenticated}
                    path="/register"
                    component={(routerProps) => <Register {...routerProps} />}
                />
                <PrivateRoute
                    authed={() => auth.isAuthenticated}
                    path="/dashboard"
                    component={Dashboard}
                />
            </div>
        );
    } else {
        return <div></div>
    }
  }
}

function mapStateToProps(state) {
  return {
    auth: state.auth
  }
}

export default withRouter(connect(mapStateToProps)(Routes));
</code>```

it is implemented like this:

```<code>class Main extends Component {

constructor(props) {
    super(props);
}

componentDidMount() {
    store.dispatch(checkAuth());
}

render() {
    return (
        <Provider store={store}>
            <Router>
                <Theme>
                    <Routes />
                </Theme>
            </Router>
        </Provider>
    );
  }
}
</code>```

This is the PrivateRoute:

```<code>export function PrivateRoute({ component: Component, authed, ...rest }) {
const isAuthenticated = authed();
return (
    <Route
        {...rest}
        render={props =>
            isAuthenticated === true ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/login",
                        state: { from: props.location }
                    }}
                />
            )
        }
    />
  );
}
</code>```

What is the best way to pass that auth prop, is it ok if i connect the Routes component and pass the auth from there, or should i be passed from somewhere else, maybe connect each component that needs it and read from there? Also how would this approach play with nested routes, like /dashboard/settings? Thanks

答:
Actually, it is ok to use this type of private route in react, but you should check two moments:

I should check, that you do not have exact attribute, so all your routes like /dashboard/panel1,  /dashboard/panel2 will be private to

 auth.isAuthenticated}
  path="/dashboard"
  component={Dashboard}
/>

You will have some problem with connect. There is a simple fix for that:

export default connect(mapStateToProps, null, null, {
  pure: false,
})(PrivateRoute);

more information here:
React router private routes / redirect not working

Body:
I'm using react router v4 with redux and i want to make use of private and protected route to redirect if user is not logged in.

i have this Routes component:

class Routes extends Component {

render() {
    const { auth } = this.props;
    // so checks against isAuthenticated can pass
    if (auth.isAuthenticated !== undefined) {
        return (

                <Route exact component={() => <Home />} />
                <PublicRoute
                    authed={() => auth.isAuthenticated}
                    path="/login"
                    component={(routerProps) => <Login {...routerProps} />}
                />
                <PublicRoute
                    authed={() => auth.isAuthenticated}
                    path="/register"
                    component={(routerProps) => <Register {...routerProps} />}
                />
                <PrivateRoute
                    authed={() => auth.isAuthenticated}
                    path="/dashboard"
                    component={Dashboard}
                />

        );
    } else {
        return

    }
  }
}

function mapStateToProps(state) {
  return {
    auth: state.auth
  }
}

export default withRouter(connect(mapStateToProps)(Routes));

it is implemented like this:

class Main extends Component {

constructor(props) {
    super(props);
}

componentDidMount() {
    store.dispatch(checkAuth());
}

render() {
    return (
        <Provider store={store}>
            <Router>
                <Theme>
                    <Routes />
                </Theme>
            </Router>
        </Provider>
    );
  }
}

This is the PrivateRoute:

export function PrivateRoute({ component: Component, authed, ...rest }) {
const isAuthenticated = authed();
return (
    <Route
        {...rest}
        render={props =>
            isAuthenticated === true ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/login",
                        state: { from: props.location }
                    }}
                />
            )
        }
    />
  );
}

What is the best way to pass that auth prop, is it ok if i connect the Routes component and pass the auth from there, or should i be passed from somewhere else, maybe connect each component that needs it and read from there? Also how would this approach play with nested routes, like /dashboard/settings? Thanks


问:
Calling a constructor for an object more than once
This code works fine. Instead of calling a setter function I used constructor and I am calling constructor for an object multiple times. Isn't constructor called only once for one object? Is it right or wrong to do as I did?</p>

```<code>    ifstream myfile;
    myfile.open("phones.txt");
    DirectoryEntry *TelephoneDirectory = new DirectoryEntry[size]; // default constructor
    for (int i = 0; i < size; i++)
    {
        TelephoneDirectory[i] = DirectoryEntry(myfile); // parameterized constructor
    }
    myfile.close();
</code>```

答:
Instead of calling a setter function I used constructor and I am calling constructor for an object multiple times.

No you are not calling constructor multiple times. You code is pretty much similar to:

```<code>DirectoryEntry object;
object = DirectoryEntry( myfile );
</code>```

you create object, invoking default ctor then create temporary and assign it to object. There are no multiple calls of ctor for object. So your code is completely valid (assuming ctors and assignment operator are valid), but if it does what you really wanted depends, as you do not seem to understand what is going on here.

Body:
This code works fine. Instead of calling a setter function I used constructor and I am calling constructor for an object multiple times. Isn't constructor called only once for one object? Is it right or wrong to do as I did?

    ifstream myfile;
    myfile.open("phones.txt");
    DirectoryEntry *TelephoneDirectory = new DirectoryEntry[size]; // default constructor
    for (int i = 0; i < size; i++)
    {
        TelephoneDirectory[i] = DirectoryEntry(myfile); // parameterized constructor
    }
    myfile.close();

Body:
Instead of calling a setter function I used constructor and I am calling constructor for an object multiple times.

No you are not calling constructor multiple times. You code is pretty much similar to:

DirectoryEntry object;
object = DirectoryEntry( myfile );

you create object, invoking default ctor then create temporary and assign it to object. There are no multiple calls of ctor for object. So your code is completely valid (assuming ctors and assignment operator are valid), but if it does what you really wanted depends, as you do not seem to understand what is going on here.


问:
ResponseBuilder - Long cannot be cast to Collection?
I have this:
Map<String, Object> social = new HashMap<String, Object>(); social.put("socialId", socialId);
social.put("savedComment", savedComment);

and I'm trying to do this: builder = Response.status(Response.Status.OK).entity(social);

Why am I receiving HTTP Status 500 - java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.Collection, since Object should work with Long and general Object classes? Can't I send two different types of data, so data contains data.socialId (as a Long) and data.savedComment (as an object)?

*By the way, socialId is a Long object, and savedComment is a SocialComment object.

答:
If you look at the API docs for entity(), it says

Any Java type instance for a response entity, that is supported by
  the runtime can be passed. It is the callers responsibility to wrap
  the actual entity with GenericEntity if preservation of its generic
  type is required.

So your map needs to support GenericEntity if you need to preserve it's type in the response.

Source: https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.ResponseBuilder.html#entity-java.lang.Object-


问:
Making asynchronous HTTP calls from flows
In Corda, how can I make an asynchronous HTTP request from within a flow? Is there an API to suspend a flow while awaiting the response to the HTTP call, or a way to provide a callback?</p>

答:
Corda uses quasar fibers to make sync-like (async) calls. Fortunately quasar has support for java's Future and guava's ListenableFuture.

Based on that, you could create a Flow like this

```<code>@InitiatingFlow
class ListenableFutureFlow<V>(val futureFn: () -> ListenableFuture<V>,
                              override val progressTracker: ProgressTracker) : FlowLogic<V>() {

    constructor(futureFn: () -> ListenableFuture<V>) : this(futureFn, tracker())

    companion object {
        object EXECUTING_FUTURE: ProgressTracker.Step("Executing future call inside fiber")
        fun tracker() = ProgressTracker(EXECUTING_FUTURE)
    }

    @Suspendable
    override fun call(): V {
        progressTracker.currentStep = EXECUTING_FUTURE
        return AsyncListenableFuture.get(futureFn())
    }
}
</code>```

And you can use it like this:

```<code>val asyncResponse = subFlow(ListenableFutureFlow { myAsyncCall(param1, param2) })
</code>```

It is not the best solution but at least works with corda's infrastructure :)

Let me know if it works for you!

Body:
Corda uses quasar fibers to make sync-like (async) calls. Fortunately quasar has support for java's Future and guava's ListenableFuture.

Based on that, you could create a Flow like this

@InitiatingFlow
class ListenableFutureFlow<V>(val futureFn: () -> ListenableFuture<V>,
                              override val progressTracker: ProgressTracker) : FlowLogic<V>() {

    constructor(futureFn: () -> ListenableFuture<V>) : this(futureFn, tracker())

    companion object {
        object EXECUTING_FUTURE: ProgressTracker.Step("Executing future call inside fiber")
        fun tracker() = ProgressTracker(EXECUTING_FUTURE)
    }

    @Suspendable
    override fun call(): V {
        progressTracker.currentStep = EXECUTING_FUTURE
        return AsyncListenableFuture.get(futureFn())
    }
}

And you can use it like this:

val asyncResponse = subFlow(ListenableFutureFlow { myAsyncCall(param1, param2) })

It is not the best solution but at least works with corda's infrastructure :)

Let me know if it works for you!


问:
Is it possible to load an image from an image field into a PDF in SuiteScript 2.0
I am currently doing a field lookup for several fields from a parent record and populating the results into a body variable prior to converting to a PDF (xml to pdf) - this works fine but one of the fields is an image field and i can only get the value of the file to populate in the pdf, I am trying to load the image itself so the image displays in the PDF - is this possible?</p>

答:
So the simple way in your workflow action script would be to take the internalid of the image and use the file api to get the URL:

```<code>var fileObj = nlapiLoadFile(id);
imgURLForPDF = fileObj.getURL();
</code>```

or SS2

```<code>//require or define includes N/file
var fileObj = file.load({id:id});
imgURLForPDF = fileObj.url;
</code>```

But there's also a somewhat odd and undocumented way. When you do an nlapiLookupField call on an image field with the getText parameter set to true you get back the image url instead of the image name. So if you are doing some text lookups on the parent field then you can get your image url in one go:

```<code>var valueFields = nlapiLookupField('customrecord_parent', parentId, ['custrecord_simple1', 'custrecord_simple2']);
var textFields = nlapiLookupField('customrecord_parent', parentId, ['custrecord_imagefield', 'custrecord_listfield'], true);
imgURLForPDF = textFields.custrecord_imagefield; //!
</code>```

The images need to be made available without login. You'll generally have to prefix the values obtained above with your data center url so your freemarker code would look something like:

```<code><img src="https://system.na2.netsuite.com${parentValues.imgURLForPDF}"/>
</code>```

Body:
So the simple way in your workflow action script would be to take the internalid of the image and use the file api to get the URL:

var fileObj = nlapiLoadFile(id);
imgURLForPDF = fileObj.getURL();

or SS2

//require or define includes N/file
var fileObj = file.load({id:id});
imgURLForPDF = fileObj.url;

But there's also a somewhat odd and undocumented way. When you do an nlapiLookupField call on an image field with the getText parameter set to true you get back the image url instead of the image name. So if you are doing some text lookups on the parent field then you can get your image url in one go:

var valueFields = nlapiLookupField('customrecord_parent', parentId, ['custrecord_simple1', 'custrecord_simple2']);
var textFields = nlapiLookupField('customrecord_parent', parentId, ['custrecord_imagefield', 'custrecord_listfield'], true);
imgURLForPDF = textFields.custrecord_imagefield; //!

The images need to be made available without login. You'll generally have to prefix the values obtained above with your data center url so your freemarker code would look something like:

<img src="https://system.na2.netsuite.com${parentValues.imgURLForPDF}"/>


问:
New-SMBShare not working when path is a variable
Following is working:

```<code>$ New-SMBShare  -name "xyz$" -Path "C:\TEMP\smbshare4" -FullAccess "NT AUTHORITY\Authenticated Users"
</code>```

But not this one where I pass -path as a variable $dirPath="C:\TEMP\\smbshare4"

```<code>$ New-SMBShare  -name "xyz$" -Path  $dirPath  -FullAccess "NT AUTHORITY\Authenticated Users"

New-SMBShare : The filename, directory name, or volume label syntax is incorrect.
At line:1 char:1
+ New-SMBShare  -name "xyz$" -Path  $dirPath  -FullAccess "NT AUTHORITY\Authentica ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified (MSFT_SMBShare:ROOT/Microsoft/Windows/SMB/MSFT_SMBShare) [New-SmbShare], CimException
+ FullyQualifiedErrorId : Windows System Error 123,New-SmbShare
</code>```

答:
Double backward slashes "\" was the problem. </p>

<p>$dirPath="C:\TEMP\smbshare4" worked.</p>

Body:
Following is working:

$ New-SMBShare  -name "xyz$" -Path "C:\TEMP\smbshare4" -FullAccess "NT AUTHORITY\Authenticated Users"

But not this one where I pass -path as a variable $dirPath="C:\TEMP\\smbshare4"

$ New-SMBShare  -name "xyz$" -Path  $dirPath  -FullAccess "NT AUTHORITY\Authenticated Users"

New-SMBShare : The filename, directory name, or volume label syntax is incorrect.
At line:1 char:1
+ New-SMBShare  -name "xyz$" -Path  $dirPath  -FullAccess "NT AUTHORITY\Authentica ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified (MSFT_SMBShare:ROOT/Microsoft/Windows/SMB/MSFT_SMBShare) [New-SmbShare], CimException
+ FullyQualifiedErrorId : Windows System Error 123,New-SmbShare

Body:
Double backward slashes "\" was the problem.

$dirPath="C:\TEMP\smbshare4" worked.


问:
studio.sh is not working on ubuntu 17.04
i have a problem in running ./studio.sh and when I try to run it by terminal , this error shows in the picture attached

click to see image

答:
You need to to into the directory where your studio.sh file exists as below :

```<code>/opt/android-studio/bin/studio.sh
</code>```

I am using path to android studio in my system, You need to your system's path to android studio, where your android studio is located.

Body:
You need to to into the directory where your studio.sh file exists as below :

/opt/android-studio/bin/studio.sh

I am using path to android studio in my system, You need to your system's path to android studio, where your android studio is located.


问:
PHP users local time
Hey Stackfriends =P
I know about the time() and the date() functuions,
but what I want to achieve is that the user from china gets another time shown than the user from France.
I cannot use JavaScript, because I am also using the local time for some calculations.</p>

答:
One way would be to use something like the IP to City database from MaxMind - this can give you a timezone for the users IP adddress.

Alternatively, just ask the user what timezone they prefer and remember it in a cookie or session variable.

Title: PHP users local time


问:
How do i reverse each character in a string?
```<code>class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}
</code>```

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

答:
You can use stream-api for your goal:</p>

```<code>Stream.of(str.split(" "))
            .map(s -> new StringBuilder(s).reverse().toString())
            .reduce((s1, s2) -> s1 + " " + s2)
            .orElse(null);
</code>```

Body:
class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

Body:
You can use stream-api for your goal:

Stream.of(str.split(" "))
            .map(s -> new StringBuilder(s).reverse().toString())
            .reduce((s1, s2) -> s1 + " " + s2)
            .orElse(null);


问:
How to collect many Pandas dataframes into one in loop
I try to collect many pandas dataframes into one, in loop/
My code is:

```<code>import pandas as pd
from pathlib import Path
from simpledbf import Dbf5

p = Path("")
df = pd.DataFrame()

for i in p.glob('*.dbf'):
    dbf = Dbf5(i.name, codec = '866')

    t = dbf.to_dataframe()
    print(t)   # prints no empty dataframe

    df.append(t)

print(df)  # prints empty dataframe
</code>```

But i have empty result.
Where is my mistake?

答:
df.append is not a inplace operation, you must assign back to df.  It returns a modified dataframe.

```<code>df = df.append(t)
</code>```

Body:
I try to collect many pandas dataframes into one, in loop/
My code is:

import pandas as pd
from pathlib import Path
from simpledbf import Dbf5

p = Path("")
df = pd.DataFrame()

for i in p.glob('*.dbf'):
    dbf = Dbf5(i.name, codec = '866')

    t = dbf.to_dataframe()
    print(t)   # prints no empty dataframe

    df.append(t)

print(df)  # prints empty dataframe

But i have empty result.
Where is my mistake?

Body:
df.append is not a inplace operation, you must assign back to df.  It returns a modified dataframe.

df = df.append(t)


问:
Angular2: How do you pass a selected item from a HTML datalist element back to the component?
I have simple component which includes a  to dreate a drop-down box. This is list is filled with the results from a Web API call. For display purposes I only use two fields of the item. However, once an element has been selected I need to do stuff with all the other fields. How do I pass the entire element back to the component?

Really would appreciate any help.

```<code><h1>Get Locations</h1>
<div>
    <div>
        <input list="browsers" name="browser" #term (keyup)="search(term.value)">
        <datalist id="browsers">
            <option *ngFor="let item of items | async" >
                {{item.code + " " + item.description}}
            </option>
        </datalist>
    </div>
    <input type="submit" value="Click" (click)="onSelect(item)" />
</div>
</code>```

The component code is as follows:

```<code>import { Component, OnInit }        from '@angular/core';
import { Observable }       from 'rxjs/Observable';
import { Subject }          from 'rxjs/Subject';
import { LocationService } from './location.service';
import {Location} from './location.component';
import './rxjs-operators';

@Component({
    selector: 'lesson-08',
    templateUrl: './views/lesson08.html',
    providers: [LocationService]
})
export class Lesson08 implements OnInit{

    constructor(private locationService: LocationService) { }

    aLoc: Location;

    ngOnInit() {
        this.aLoc = new Location();
    }

    errorMessage: string;
    locations: Location[];
    mode = 'Observable';
    displayValue: string;

    private searchTermStream = new Subject<string>();

    search(term: string) {
        this.searchTermStream.next(term);
    }

    onSelect(item: Location) {
        // do stuff with this location

    }

    items: Observable<Location[]> = this.searchTermStream
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap((term: string) => this.locationService.search(term));
    }
</code>```

答: The (click) event calling the method should be on the option selected. Your declared "item" is only known in the scope of the *ngFor, so on the levels of its children. You declared it on a too high level.</p>

Body:
I have simple component which includes a  to dreate a drop-down box. This is list is filled with the results from a Web API call. For display purposes I only use two fields of the item. However, once an element has been selected I need to do stuff with all the other fields. How do I pass the entire element back to the component?

Really would appreciate any help.

Get Locations

        <input list="browsers" name="browser" #term (keyup)="search(term.value)">
        <datalist id="browsers">
            <option *ngFor="let item of items | async" >
                {{item.code + " " + item.description}}
            </option>
        </datalist>

    <input type="submit" value="Click" (click)="onSelect(item)" />

The component code is as follows:

import { Component, OnInit }        from '@angular/core';
import { Observable }       from 'rxjs/Observable';
import { Subject }          from 'rxjs/Subject';
import { LocationService } from './location.service';
import {Location} from './location.component';
import './rxjs-operators';

@Component({
    selector: 'lesson-08',
    templateUrl: './views/lesson08.html',
    providers: [LocationService]
})
export class Lesson08 implements OnInit{

    constructor(private locationService: LocationService) { }

    aLoc: Location;

    ngOnInit() {
        this.aLoc = new Location();
    }

    errorMessage: string;
    locations: Location[];
    mode = 'Observable';
    displayValue: string;

    private searchTermStream = new Subject<string>();

    search(term: string) {
        this.searchTermStream.next(term);
    }

    onSelect(item: Location) {
        // do stuff with this location

    }

    items: Observable<Location[]> = this.searchTermStream
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap((term: string) => this.locationService.search(term));
    }


问:
CarbonKit CarbonTabSwipeNavigation, Viewcontrollers not aligning correctly
I'm using Carbonkit's CarbonTabSwipeNavigation by ermalkaleci , when the view loads, the viewcontrollers are aligned properly, then when switching to the second viewcontroller the alignment of the second viewcontroller is correct but when scrolling back to the first viewcontroller, it is aligned wrong and a small portion of the second viewcontroller is visible. Tried everything I could find but no luck so far.

My current setup I'm using a toolbar but same behavior when inserting with insertIntoRootViewController :(

```<code>    class func setupCarbonPages(carbonSwipeTabsItem:CarbonTabSwipeNavigation,tabTitles:[String],totalWidth: CGFloat) -> CarbonTabSwipeNavigation{

    // Setup the default style
    carbonSwipeTabsItem.toolbar.translucent = false
    carbonSwipeTabsItem.setIndicatorColor(AppConfig.BLUECOLOR)
    carbonSwipeTabsItem.setNormalColor(AppConfig.BLUECOLOR)
    carbonSwipeTabsItem.setSelectedColor(AppConfig.BLUECOLOR, font: UIFont.boldSystemFontOfSize(14))
    carbonSwipeTabsItem.setTabExtraWidth(CGFloat(0))
    carbonSwipeTabsItem.setNormalColor(AppConfig.BLUECOLOR, font: AppConfig.REGULAR_FONT_16)
    carbonSwipeTabsItem.setSelectedColor(AppConfig.BLUECOLOR, font: AppConfig.REGULAR_FONT_16)

    // Assign tab width & preload all data
    let menuTabItems:UInt = UInt(tabTitles.count)
    let tabWidth = (totalWidth / CGFloat(menuTabItems))
    for index:UInt in 0 ..< menuTabItems {
        carbonSwipeTabsItem.carbonSegmentedControl!.setWidth(tabWidth, forSegmentAtIndex: Int(index))
    }

    return carbonSwipeTabsItem
}
</code>```

Then in my viewcontroller :

```<code>private func setupSwipableTabs(){
    let width = self.view.frame.width

    carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: menuTabTitles as [AnyObject], toolBar: self.toolBar,delegate: self)
    Helper.setupCarbonPages(carbonTabSwipeNavigation, tabTitles: menuTabTitles, totalWidth: self.view.frame.width).insertIntoRootViewController(self)
    Helper.preloadCarbonPages(carbonTabSwipeNavigation, tabs: 2)
}
</code>```

Library: https://github.com/ermalkaleci/CarbonKit

(Red line is part of the second viewcontroller)

答:
you can set width of its segment:</p>

```<code>carbonTabSwipeNavigation.carbonSegmentedControl?.setWidth(widthItem, forSegmentAt: 0)
</code>```

Body:
I'm using Carbonkit's CarbonTabSwipeNavigation by ermalkaleci , when the view loads, the viewcontrollers are aligned properly, then when switching to the second viewcontroller the alignment of the second viewcontroller is correct but when scrolling back to the first viewcontroller, it is aligned wrong and a small portion of the second viewcontroller is visible. Tried everything I could find but no luck so far.

My current setup I'm using a toolbar but same behavior when inserting with insertIntoRootViewController :(

    class func setupCarbonPages(carbonSwipeTabsItem:CarbonTabSwipeNavigation,tabTitles:[String],totalWidth: CGFloat) -> CarbonTabSwipeNavigation{

    // Setup the default style
    carbonSwipeTabsItem.toolbar.translucent = false
    carbonSwipeTabsItem.setIndicatorColor(AppConfig.BLUECOLOR)
    carbonSwipeTabsItem.setNormalColor(AppConfig.BLUECOLOR)
    carbonSwipeTabsItem.setSelectedColor(AppConfig.BLUECOLOR, font: UIFont.boldSystemFontOfSize(14))
    carbonSwipeTabsItem.setTabExtraWidth(CGFloat(0))
    carbonSwipeTabsItem.setNormalColor(AppConfig.BLUECOLOR, font: AppConfig.REGULAR_FONT_16)
    carbonSwipeTabsItem.setSelectedColor(AppConfig.BLUECOLOR, font: AppConfig.REGULAR_FONT_16)

    // Assign tab width & preload all data
    let menuTabItems:UInt = UInt(tabTitles.count)
    let tabWidth = (totalWidth / CGFloat(menuTabItems))
    for index:UInt in 0 ..< menuTabItems {
        carbonSwipeTabsItem.carbonSegmentedControl!.setWidth(tabWidth, forSegmentAtIndex: Int(index))
    }

    return carbonSwipeTabsItem
}

Then in my viewcontroller :

private func setupSwipableTabs(){
    let width = self.view.frame.width

    carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: menuTabTitles as [AnyObject], toolBar: self.toolBar,delegate: self)
    Helper.setupCarbonPages(carbonTabSwipeNavigation, tabTitles: menuTabTitles, totalWidth: self.view.frame.width).insertIntoRootViewController(self)
    Helper.preloadCarbonPages(carbonTabSwipeNavigation, tabs: 2)
}

Library: https://github.com/ermalkaleci/CarbonKit

(Red line is part of the second viewcontroller)

Body:
you can set width of its segment:

carbonTabSwipeNavigation.carbonSegmentedControl?.setWidth(widthItem, forSegmentAt: 0)


问:
Broken dependencies after upgrading from Visual Studio 2017 15.4.5 to 15.5
I have a solution that contains:

Asp.Net Core 1.1 Project targeting the Full Framework 4.61

Several Class Library Projects targeting Full Framework 4.61

This solution compiled without errors in Visual Studio 15.4.5.

I upgraded Visual Studio to version 15.5 and now all my dependencies are broken, see screenshot.

Interestingly, it turns out that the solution will in compile 15.5 even though it's showing all those warning icons on the dependencies. See below:

So that's got me really scratching my head. The solution compiles, but Visual Studio is showing all those warning icons on the dependencies. Why? It seems like the dependencies are't broken if the solution compiles. But the warning icons must mean something. Hmmm

Any idea why this happened and what I can do to make all the warning icons disappear from the Web Project's dependencies?

答:
I figured it out.  Visual Studio 2017 V15.5 doesn't like right parentheses in a project name for some reason, at least not in an Asp.Net Core project.  To figure this out I started by using VS to create a new default Asp.Net Core Project and the dependencies all looked fine.

Then I edited the name of the project in VS to start with 1)  (something I typically do so that the web project will be listed first).  And all the dependencies showed the warning sign.

The solution still compiles but the warning signs on dependencies remain.  Even closing and reopening the solution dosen't fix it.  Then I changed the name of the name of the project back to not have the ")" char in it and the warning signs on dependencies remain but if I close the solution and reopen it then they dependencies look good again.  Sometimes I found that I needed to close the solution and reopen it to get the fix to show but sometimes it would show right away when I removed the ")" char.  Not sure why the inconsistency.


问:
How can I ensure that all primitives are at least null-initialized in my iOS app?
Under ARC, all objects are nil-initialized if they are declared but not used, but the same is not true of primitives. I'd like to trade some performance for safety and make sure that they're always initialized. Is there some flag I can pass to clang to have it nil-initialize everything by default?</p>

答:
There is no flag that we can pass to do this. The primitives you declare are initialized to some value when they are created, you just do not know what that value will be. You cannot set any primitive types to nil.

Here is a post that you may find helpful to understand primitives and nil better.


问:
Absolute line numbers in spacemacs
Does the spacemacs have a absolute line number setting, opposed to relative line numbers in the emacs dot files " dotspacemacs-line-numbers 'relative "?</p>

答:
set it to t

From the documentation:

Documentation: Control line numbers activation. If set to ‘t’ or
  ‘relative’ line numbers are turned on in all ‘prog-mode’ and
  ‘text-mode’ derivatives. If set to ‘relative’, line numbers are
  relative.

Title: Absolute line numbers in spacemacs


答:
Try this, </p>

```<code>df['8thcol'] = df.apply(lambda x: x[' is1'] + x[' is5'] + x[' is10'] + \
                                x['im1'] + x['im5']+ x['im10'], axis=1)
const = 5 # any constant value
df['8thcol']  = df.8thcol * const

df
</code>```

Title: Adding a column to a dataframe

Body:
I have a dataframe like this:

case    is1     is5     is10    im1     im5     im10
686     0.1406  0.2997  0.1490  0.1339  0.1350  0.1417
950     0.1602  0.3448  0.1719  0.0884  0.0962  0.1385
1005    0.1641  0.2606  0.1507  0.1306  0.1613  0.1328
1005    0.1456  0.3097  0.1825  0.1116  0.1295  0.1211

I'd like to add a 8th column using a formula, say

const1*is1+const2*is2+...const6*im10

How would I do that?

Body:
Try this,

df['8thcol'] = df.apply(lambda x: x[' is1'] + x[' is5'] + x[' is10'] + \
                                x['im1'] + x['im5']+ x['im10'], axis=1)
const = 5 # any constant value
df['8thcol']  = df.8thcol * const

df


问:
Highlight cells based on cell content with Excel VBA
This is for an Microsoft Excel VBA macro. What it is supposed to do, for every row, when "Late" is entered into column C, to highlight the cell 2 spaces to the left and Range of cells 3 spaces to the right through 43. So example is C4 contains "Late", highlight A4 and F4:AW4. Same goes for the word "Hold" just a different color.</p>

```<code>Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = lastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i & ":AW" & i).ClearContents
        .Range("F" & i & ":AW" & i).ClearContents

     End If
  Next i
  Application.EnableEvents = True
End With
End Sub
</code>```

答:
Great! I wanted to run this in the worksheet and not as a module. So i added a few extra lines and ByVal Target As Range to fire everytime a change is made in the range but it doesn't seem to work. Am i missing something?</p>

```<code>Private Sub Highlight_Condition(ByVal Target As Range)

Dim LastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = LastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i).EntireRow.Interior.ColorIndex = xlNone
     End If
  Next i
  Application.EnableEvents = True
End With

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is for an Microsoft Excel VBA macro. What it is supposed to do, for every row, when "Late" is entered into column C, to highlight the cell 2 spaces to the left and Range of cells 3 spaces to the right through 43. So example is C4 contains "Late", highlight A4 and F4:AW4. Same goes for the word "Hold" just a different color.

Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = lastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i & ":AW" & i).ClearContents
        .Range("F" & i & ":AW" & i).ClearContents

     End If
  Next i
  Application.EnableEvents = True
End With
End Sub

Body:
Great! I wanted to run this in the worksheet and not as a module. So i added a few extra lines and ByVal Target As Range to fire everytime a change is made in the range but it doesn't seem to work. Am i missing something?

Private Sub Highlight_Condition(ByVal Target As Range)

Dim LastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = LastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i).EntireRow.Interior.ColorIndex = xlNone
     End If
  Next i
  Application.EnableEvents = True
End With

End Sub


问:
How to render HTML elements in different orders when in mobile view?
I have the following HTML:

```<code><div class="row proadjuster">
  <div class="col-lg-5 propadder"></div>
  <div class="col-lg-7 pro2"></div>
</div>
</code>```

Is it possible to make sure col-lg-7 displays first when in mobile view?

答:
If you mean like to col-lg-7 to switch position with col-lg-5, than you can make it like this</p>

```<code>.row {
display: flex;
}

@media screen only and (max-width: 767px) {
.col-lg-7 {
order: 1;
}
.col-lg-5 {
order: 2;
}
}
</code>```

Body:
I have the following HTML:

Is it possible to make sure col-lg-7 displays first when in mobile view?

Body:
If you mean like to col-lg-7 to switch position with col-lg-5, than you can make it like this

.row {
display: flex;
}

@media screen only and (max-width: 767px) {
.col-lg-7 {
order: 1;
}
.col-lg-5 {
order: 2;
}
}


问:
Android Studio - ADB start server fails, adbkey check fails
Problem: adb start-server fails.

```<code>--- adb starting (pid 1414) ---
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Version 27.0.0-4455170
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Installed as /Users/[username]/Library/Android/sdk/platform-tools/adb
adb I 12-05 17:28:30  1414 48453 main.cpp:57]
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:416]
adb_auth_init...
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:174] read_key_file '/Users/[username]/.android/adbkey'...
adb F 12-05 17:28:30  1414 48466 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)
</code>```

Catalyst: Installing platform tools v27.0.0

Solutions Tried: Restarting Android Studio, Restarting computer, Manually starting ADB via terminal, deleting /Users/[username]/.android/adbkey and adbkey.pub, and reinstalling platform tools

Also I am not using genymotion, just the stock emulator.

答:
To add to the answer, here are some commands to quickly rollback on Macs. This was borrowed and tweaked from a helpful post in the bug tracker</p>

```<code>cd $ANDROID_HOME && rm -rf platform-tools/ && curl https://dl.google.com/android/repository/platform-tools_r26.0.2-darwin.zip -o platform-tools_r26.0.2-darwin.zip && unzip platform-tools_r26.0.2-darwin.zip
</code>```

Body:
Problem: adb start-server fails.

--- adb starting (pid 1414) ---
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Version 27.0.0-4455170
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Installed as /Users/[username]/Library/Android/sdk/platform-tools/adb
adb I 12-05 17:28:30  1414 48453 main.cpp:57]
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:416]
adb_auth_init...
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:174] read_key_file '/Users/[username]/.android/adbkey'...
adb F 12-05 17:28:30  1414 48466 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)

Catalyst: Installing platform tools v27.0.0

Solutions Tried: Restarting Android Studio, Restarting computer, Manually starting ADB via terminal, deleting /Users/[username]/.android/adbkey and adbkey.pub, and reinstalling platform tools

Also I am not using genymotion, just the stock emulator.

Body:
To add to the answer, here are some commands to quickly rollback on Macs. This was borrowed and tweaked from a helpful post in the bug tracker

cd $ANDROID_HOME && rm -rf platform-tools/ && curl https://dl.google.com/android/repository/platform-tools_r26.0.2-darwin.zip -o platform-tools_r26.0.2-darwin.zip && unzip platform-tools_r26.0.2-darwin.zip


问:
How am I supposed to write over an array given the number of times it has to be copied in Java
I am supposed to "multiply" an array for given number of times, using the int copy variable. However, I am stuck on "writing over the array" as arrays can not be modified, and copying the array a given amount of times. Clearer instructions can be found below. Thanks! :)

```<code>int[] arrayMultiplier(int[] arr, int copies)
This method should return an array generated by writing the array arr
several (copies) times in a row.
For example if the array nums = [3, 5, 6]:
arrayMultiplier(nums, 3)
would return the array [3, 5, 6, 3, 5, 6, 3, 5, 6]
</code>```

I should clarify that I found two other posts on how to do this, but they used C++ and Javascript instead of Java

答:
Try creating the array you want to return from the multiplier

```<code>int[] multiplied = new int[arr.length * copies];
</code>```

Then loop through  the new array and populate it.

```<code>for(int i = 0;i<=multiplied.length-1;i++){
   multiplied[i] = arr[i%copies];
}
</code>```

Body:
I am supposed to "multiply" an array for given number of times, using the int copy variable. However, I am stuck on "writing over the array" as arrays can not be modified, and copying the array a given amount of times. Clearer instructions can be found below. Thanks! :)

int[] arrayMultiplier(int[] arr, int copies)
This method should return an array generated by writing the array arr
several (copies) times in a row.
For example if the array nums = [3, 5, 6]:
arrayMultiplier(nums, 3)
would return the array [3, 5, 6, 3, 5, 6, 3, 5, 6]

I should clarify that I found two other posts on how to do this, but they used C++ and Javascript instead of Java

Body:
Try creating the array you want to return from the multiplier

int[] multiplied = new int[arr.length * copies];

Then loop through  the new array and populate it.

for(int i = 0;i<=multiplied.length-1;i++){
   multiplied[i] = arr[i%copies];
}


问:
‘Cordova/CDV.h’ file not found in Xcode 8.2.1
I have one hybrid Cordova project, which is running fine Xcode 5.1.1, but when I am trying to Archive the project in Xcode 8.2.1 with ‘Generic iOS Device’ I am getting the error ‘Cordova/CDV.h’ is not found.

I read many articles about this problem, but none could solve my problem. Most answers are telling to follow the below steps:

"Add this line to your Build Settings -> Header Search Paths:
$(OBJROOT)/UninstalledProducts/$(PLATFORM_NAME)/include
"

I have did this but problem not solved, getting another error ‘ld: library not found for -lcrt1.3.1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)’

Also I have changed the bitcode YES to NO in target Build Settings, but no fruitful result.

Project cordova version 3.4.0 where installed cordova version in machine 6.4.0

Has anybody experience with this kind of problem?
Please, can anyone help? I've been working on this for days.

答:
Seems like the "Cordova" folder isn't getting copied into the project during cordova platform add ios

So, you'll have to copy the "Cordova" source folder into your project manually. But you'll have to download the ios source packages from github first, which is located at:

https://github.com/apache/cordova-ios

After downloading the "cordova-ios-master.zip" package and unzipping it, copy the folder named "CordovaLib" into your project next to the Xcode project file:

```<code>PROJECT_FOLDER/platforms/ios/PROJECT_NAME
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcodeproj
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcworkspace
PROJECT_FOLDER/platforms/ios/cordova
PROJECT_FOLDER/platforms/ios/CordovaLib   <------- here
PROJECT_FOLDER/platforms/ios/ios.json
PROJECT_FOLDER/platforms/ios/platform_www
PROJECT_FOLDER/platforms/ios/pods-debug.xcconfig
PROJECT_FOLDER/platforms/ios/pods-release.xcconfig
PROJECT_FOLDER/platforms/ios/www
</code>```

Body:
Seems like the "Cordova" folder isn't getting copied into the project during cordova platform add ios

So, you'll have to copy the "Cordova" source folder into your project manually. But you'll have to download the ios source packages from github first, which is located at:

https://github.com/apache/cordova-ios

After downloading the "cordova-ios-master.zip" package and unzipping it, copy the folder named "CordovaLib" into your project next to the Xcode project file:

PROJECT_FOLDER/platforms/ios/PROJECT_NAME
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcodeproj
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcworkspace
PROJECT_FOLDER/platforms/ios/cordova
PROJECT_FOLDER/platforms/ios/CordovaLib   <------- here
PROJECT_FOLDER/platforms/ios/ios.json
PROJECT_FOLDER/platforms/ios/platform_www
PROJECT_FOLDER/platforms/ios/pods-debug.xcconfig
PROJECT_FOLDER/platforms/ios/pods-release.xcconfig
PROJECT_FOLDER/platforms/ios/www


问:
Java beginner: convert an image to a binary array
this is what I've gone so far and I can't seem to go further because I don't understand bitwise operations on the RGB

```<code>// Read from a file
File file = new File("src/a.gif");
image = ImageO.read(file);
int[] rgbarr = image.getRGB(0, 0, 13, 15, null, 0, 13);// image is 13*15
System.out.println(rgbarr.length);
for (int i : rgbarr)
    {
        System.out.println(i);
    }
</code>```

Output: was values such as -16777216 and -1 Because I've already made an image black and white just to ease my understanding

But in our case here let's suppose it would be just random image , how do I get from normal RGB image to binary values (0 or 1) for each pixel.

答: You already have RGB values in the int[], that is color of each pixel. You could compare this to a specific background color, like black, to get a 1-bit pixel value. Then maybe set a bit in another appropriately sized byte[] array...</p>

Body:
this is what I've gone so far and I can't seem to go further because I don't understand bitwise operations on the RGB

// Read from a file
File file = new File("src/a.gif");
image = ImageO.read(file);
int[] rgbarr = image.getRGB(0, 0, 13, 15, null, 0, 13);// image is 13*15
System.out.println(rgbarr.length);
for (int i : rgbarr)
    {
        System.out.println(i);
    }

Output: was values such as -16777216 and -1 Because I've already made an image black and white just to ease my understanding

But in our case here let's suppose it would be just random image , how do I get from normal RGB image to binary values (0 or 1) for each pixel.


问:
Query with GROUP BY and ORDER BY not working when multiple columns in SELECT are chosen
I'm updating an old website and one of the queries isn't working anymore:

```<code>SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

```<code>SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2
</code>```

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

```<code>SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

```<code>SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

```<code>Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by
</code>```

答:
First of all, when query() returns false, you should find out what the error was. You seem to be using PDO, so I will direct you to this page: http://php.net/manual/en/pdo.error-handling.php

TL;DR - you should enable PDO exceptions, or else you need to write code to check the result of every call to query(), prepare(), and execute() to see if an error occurred. And if so, use errorInfo() to find out the actual error. Doing anything else is flying blind!

Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
  clause and contains nonaggregated column 'webvictoria.cats_oct.matchLink'
  which is not functionally dependent on columns in GROUP BY clause; this is
  incompatible with sql_mode=only_full_group_by

This is a common issue. See dozens of questions tagged mysql-error-1055.

I guess you just upgraded to MySQL 5.7. MySQL 5.7 enabled strict mode by default, so I guess you just upgraded. Prior to MySQL 5.6, strict mode was optional and not enabled by default.

See: https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

You can't write ambiguous queries. If you GROUP BY col2, which value in the group of rows of each group should be used for col1 and col3? It's ambiguous.

Without strict mode, MySQL chooses an arbitrary row from the group. With strict mode, it reverts to standard SQL behavior, and disallows the ambiguous query. This is how most other brands of SQL database behave, by the way.

To fix it, you must follow this rule: Every column in your select list must be one of:

A column in your GROUP BY clause

A column functionally dependent on the columns in your GROUP BY clause (so there can only be one value)

Used in an aggregate function like MIN(), MAX(), COUNT(), SUM(), AVG(), or GROUP_CONCAT()

Some people choose to disable strict mode in MySQL 5.7 for the sake of "getting the code working again." But it isn't working—it's just giving ambiguous results like it did before MySQL 5.7.

It's better to fix the logic of your queries.

Body:
I'm updating an old website and one of the queries isn't working anymore:

SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by


问:
Fibonacci C++ return Error
I wanted to create a function which prints out the fib numbers. But i can´t fix this error. Next allways stays the same from the initialisation. I´m a very beginner of Cpp.

```<code>#include "stdafx.h"
#include <math.h>
#include <iostream>

int fib(int &n)
{
    int first = 0, second = 1, next{};

    for (int i = 0; i <= n; i++) {
        if (i <= 1) {
            int next = i;

        }

        else
        {
            int next = first + second;
            first = second;
            second = next;

        }
        std::cout << next << std::endl;
    }
return next;
}

int main()

{

    int stelle;

    std::cout << "Bitte geben Sie die Stelle der Fibonacci Folge ein die Sie erhalten möchten" << std::endl;
    std::cin >> stelle;
    fib(stelle);

    std::cout << "Tastedrücken zum Beenden";
    int var;
    std::cin >> var;

    return 0;
}
</code>```

Thanks for help

答:
Your code makes me think that there is lack of clarity in how to translate the math to code.

You can implement it using an iterative logic or recursive logic.

In either case, there are two running numbers that you have to deal with.

Let's say you start with the 0 and 1 as the starting numbers.

In the next iteration, they need to be 1 and 1.

In the next iteration, they need to be 1 and 2.

In the next iteration, they need to be 2 and 3.

In the next iteration, they need to be 3 and 5.

etc.

At the end of the iteration (or recursion), the second number from that pair is the final Fibonacci number.

Here's one such implementation.

```<code>int fib(int n)
{
   if ( n == 0 )
   {
      return 0;
   }

   int ans1 = 0;
   int ans2 = 1;
   for (int i = 1; i < n; ++i )
   {
      int temp = ans2;
      ans2 = ans1 + ans2;
      ans1 = temp;
   }
   return ans2;
}
</code>```

A working program:

```<code>#include <iostream>

int fib(int n)
{
   if ( n == 0 )
   {
      return 0;
   }

   int ans1 = 0;
   int ans2 = 1;
   for (int i = 1; i < n; ++i )
   {
      int temp = ans2;
      ans2 = ans1 + ans2;
      ans1 = temp;
   }
   return ans2;
}

int main()
{
   int stelle;

   std::cout << "Bitte geben Sie die Stelle der Fibonacci Folge ein die Sie erhalten möchten" << std::endl;
   std::cin >> stelle;
   for ( int i = 1; i < stelle; ++i )
   {
      std::cout << "fib(" << i << "): " << fib(i) << std::endl;
   }

   return 0;
}
</code>```

The output of the program when the input is 20:

Bitte geben Sie die Stelle der Fibonacci Folge ein die Sie erhalten m▒chten
fib(1): 1
fib(2): 1
fib(3): 2
fib(4): 3
fib(5): 5
fib(6): 8
fib(7): 13
fib(8): 21
fib(9): 34
fib(10): 55
fib(11): 89
fib(12): 144
fib(13): 233
fib(14): 377
fib(15): 610
fib(16): 987
fib(17): 1597
fib(18): 2584
fib(19): 4181
```

Title: Fibonacci C++ return Error

Body:
I wanted to create a function which prints out the fib numbers. But i can´t fix this error. Next allways stays the same from the initialisation. I´m a very beginner of Cpp.

#include "stdafx.h"
#include <math.h>
#include <iostream>

int fib(int &n)
{
    int first = 0, second = 1, next{};

    for (int i = 0; i <= n; i++) {
        if (i <= 1) {
            int next = i;

        }

        else
        {
            int next = first + second;
            first = second;
            second = next;

        }
        std::cout << next << std::endl;
    }
return next;
}

int main()

{

    int stelle;

    std::cout << "Bitte geben Sie die Stelle der Fibonacci Folge ein die Sie erhalten möchten" << std::endl;
    std::cin >> stelle;
    fib(stelle);

    std::cout << "Tastedrücken zum Beenden";
    int var;
    std::cin >> var;

    return 0;
}

Thanks for help

Body:
Your code makes me think that there is lack of clarity in how to translate the math to code.

You can implement it using an iterative logic or recursive logic.

In either case, there are two running numbers that you have to deal with.

Let's say you start with the 0 and 1 as the starting numbers.

In the next iteration, they need to be 1 and 1.

In the next iteration, they need to be 1 and 2.

In the next iteration, they need to be 2 and 3.

In the next iteration, they need to be 3 and 5.

etc.

At the end of the iteration (or recursion), the second number from that pair is the final Fibonacci number.

Here's one such implementation.

int fib(int n)
{
   if ( n == 0 )
   {
      return 0;
   }

   int ans1 = 0;
   int ans2 = 1;
   for (int i = 1; i < n; ++i )
   {
      int temp = ans2;
      ans2 = ans1 + ans2;
      ans1 = temp;
   }
   return ans2;
}

A working program:

#include <iostream>

int fib(int n)
{
   if ( n == 0 )
   {
      return 0;
   }

   int ans1 = 0;
   int ans2 = 1;
   for (int i = 1; i < n; ++i )
   {
      int temp = ans2;
      ans2 = ans1 + ans2;
      ans1 = temp;
   }
   return ans2;
}

int main()
{
   int stelle;

   std::cout << "Bitte geben Sie die Stelle der Fibonacci Folge ein die Sie erhalten möchten" << std::endl;
   std::cin >> stelle;
   for ( int i = 1; i < stelle; ++i )
   {
      std::cout << "fib(" << i << "): " << fib(i) << std::endl;
   }

   return 0;
}

The output of the program when the input is 20:

Bitte geben Sie die Stelle der Fibonacci Folge ein die Sie erhalten m▒chten
fib(1): 1
fib(2): 1
fib(3): 2
fib(4): 3
fib(5): 5
fib(6): 8
fib(7): 13
fib(8): 21
fib(9): 34
fib(10): 55
fib(11): 89
fib(12): 144
fib(13): 233
fib(14): 377
fib(15): 610
fib(16): 987
fib(17): 1597
fib(18): 2584
fib(19): 4181


问:
Get TimeZone offset value from TimeZone without TimeZone name
I need to save the phone's timezone in the format [+/-]hh:mm

I am using TimeZone class to deal with this, but the only format I can get is the following:

```<code>PST -05:00
GMT +02:00
</code>```

I would rather not substring the result, is there any key or option flag I can set to only get the value and not the name of that timezone (GMT/CET/PST...)?

答:
With Java 8 now, you can use:

```<code>Integer offset  = ZonedDateTime.now().getOffset().getTotalSeconds();
</code>```

to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case.

Example: https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html

Body:
I need to save the phone's timezone in the format [+/-]hh:mm

I am using TimeZone class to deal with this, but the only format I can get is the following:

PST -05:00
GMT +02:00

I would rather not substring the result, is there any key or option flag I can set to only get the value and not the name of that timezone (GMT/CET/PST...)?

Body:
With Java 8 now, you can use:

Integer offset  = ZonedDateTime.now().getOffset().getTotalSeconds();

to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case.

Example: https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html


问:
Geopackage: convert BLOB to coordinates
I'm working with SQLite-Mananger Plugin for FireFox to edit my local geopackage database.

The geometry is stored as BLOB in various tables.
Now I'd like to encode the not readable BLOB format into human readable coordinates.

I already tried it that way:

```<code>Select STAsText(geometry) as geometry from table;
</code>```

With the following error:

```<code>no such function: STAsText
</code>```

I guess because it is a local database and the STAsText-function is for SQL-Sever.

I also tried it with:

```<code>SELECT quote(geometry) FROM table
</code>```

But with this I also get no coordinates.

答:
just use GDAL OGR2OGR "ogr2ogr -f "GeoJSON"  path/filename.geojson path/filename.gpkg"

Or use QGIS Desktop.   GeoPackage uses a derivation of WKB -Well Known Binary for it's Vector Features BLOB.  Conversion to GeoJSON is very straight forward. You can also use GeoPackage-JS to do the conversion.
Click Open Geopackage and it will allow you to download as GeoJSON http://ngageoint.github.io/geopackage-js/

Title: Geopackage: convert BLOB to coordinates

Body:
I'm working with SQLite-Mananger Plugin for FireFox to edit my local geopackage database.

The geometry is stored as BLOB in various tables.
Now I'd like to encode the not readable BLOB format into human readable coordinates.

I already tried it that way:

Select STAsText(geometry) as geometry from table;

With the following error:

no such function: STAsText

I guess because it is a local database and the STAsText-function is for SQL-Sever.

I also tried it with:

SELECT quote(geometry) FROM table

But with this I also get no coordinates.


答:
I'm betting that each int in the array is a packed ARGB value;

```<code>boolean [] output = new boolean[rgbarr.length];
for ( int i=0; i<rgbarr.length; ++i ) {
  int a = (rgbarr[i] >> 24 ) & 0x0FF;
  int r = (rgbarr[i] >> 16 ) & 0x0FF;
  int g = (rgbarr[i] >> 8  ) & 0x0FF;
  int b = (rgbarr[i]       ) & 0x0FF;
  output[i] = (0.30*r + 0.59*g + 0.11*b) > 127;
}
</code>```

The output equation I choose was taken from a definition of Luminance from wikipedia. You can change the scales so long as the coefficients add up to 1.

Title: Java beginner: convert an image to a binary array

Body:
I'm betting that each int in the array is a packed ARGB value;

boolean [] output = new boolean[rgbarr.length];
for ( int i=0; i<rgbarr.length; ++i ) {
  int a = (rgbarr[i] >> 24 ) & 0x0FF;
  int r = (rgbarr[i] >> 16 ) & 0x0FF;
  int g = (rgbarr[i] >> 8  ) & 0x0FF;
  int b = (rgbarr[i]       ) & 0x0FF;
  output[i] = (0.30*r + 0.59*g + 0.11*b) > 127;
}

The output equation I choose was taken from a definition of Luminance from wikipedia. You can change the scales so long as the coefficients add up to 1.


问:
How to mock a service in a test file that is being called in OnInit of the component being tested?
In AutoReceptionistRecommendation.component.ts

I have an ngOninit method that looks like this:

```<code>  ngOnInit() {
    this.city = this.employee.getEmpData().city;
  }
</code>```

In the test file AutoReceptionistRecommendation.component.spec.ts

I have code that looks like this:

```<code>describe('AutoReceptionistRecommendationComponent', () => {
  let component: AutoReceptionistRecommendationComponent;
  let fixture: ComponentFixture<AutoReceptionistRecommendationComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AutoReceptionistRecommendationComponent ],
      imports: [
        FormsModule,
        MatCardModule,
        MatIconModule,
        HttpModule
      ],
      providers: [
        EmployeeService,
        EmployeeHttpService
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AutoReceptionistRecommendationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

When I run ng test I get an error that looks like this:

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest':
  Failed to load
  'ng:///DynamicTestModule/AutoReceptionistRecommendationComponent_Host.ngfactory.js'.

If I remove the line in NgOnInit this error does not occur, and the test continues. I think that I have to mock this service somehow in order for the test to go through. What is the best way to do that, can somebody provide documentation that explains how to do this? Or give me insight as to why this error occurs with the line in ngOninit and does not occur when it is not there?

答:
Efficient unit testing requires to isolate currently tested unit from other moving parts.

Real HttpModule shouldn't be used in unit tests. The requests should be mocked with MockBackend when testing the units that use Http directly. Otherwise these units should be mocked, like:

```<code>providers: [
  ...
  { provide: EmployeeService, useValue: jasmine.createSpyObj('', ['getEmpData']) }
]
</code>```

Component ngOnInit is called on first detectChanges call. This means that employee.getEmpData should be mocked beforehand:

```<code>component = fixture.componentInstance;
employee.getEmpData.and.returnValue({ city: ... });
fixture.detectChanges();
</code>```

Body:
In AutoReceptionistRecommendation.component.ts

I have an ngOninit method that looks like this:

  ngOnInit() {
    this.city = this.employee.getEmpData().city;
  }

In the test file AutoReceptionistRecommendation.component.spec.ts

I have code that looks like this:

describe('AutoReceptionistRecommendationComponent', () => {
  let component: AutoReceptionistRecommendationComponent;
  let fixture: ComponentFixture<AutoReceptionistRecommendationComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AutoReceptionistRecommendationComponent ],
      imports: [
        FormsModule,
        MatCardModule,
        MatIconModule,
        HttpModule
      ],
      providers: [
        EmployeeService,
        EmployeeHttpService
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AutoReceptionistRecommendationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});

When I run ng test I get an error that looks like this:

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest':
  Failed to load
  'ng:///DynamicTestModule/AutoReceptionistRecommendationComponent_Host.ngfactory.js'.

If I remove the line in NgOnInit this error does not occur, and the test continues. I think that I have to mock this service somehow in order for the test to go through. What is the best way to do that, can somebody provide documentation that explains how to do this? Or give me insight as to why this error occurs with the line in ngOninit and does not occur when it is not there?

Body:
Efficient unit testing requires to isolate currently tested unit from other moving parts.

Real HttpModule shouldn't be used in unit tests. The requests should be mocked with MockBackend when testing the units that use Http directly. Otherwise these units should be mocked, like:

providers: [
  ...
  { provide: EmployeeService, useValue: jasmine.createSpyObj('', ['getEmpData']) }
]

Component ngOnInit is called on first detectChanges call. This means that employee.getEmpData should be mocked beforehand:

component = fixture.componentInstance;
employee.getEmpData.and.returnValue({ city: ... });
fixture.detectChanges();


问:
Catch MySQL error when record does not exist in NodeJS
I am trying to figure out how I can catch an error when a requested id is not found in the Database records.

My code is:

```<code>router.get('/users/:id', function(req, res) {

    getId = req.params.id

    db.con.query('SELECT * FROM employees where id=?', getId, function(err, results) {

       if (err) {
            console.log('error in query')
            return

        } else {
            obj = {
                id: results[0].id,
                name: results[0].name,
                location: results[0].location
                // error should be cached here when a requested results[0].id is not found
            }
            res.render('showuser');
        }
    })

});
</code>```

In the console, I get the following error when a non-existed id is requested as it should be, however I cannot catch this error programmatically.

```<code>throw err; // Rethrow non-MySQL errors
^
ReferenceError: id is not defined
at Query._callback (C:\NodeJS\CRUD\CRUD-4\routes\add.js:21:13)
</code>```

Node: v8.8.0

Express: v4.15.5

答:
Try this:

```<code>try{
  obj = {
     id: results[0].id,
     name: results[0].name,
     location: results[0].location
  }
}catch(err){
  //handle error
}
</code>```

try {...}catch... is how you handle exceptions in JavaScript. You can read more about it here.

Body:
I am trying to figure out how I can catch an error when a requested id is not found in the Database records.

My code is:

router.get('/users/:id', function(req, res) {

    getId = req.params.id

    db.con.query('SELECT * FROM employees where id=?', getId, function(err, results) {

       if (err) {
            console.log('error in query')
            return

        } else {
            obj = {
                id: results[0].id,
                name: results[0].name,
                location: results[0].location
                // error should be cached here when a requested results[0].id is not found
            }
            res.render('showuser');
        }
    })

});

In the console, I get the following error when a non-existed id is requested as it should be, however I cannot catch this error programmatically.

throw err; // Rethrow non-MySQL errors
^
ReferenceError: id is not defined
at Query._callback (C:\NodeJS\CRUD\CRUD-4\routes\add.js:21:13)

Node: v8.8.0

Express: v4.15.5

Body:
Try this:

try{
  obj = {
     id: results[0].id,
     name: results[0].name,
     location: results[0].location
  }
}catch(err){
  //handle error
}

try {...}catch... is how you handle exceptions in JavaScript. You can read more about it here.


问:
Name convention on Java Swing components(prefix)
An question that was brought to my mind when programming with Swing in Java was, is it a recommendation or an "official"/most used naming convention(prefix) on Swing components.

Such as(even though other may prefer other naming conventions this is what I am currently using):

txt for JTextField

btn for JButton

lbl for JLabel

pnl for JPanel

But then my list ends..

I think such prefixes enhance the readability in my code so, but I do not have any names for components such as JComboBox, JList, JRadioButton, JCheckButton and so the list goes on.

Thanks in advance.

答:
I usually hate this sort of thing, because it smacks of Hungarian notation.  I don't like the idea of embedding the type in the name of the variable, because if you change types it shouldn't mandate changing all the variable names.

But in the case of Swing, I guess it's acceptable.

A good IDE will generate variable names for you.  Why not let it?  I'd also just spell out the type if you insist (e.g. submitButton instead of btnSubmit).  Keystrokes are cheap.


问:
error 'Cordova/CDVViewController.h' file not found Xcode 9
i have some error after building ionic app iOS version and when open it with Xcode 9 i got error 'Cordova/CDVViewController.h' file not found i didn't understand why in fact this is first time i got this error</p>

答:
Same was happening for me. The following allowed the project to build:

The "Cordova" folder isn't getting copied into the project during cordova platform add ios.

So, you'll have to copy the "Cordova" source folder into your project manually. But you'll have to download the ios source packages from github first, which is located at:

https://github.com/apache/cordova-ios

After downloading the "cordova-ios-master.zip" package and unzipping it, copy the folder named "CordovaLib" into your project next to the Xcode project file:

```<code>PROJECT_FOLDER/platforms/ios/PROJECT_NAME
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcodeproj
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcworkspace
PROJECT_FOLDER/platforms/ios/cordova
PROJECT_FOLDER/platforms/ios/CordovaLib   <------- here
PROJECT_FOLDER/platforms/ios/ios.json
PROJECT_FOLDER/platforms/ios/platform_www
PROJECT_FOLDER/platforms/ios/pods-debug.xcconfig
PROJECT_FOLDER/platforms/ios/pods-release.xcconfig
PROJECT_FOLDER/platforms/ios/www
</code>```

Body:
Same was happening for me. The following allowed the project to build:

The "Cordova" folder isn't getting copied into the project during cordova platform add ios.

So, you'll have to copy the "Cordova" source folder into your project manually. But you'll have to download the ios source packages from github first, which is located at:

https://github.com/apache/cordova-ios

After downloading the "cordova-ios-master.zip" package and unzipping it, copy the folder named "CordovaLib" into your project next to the Xcode project file:

PROJECT_FOLDER/platforms/ios/PROJECT_NAME
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcodeproj
PROJECT_FOLDER/platforms/ios/PROJECT_NAME.xcworkspace
PROJECT_FOLDER/platforms/ios/cordova
PROJECT_FOLDER/platforms/ios/CordovaLib   <------- here
PROJECT_FOLDER/platforms/ios/ios.json
PROJECT_FOLDER/platforms/ios/platform_www
PROJECT_FOLDER/platforms/ios/pods-debug.xcconfig
PROJECT_FOLDER/platforms/ios/pods-release.xcconfig
PROJECT_FOLDER/platforms/ios/www


问:
Unable to send object in Express response
I'm trying to send all the data from my database back using res.send, but it's throwing me an error. On my frontend, I'm calling the endpoint select and trying to return all rows and data within the database.

```<code>app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];
      res.send(row);
    }
  })
});
</code>```

答:
You should use res.write instead of res.send as the latter terminates the function (nothing after the first use of res.send is executed)

```<code>app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];
      res.write(row);
    }
    res.end(); //this finally sends the response
  })
});
</code>```

Or if you want to use res.send send the whole rows array:

```<code>app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    res.send(rows);
  })
});
</code>```

Body:
I'm trying to send all the data from my database back using res.send, but it's throwing me an error. On my frontend, I'm calling the endpoint select and trying to return all rows and data within the database.

app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];
      res.send(row);
    }
  })
});

Body:
You should use res.write instead of res.send as the latter terminates the function (nothing after the first use of res.send is executed)

app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];
      res.write(row);
    }
    res.end(); //this finally sends the response
  })
});

Or if you want to use res.send send the whole rows array:

app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    res.send(rows);
  })
});