问:
C++: Dynamically loading classes from dlls
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

```<code>//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};
</code>```

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

```<code>//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }
</code>```

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

答:
Easiest way to do this, IMHO, is to have a simple C function that returns a pointer to an interface described elsewhere. Then your app, can call all of the functions of that interface, without actually knowing what class it is using.

Edit: Here's a simple example.

In your main app code, you create a header for the interface:

```<code>class IModule
{
public:
    virtual ~IModule(); // <= important!
    virtual void doStuff() = 0;
};
</code>```

Main app is coded to use the interface above, without any details on the actual implementation of the interface.

```<code>class ActualModule: public IModule
{
/* implementation */
};
</code>```

Now, the modules - the DLL's have the actual implementations of that interface, and those classes don't even have to be exported - __declspec (dllexport) isn't needed. The only requirement for the modules is to export a single function, that would create and return an implementation of the interface:

```<code>__declspec (dllexport) IModule* CreateModule()
{
    // call the constructor of the actual implementation
    IModule * module = new ActualModule();
    // return the created function
    return module;
}
</code>```

note: error checking left out - you'd usually want to check, if new returned the correct pointer and you should protect yourself from the exceptions that might be thrown in the constructor of the ActualModule class.

Then, in your main app, all you need is to simply load the module (LoadLibrary function) and find the function CreateModule (GetProcAddr function). Then, you use the class through the interface.

Edit 2: your RefCount (base class of the interface), can be implemented in (and exported from) the main app. Then all your module would need to link to the lib file of the main app (yes! EXE files can have LIB files just like DLL files!) And that should be enough.

OwnerDisplayName: Fire Lancer

Body:
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

LastEditorDisplayName: Fire Lancer

Body:
Easiest way to do this, IMHO, is to have a simple C function that returns a pointer to an interface described elsewhere. Then your app, can call all of the functions of that interface, without actually knowing what class it is using.

Edit: Here's a simple example.

In your main app code, you create a header for the interface:

class IModule
{
public:
    virtual ~IModule(); // <= important!
    virtual void doStuff() = 0;
};

Main app is coded to use the interface above, without any details on the actual implementation of the interface.

class ActualModule: public IModule
{
/* implementation */
};

Now, the modules - the DLL's have the actual implementations of that interface, and those classes don't even have to be exported - __declspec (dllexport) isn't needed. The only requirement for the modules is to export a single function, that would create and return an implementation of the interface:

__declspec (dllexport) IModule* CreateModule()
{
    // call the constructor of the actual implementation
    IModule * module = new ActualModule();
    // return the created function
    return module;
}

note: error checking left out - you'd usually want to check, if new returned the correct pointer and you should protect yourself from the exceptions that might be thrown in the constructor of the ActualModule class.

Then, in your main app, all you need is to simply load the module (LoadLibrary function) and find the function CreateModule (GetProcAddr function). Then, you use the class through the interface.

Edit 2: your RefCount (base class of the interface), can be implemented in (and exported from) the main app. Then all your module would need to link to the lib file of the main app (yes! EXE files can have LIB files just like DLL files!) And that should be enough.

OwnerDisplayName: Paulius Maruška

LastEditorDisplayName: Paulius Maruška


来源: stackexchange

问:
How to install Python using source files to a custom directory
I want to build Python 2.7.1 additionally to the one the redhat server already has pre-installed.

What options do I need to modify/use so that Python can be built under i.e. /opt/Python27

I would appreciate any help!

答:
Configure with:

./configure --prefix=/opt/Python27

In general, you can just do ./configure --help to get a list of all the options you're allowed to set for that configure script.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Phone doesn't show my application to open txt-files
I'm quite new to android programming and I'm also not the best programmer and the following code should work based on my knowledge... So, that's the issue:
I want my application to be shown as an option for opening a txt-file on my phone. That's why I created a broadcast receiver, which is specified in my manifest like this:

```<code><receiver android:name="MyBroadcastReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_VIEW"/>
                <action android:name="android.intent.action.ACTION_EDIT"/>
                <action android:name="android.intent.action.ACTION_PICK"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>

                <data android:scheme="file"/>
                <data android:mimeType="text/plain"/>
                <data android:pathPattern=".*\\.txt"/>
                <data android:host="*"/>
            </intent-filter>
        </receiver>
</code>```

And my broadcastreceiver class looks like this:

```<code>public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intentNoteActivity = new Intent(context, NoteActivity.class);
        intentNoteActivity.putExtra("URI", intent.getData());
        context.startActivity(intentNoteActivity);
    }
}
</code>```

But if I try to open a txt-file on my phone on where the application is installed it does not show my application. What did I do wrong?

答:
That's why I created a broadcast receiver

A BroadcastReceiver is not used to open documents this way. An Activity does that.

But if I try to open a txt-file on my phone on where the application is installed it does not show my application.

That is because other apps will use startActivity(), not sendBroadcast(), with ACTION_VIEW Intents.

Create an activity and use your <intent-filter> with it. It should work with a few apps, though not very many. Eliminating <data android:pathPattern=".*\\.txt"/> and <data android:host="*"/>, and adding <data android:scheme="content"/>, will help increase compatibility.

Body:
I'm quite new to android programming and I'm also not the best programmer and the following code should work based on my knowledge... So, that's the issue:
I want my application to be shown as an option for opening a txt-file on my phone. That's why I created a broadcast receiver, which is specified in my manifest like this:

<receiver android:name="MyBroadcastReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_VIEW"/>
                <action android:name="android.intent.action.ACTION_EDIT"/>
                <action android:name="android.intent.action.ACTION_PICK"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>

                <data android:scheme="file"/>
                <data android:mimeType="text/plain"/>
                <data android:pathPattern=".*\\.txt"/>
                <data android:host="*"/>
            </intent-filter>
        </receiver>

And my broadcastreceiver class looks like this:

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intentNoteActivity = new Intent(context, NoteActivity.class);
        intentNoteActivity.putExtra("URI", intent.getData());
        context.startActivity(intentNoteActivity);
    }
}

But if I try to open a txt-file on my phone on where the application is installed it does not show my application. What did I do wrong?


问:
 Anchor remains in URL and in page after refreshing
I have this little issue here with my page, where if I reload it while being anchored, the anchor remains and there is a problem to it. I.E

```<code>http://localhost/public/product/1#mod1
</code>```

The anchor is #mod1, and while the anchor remains active after refresh, my CSS code is saying that this element:

```<code>.overlay:target
</code>```

is active. Which is a very big issue, because then it doesn't allow me to explore the functionallity I have implemented on this anchor, unless I remove the #mod1 from the end of the page manually by hand. Because this CSS element makes this div visible when it should be not unless activated with the a href element.

```<code><a href="#mod{{$key}}" class="button">(?)</a>
<div id="mod{{$key}}" class="overlay">
    content
</div>
</code>```

Any ideas on how could I solve it? I tried catching whether the user has refreshed the page and redirecting him to an action/route/url, but the page stays blank then and URL unchanged.

答:
Well I wanted to purely solve this without JS, but here's what I did, HTML:

```<code><a ng-href="mod{{$key}}" class="button">(?)</a>
<div id="mod{{$key}}" class="overlay">
</code>```

Then replaced the CSS of overlay:target to -> overlay:active, and implemented JS:

```<code>var curmod;
$('a.button').on('click', function(e)
{
    curmod = document.getElementById($(this).attr('ng-href'));
    $(curmod).addClass('active');
});
$('.popup a.close').on('click', function(e)
{
    $(curmod).removeClass('active');
    curmod = null;
});
</code>```

Title: <a href> Anchor remains in URL and in page after refreshing

Body:
I have this little issue here with my page, where if I reload it while being anchored, the anchor remains and there is a problem to it. I.E

http://localhost/public/product/1#mod1

The anchor is #mod1, and while the anchor remains active after refresh, my CSS code is saying that this element:

.overlay:target

is active. Which is a very big issue, because then it doesn't allow me to explore the functionallity I have implemented on this anchor, unless I remove the #mod1 from the end of the page manually by hand. Because this CSS element makes this div visible when it should be not unless activated with the a href element.

(?)

    content

Any ideas on how could I solve it? I tried catching whether the user has refreshed the page and redirecting him to an action/route/url, but the page stays blank then and URL unchanged.

Body:
Well I wanted to purely solve this without JS, but here's what I did, HTML:

<a ng-href="mod{{$key}}" class="button">(?)</a>
<div id="mod{{$key}}" class="overlay">

Then replaced the CSS of overlay:target to -> overlay:active, and implemented JS:

var curmod;
$('a.button').on('click', function(e)
{
    curmod = document.getElementById($(this).attr('ng-href'));
    $(curmod).addClass('active');
});
$('.popup a.close').on('click', function(e)
{
    $(curmod).removeClass('active');
    curmod = null;
});


问:
Multi line graph with ordinal x-axis
I used the code below to make a multiple line graph in d3 with a linear x-axis and it works just fine. Now I want to make the x-axis ordinal, but I have no clue how to do this. Any help would be amazing!

Code:

```<code><!DOCTYPE html>
<html>
  <body>
    <center><h1>ZNF expression DFC</h1></center>
    <meta charset="utf-8">
    <style>

    .axis--x path {
      display: none;
    }

    .line {
      fill: none;
      stroke: steelblue;
      stroke-width: 3.0px;
    }

    div.tooltip {
        position: absolute;
        text-align: center;
        width: 60px;
        height: 18px;
        padding: 2px;
        font: 12px sans-serif;
        background: lightsteelblue;
        border: 0px;
        border-radius: 8px;
        pointer-events: none;
    }

    </style>
    <svg width="1560" height="1000"></svg>
    <script src="//d3js.org/d3.v4.min.js"></script>
    <script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
    <script>

    var svg = d3.select("svg"),
        margin = {top: 20, right: 80, bottom: 30, left: 50},
        width = svg.attr("width") - margin.left - margin.right,
        height = svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var x = d3.scaleLinear().range([0, width]),
        y = d3.scaleLinear().range([height, 0]),
        z = d3.scaleOrdinal(d3.schemeCategory20);

    // Define the div for the tooltip
    var div = d3.select("body").append("div")
        .attr("class", "tooltip")
        .style("opacity", 0);

    var line = d3.line()
        .x(function(d) { return x(d.Age); })
        .y(function(d) { return y(d.expression); });

    d3.csv("expression_ZNF_ages.csv", function(error, data) {
      if (error) throw error;

      var znfs = data.columns.slice(1).map(function(id) {
        return {
          id: id,
          values: data.map(function(d) {
            return {Age: d.Age, expression: d[id]};
          })
        };
      });

      x.domain([0, data.length]).range([0, width]);
      y.domain([0, 40]).range([height,0]);
      z.domain(znfs.map(function(c) { return c.id; }));

      g.append("g")
          .attr("class", "axis axis--x")
          .attr("transform", "translate(0," + height + ")")
          .call(d3.axisBottom(x));

      g.append("g")
          .attr("class", "axis axis--y")
          .call(d3.axisLeft(y))
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", "0.71em")
          .attr("fill", "#000")
          .text("expression"  );

      var city = g.selectAll(".city")
        .data(znfs)
        .enter().append("g")
          .attr("class", "city");

      city.append("path")
          .attr("class", "line")
          .attr("d", function(d) { return line(d.values); })
          .style("stroke", function(d) { return z(d.id); })
          .on("mouseover", function(d) {
                div.transition()
                    .duration(200)
                    .style("opacity", .9);
                div .html(d.id)
                    .style("left", (d3.event.pageX) + "px")
                    .style("top", (d3.event.pageY - 28) + "px");
                })
            .on("mouseout", function(d) {
                div.transition()
                    .duration(500)
                    .style("opacity", 0);
            });
    });

    </script>
  </body>
</html>
</code>```

The data with which I want to work is a csv file and looks like this:

Age, ZNF8, ZNF18, ZNF136, ZNF140 .... ZNF778,

"8pwc", 13.654, 12.643, 10.593, 8,124, .... 9.900,

"9pwc", 4.364, 1.004, 3.576, 0.032, .... 5.512,

"2yrs", 65.345, 53.278, 33.001, 68.844, .... 54.544,

....

Thank you!

答:
In this particular case, you have to use a point scale, which is a type of ordinal scale:

Point scales are a variant of band scales with the bandwidth fixed to zero. Point scales are typically used for scatterplots with an ordinal or categorical dimension.

A point scale will allow you to map a categorical (qualitative) variable to a continuous numeric output.

Thus, your scale should be:

```<code>var x = d3.scalePoint().range([0, width])
</code>```

And its domain should be defined with a map:

```<code>x.domain(data.map(d=>d.Age));
</code>```

Here is the working code: https://plnkr.co/edit/2nOLP5fEIHbs2U8OQB2y?p=preview

Title: Multi line graph with ordinal x-axis

Body:
I used the code below to make a multiple line graph in d3 with a linear x-axis and it works just fine. Now I want to make the x-axis ordinal, but I have no clue how to do this. Any help would be amazing!

Code:

<!DOCTYPE html>

ZNF expression DFC

    <meta charset="utf-8">

    <svg width="1560" height="1000"></svg>

The data with which I want to work is a csv file and looks like this:

Age, ZNF8, ZNF18, ZNF136, ZNF140 .... ZNF778,

"8pwc", 13.654, 12.643, 10.593, 8,124, .... 9.900,

"9pwc", 4.364, 1.004, 3.576, 0.032, .... 5.512,

"2yrs", 65.345, 53.278, 33.001, 68.844, .... 54.544,

....

Thank you!

Body:
In this particular case, you have to use a point scale, which is a type of ordinal scale:

Point scales are a variant of band scales with the bandwidth fixed to zero. Point scales are typically used for scatterplots with an ordinal or categorical dimension.

A point scale will allow you to map a categorical (qualitative) variable to a continuous numeric output.

Thus, your scale should be:

var x = d3.scalePoint().range([0, width])

And its domain should be defined with a map:

x.domain(data.map(d=>d.Age));

Here is the working code: https://plnkr.co/edit/2nOLP5fEIHbs2U8OQB2y?p=preview


问:
getSupportActionBar from inside of Fragment ActionBarCompat
I'm starting a new project that uses the AppCompat/ActionBarCompat in v7 support library. I'm trying to figure out how to use the getSupportActionBar from within a fragment. My activity that hosts the fragment extends ActionBarActivity, but I don't see a similar support class for Fragments.

From within my fragment

```<code>    public class CrimeFragment extends Fragment {
          //...

          getActivity().getSupportActionBar().setSubtitle(R.string.subtitle); // getSupportActionBar is not defined in the v4 version of Fragment

          //...
    }
</code>```

The google page for using it (http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html) says there should be no changes for the v4 fragment. Do I need to cast all my getActivity() calls to an ActionBarActivity? That seems like poor design.

答:
As an updated answer for Pierre-Antoine LaFayette's answer

ActionBarActivity is deprecated; use AppCompatActivity instead

```<code>((AppCompatActivity)getActivity()).getSupportActionBar();
</code>```

Body:
I'm starting a new project that uses the AppCompat/ActionBarCompat in v7 support library. I'm trying to figure out how to use the getSupportActionBar from within a fragment. My activity that hosts the fragment extends ActionBarActivity, but I don't see a similar support class for Fragments.

From within my fragment

    public class CrimeFragment extends Fragment {
          //...

          getActivity().getSupportActionBar().setSubtitle(R.string.subtitle); // getSupportActionBar is not defined in the v4 version of Fragment

          //...
    }

The google page for using it (http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html) says there should be no changes for the v4 fragment. Do I need to cast all my getActivity() calls to an ActionBarActivity? That seems like poor design.

Body:
As an updated answer for Pierre-Antoine LaFayette's answer

ActionBarActivity is deprecated; use AppCompatActivity instead

((AppCompatActivity)getActivity()).getSupportActionBar();


问:
spring mvc(rest) with angular2 causing 302 moved temporarily
We have simple spring mvc(rest), security and Angular2 app which is deployed in weblogic 12.1.2 Everything is packaged as single war file including dist folder of angular2 app. When app launched by index.html, it is requesting multiple Angular2 generated js files.

Randomly we are getting  302 moved temporarily status code on this request and that causing app to not launched successfully.

Does anyone know what might be causing this error? Or to be specific how should be handle 302 on server side if it has to be?

答: It turned out to be LB was not using proper sticky session.</p>


问:
Which is better: Several SQL queries or one sql data with lots of data?
I am making a quiz and I am expecting a lot of players for it. The quiz has a fixed number of questions.The quiz system can either fetch individual questions one by one from the MySql database and display it to the user. Or alternatively  I can fetch all the questions when he/she logs in and display them one by one. Can the second method significantly help in reducing the load on the server due to large number of SQL queries? Here I am talking about 500-600 users simultaneously playing the game.</p>

答: If the number of questions is small, it would make little difference either way. And if the number of questions is large, fetching in a single query is more efficient since you'll avoid most of the back-and-forth network latencies. </p>


问:
azure documentdb create document duplicates Id property
I want to store the following object in azure documentdb

```<code>public class MyDocument
{
    public string Id { get; set; }
    public SomeOtherClass SomeOtherClass { get; set; }
}
</code>```

the property Id is a timestamp (yyyyMMddHHmmss) followed by a guid. As a side-effect, this allows me to sort on Id.
I used this call to store it:

```<code> await docDbClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc);
</code>```

When the document is stored, it has my documents properties (Id and SomeOtherClass) and an additional "id" property (note the lowercase "i"). (and some other technical properties used by documentdb). This is filled with a guid.

As far as I understood, by storing an object which already has an Id property, documentdb would use this and not generate it's own (but it did!).

Now I have two problems: I can't check with

```<code> await docDbClient.ReadDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc.Id);
</code>```

to see if a document already exists, and I can't use the Id property to sort and compare documents in a query like this:

```<code>IQueryable<MyDocument> query = _client.CreateDocumentQuery<MyDocument>(
            UriFactory.CreateDocumentCollectionUri(_account.Database, _account.Collection), queryOptions);
 query = query.Where(x => x.Id.CompareTo(inputValue) >= 0);
</code>```

where inputValue is another key of the same form, to be used for paging. Because when deserializing the object out of documentdb, the id property replaces my Id property and I never see it's original value.

Am I using this wrong?
Did I make the wrong assumption that my Id property would be used instead of an auto-generated one with lowercase?

EDIT: I can confirm that this is solved when using [JsonProperty("id")] on the Id property. But any document already insertedI can't retrieve my original value of Id

答:
The ID field is expected to be "id" lower case.

This would solve it:

```<code>[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
</code>```

Body:
I want to store the following object in azure documentdb

public class MyDocument
{
    public string Id { get; set; }
    public SomeOtherClass SomeOtherClass { get; set; }
}

the property Id is a timestamp (yyyyMMddHHmmss) followed by a guid. As a side-effect, this allows me to sort on Id.
I used this call to store it:

 await docDbClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc);

When the document is stored, it has my documents properties (Id and SomeOtherClass) and an additional "id" property (note the lowercase "i"). (and some other technical properties used by documentdb). This is filled with a guid.

As far as I understood, by storing an object which already has an Id property, documentdb would use this and not generate it's own (but it did!).

Now I have two problems: I can't check with

 await docDbClient.ReadDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc.Id);

to see if a document already exists, and I can't use the Id property to sort and compare documents in a query like this:

IQueryable<MyDocument> query = _client.CreateDocumentQuery<MyDocument>(
            UriFactory.CreateDocumentCollectionUri(_account.Database, _account.Collection), queryOptions);
 query = query.Where(x => x.Id.CompareTo(inputValue) >= 0);

where inputValue is another key of the same form, to be used for paging. Because when deserializing the object out of documentdb, the id property replaces my Id property and I never see it's original value.

Am I using this wrong?
Did I make the wrong assumption that my Id property would be used instead of an auto-generated one with lowercase?

EDIT: I can confirm that this is solved when using [JsonProperty("id")] on the Id property. But any document already insertedI can't retrieve my original value of Id

Body:
The ID field is expected to be "id" lower case.

This would solve it:

[JsonProperty(PropertyName = "id")]
public string Id { get; set; }


问:
Is it possible to make eggs with a None zip-safe flag default to being instaleld zipped with Distribute?
Our large python project is being upgraded from using the legacy "setuptools" project to use "distribute" as a drop-in replacement.

We've noticed one problematic difference between the two applications: In setuptools an egg which had an undefined zip-safe flag was assumed to be zip-safe and would install as a zipped file (unless the user explicitly specifies not to).

By comparison with the new Distribute all eggs are assumed to be not zip safe (and will install unzipped) unless they have the zip-safe flag set to be explictly True.

As a consequence eggs which would previously have been installed simply by copying the .egg file to the site-packages are now unzipped to site-packages. Ideally, I'd like the new distribute to install eggs in a manner which is exactly consistent with the older setuptools.

It may sound like an inconsequential thing, however if we change something as fundamental as the directory structure of the site-packages folder it will force our team to go through a phase of international UAT which will be very time-consuming. It would be far better if we could simply guarantee that the new installer produces the exact same directory structure as the old one.

FYI, I'm using the very latest distribute on Python 2.4.4 for Windows XP 32bit.

答:
If you're using Python 2.4 on Windows, there aren't any advantages to using Distribute over Setuptools.  Distribute only offers a comparative advantage on Python 2.6 (where it supports the new "home" directory layout) and Python 3.x (which setuptools hasn't been ported to).

Apart from that, there aren't really any "upgrades" in Distribute, relative to setuptools; in fact, Distribute still contains bugs that have either been fixed in setuptools, or that never existed in setuptools (because they were added in Distribute).

You should also be aware that the people who created Distribute are now mainly working on Distutils2, and are NOT planning any significant improvements to Distribute.

I realize this might not be the answer you're looking for, since apparently you've already decided to switch.  However, if you switched purely on the basis of the popular rumor that setuptools isn't maintained or has bugs that Distribute fixes (which is actually the other way around), you might want to reconsider.


问:
How do I validate this kind of xml errors in the c# code?
```<code><?xml version="1.0" encoding="utf-8"?>
<xml>
  <a>str1234</a>xxxx
</xml>
</code>```

I got this xml file, as you can see, there's "xxxx" after the "a" close tag.

I tried the xmldocument.load() method but it wouldn't throw any exceptions.

I tried to generate a xsd file from this xml, then validate this xml with the generated xsd.

However, it also wouldn't throw any errors.

答:
It is important to understand the difference between valid and well-formed XML.

Commenters have sloppily said that your XML is valid.  They actually should not make such a statement without a schema against which to assess validity.  They should be saying that your XML is well-formed.

You seem to be concerned that xxxx text as a sibling to an a element is not well formed, but it is perfectly well-formed XML.  It might also be valid, if the parent element, xml is defined by a schema to allow mixed-content.

I tried to generate a xsd file from this xml, then validate this xml
  with the generated xsd.

Well, if you used a tool to generate an XSD from an XML document instance, and the XSD said the XML was valid, then the tool is working as designed.

But when my code loading this kind of .config file,it got stuck.

Just like being well-formed doesn't guarantee validity, it also doesn't guarantee that it meets the needs of any given consuming XML application.  A configuration file has rules, perhaps expressed in an XSD, that the XML must follow.  These rules are in addition to being well-formed (the rules that a parser requires in order to parse XML).

See also How to validate xml code file though .NET? + How would I do it if I use XML serialization?

Body:
<?xml version="1.0" encoding="utf-8"?>
<xml>
  str1234xxxx
</xml>

I got this xml file, as you can see, there's "xxxx" after the "a" close tag.

I tried the xmldocument.load() method but it wouldn't throw any exceptions.

I tried to generate a xsd file from this xml, then validate this xml with the generated xsd.

However, it also wouldn't throw any errors.


问:
difference between android.support.v7.app.AlertController.RecycleListView and android.support.v7.widget.RecyclerView
I recently update my Android Studio and also SDK. In new Android Studio, there is android.support.v7.app.AlertController.RecycleListView. I am familiar with android.support.v7.RecyclerView, so I am a little bit confused that what is the difference between these two. If anyone can guide then it would be thankful.

答:
RecycleListView is an internal class not intended for external use. The fact that it is showing up publicly in the support library is probably a mistake.

You can see here in the regular (non-appcompat) version it is an internal class http://developer.oesf.biz/em/developer/reference/eggplant/com/android/internal/app/AlertController.RecycleListView.html

edit: The old link is no longer available. Here is the archive.org version: https://web.archive.org/web/20170604100431/http://developer.oesf.biz/em/developer/reference/eggplant/com/android/internal/app/AlertController.RecycleListView.html

ContentLicense: CC BY-SA 4.0


问:
Get the value of the lowest array key
I have an array which returns this:

```<code>    Array (
            [122] => value
            [43] => value1
            [654645] => value2
            [34634] => value3
            [3] => value4  // I want this
            [550] => value5
    )
</code>```

How can I return value4 from the lowest key [3], I have read http://php.net/manual/en/array.sorting.php and attempted some of the sort by key examples with no luck.

答:
This will also helpful to you...

echo min(array_keys($arr));

Title: Get the value of the lowest array key

Body:
I have an array which returns this:

    Array (
            [122] => value
            [43] => value1
            [654645] => value2
            [34634] => value3
            [3] => value4  // I want this
            [550] => value5
    )

How can I return value4 from the lowest key [3], I have read http://php.net/manual/en/array.sorting.php and attempted some of the sort by key examples with no luck.


问:
How to make my application mount a sparse bundle without showing it in the Finder?
I am creating an application that has a bunch of files saved that are encrypted by using a sparse bundle, just like Time Machine does (my name is just a coincidence). I need to mount the sparse bundle to a mount point (I don't care which one). However, I'm afraid that when it
gets mounted it shows up on the desktop and in the Finder.

I have two questions:

How can I mount a sparse bundle from a Cocoa application?

How can I be sure it doesn't show up in the Finder/on the desktop?

My SDK is 10.6, by the way.

答: Use the Disk Arbitration framework. Specifically, call the DADiskMountWithArguments() function, passing the "nobrowse" argument.</p>


问:
Div with fixed width and inline element
I wrote some simple html document. I have two element inside: div with FIXED width, and image after it. As far I know, image is inline element, so it suppose to be positioned next to div, on the right side, since div has fixed width and there is a plenty room for image. Instead, image goes below div element. So it seems, that div element takes 100% of width no matter of what size it is. Why this happens?
Code: </p>

```<code>    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title></title>
            <meta charset="UTF-8" />

        </head>
    <body>
        <div style="width:500px;"><p>Some text</p></div>
        <img src="someImage.jpeg " />
    </body>
    </html>
</code>```

答:
Div is a block element. Therefore, other elements won't be placed next to it by default
You can add the following line to your CSS to achieve the behavior you expect:

img {float: right;}

Title: Div with fixed width and inline element

Body:
I wrote some simple html document. I have two element inside: div with FIXED width, and image after it. As far I know, image is inline element, so it suppose to be positioned next to div, on the right side, since div has fixed width and there is a plenty room for image. Instead, image goes below div element. So it seems, that div element takes 100% of width no matter of what size it is. Why this happens?
Code:

    <!DOCTYPE html>

            <title></title>
            <meta charset="UTF-8" />

Some text


问:
How to draw pheatmap plot to screen and also save to file
I'm working with the pheatmap package. By default, it draws the plot to the screen. In my case, that means output in a R markdown notebook in R studio. But I also want to save to a file. If I save it to a file, giving it the filename= argument, it doesn't draw to the screen (R notebook). Is there a way to get both things to happen? And more generally, with any plot (ggplot2) where I want to both save and show on the screen?

答:
FYI, I made a more complex function that includes making the pheatmap and then calling the save_heatmap function from above. I'm posting it here if it is useful to anyone, and also for critiques. I added in a line to save the heatmap image file with the name of the matrix that gives rise to the heatmap. This is helpful for downstream organization of the files.

```<code>save_pheatmap <- function(x, filename, width=480, height=960) {
   stopifnot(!missing(x))
   stopifnot(!missing(filename))
   png(filename,width = width, height=height)
   grid::grid.newpage()
   grid::grid.draw(x$gtable)
   dev.off()
}

plot_heatmap <- function(mat,color=NULL, cluster_rows=NULL, cluster_cols=NULL, scale=NULL,
  cellwidth=NULL, cellheight=NULL,show_colnames=NULL, labels_col=NULL, show_rownames=NULL,
  border_color=NULL,legend=NULL,...){

  #Default Color
  if (is.null(color)){
    color=rev(col.pal)
  }

  #Default cluster
  if (is.null(cluster_rows)){
    cluster_rows=FALSE
  }

  if (is.null(cluster_cols)){
    cluster_cols=FALSE
  }

  #Default sclae
  if(is.null(scale)){
    scale="none"
  }

  #Default cell dims
  if (is.null(cellwidth)){
    cellwidth=12
  }

  if (is.null(cellheight)){
    cellheight=12
  }

  #Default Labels

  if (is.null(show_colnames)){
    show_colnames=TRUE
  }

  if (is.null(labels_col)){
    labels_col=NULL
  }

  if (is.null(show_rownames)){
    show_rownames=FALSE
  }

  #Set border

  if (is.null(border_color)){
    border_color=NA
  }

  #Legend

  if (is.null(legend)){
    legend=FALSE
  }

  temp_hm <- pheatmap(mat,color=color, cluster_rows=cluster_rows, cluster_cols=cluster_cols, scale=scale,
  cellwidth=cellwidth, cellheight=cellheight,show_colnames=show_colnames, labels_col=labels_col,
  show_rownames=show_rownames,border_color=border_color,legend=legend)

  temp_hm_name <- paste(deparse(substitute(mat)),".png", sep="")

  save_pheatmap(temp_hm, filename=temp_hm_name)
</code>```

}

Body:
FYI, I made a more complex function that includes making the pheatmap and then calling the save_heatmap function from above. I'm posting it here if it is useful to anyone, and also for critiques. I added in a line to save the heatmap image file with the name of the matrix that gives rise to the heatmap. This is helpful for downstream organization of the files.

save_pheatmap <- function(x, filename, width=480, height=960) {
   stopifnot(!missing(x))
   stopifnot(!missing(filename))
   png(filename,width = width, height=height)
   grid::grid.newpage()
   grid::grid.draw(x$gtable)
   dev.off()
}

plot_heatmap <- function(mat,color=NULL, cluster_rows=NULL, cluster_cols=NULL, scale=NULL,
  cellwidth=NULL, cellheight=NULL,show_colnames=NULL, labels_col=NULL, show_rownames=NULL,
  border_color=NULL,legend=NULL,...){

  #Default Color
  if (is.null(color)){
    color=rev(col.pal)
  }

  #Default cluster
  if (is.null(cluster_rows)){
    cluster_rows=FALSE
  }

  if (is.null(cluster_cols)){
    cluster_cols=FALSE
  }

  #Default sclae
  if(is.null(scale)){
    scale="none"
  }

  #Default cell dims
  if (is.null(cellwidth)){
    cellwidth=12
  }

  if (is.null(cellheight)){
    cellheight=12
  }

  #Default Labels

  if (is.null(show_colnames)){
    show_colnames=TRUE
  }

  if (is.null(labels_col)){
    labels_col=NULL
  }

  if (is.null(show_rownames)){
    show_rownames=FALSE
  }

  #Set border

  if (is.null(border_color)){
    border_color=NA
  }

  #Legend

  if (is.null(legend)){
    legend=FALSE
  }

  temp_hm <- pheatmap(mat,color=color, cluster_rows=cluster_rows, cluster_cols=cluster_cols, scale=scale,
  cellwidth=cellwidth, cellheight=cellheight,show_colnames=show_colnames, labels_col=labels_col,
  show_rownames=show_rownames,border_color=border_color,legend=legend)

  temp_hm_name <- paste(deparse(substitute(mat)),".png", sep="")

  save_pheatmap(temp_hm, filename=temp_hm_name)

}


问:
Read from csv file into 2d array and sort the array using c
In my csv file, currently i have data like

```<code>45454, 32, 78, C, 67
45452, 22, 38, C, 34
</code>```

I want to add the data into 2d array and sort them.
Currently i am using this approach

```<code>#include<stdio.h>
#include<conio.h>
#include<String.h>

void getData(char *buff);
int main()
{
    FILE *fp = fopen("file1.csv", "r");
    int count = -1;
    do
    {
        char buff[1024];
        fgets(buff, 1024, (FILE*)fp);
        count++;
        if(count != 1)
        {
            printf(buff);
            getData(buff);
        }
    }
    while((getc(fp))!= EOF);

}
void getData(char buff[])
{
    char *token = strtok(buff,",");
    int counter=0;

    while( token != NULL )
    {
        counter++;
        printf(" %s\n",token);
        token = strtok(NULL,",");
    }
}
</code>```

But i want to read data using fgets and sscanf and store them into single dimensional VLA’s (variable-length arrays)
How can i do that?

答:
This is my working code</p>

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct
{
    int id, exam1, exam2, exam3;
    char grade;
} Row;

int getSize(char* filename)
{
    int rows=0;
    FILE* file = fopen(filename, "r");
    char line[1024];
    while (fgets(line, 1024, file) != NULL)
    {
        rows++;
    }

    return rows;
}

void sort(Row *a, int length)
{
    int j;
    Row temp;
    int i;
    for (i = 1; i < length; i++)
    {
        j = i;
        while (j > 0 && a[j].id < a[j - 1].id || (a[j].id == a[j - 1].id && a[j].grade < a[j - 1].grade))
        {
            temp = a[j];
            a[j] = a[j - 1];
            a[j - 1] = temp;
            j--;
        }
    }
}

int binarySearch(Row *row, int size, int key)
{
    int i, start, end, mid;
    start = 0;
    end = size;

    do
    {
        mid = (int)((start + end)/2);
        if(row[mid].id == key)
        {
            printf("\n");
            printf("+--------+");
            printf("-----------+");
            printf("-------+\n");
            printf("| Index  |  Student  | Grade |\n");
            printf("+--------+");
            printf("-----------+");
            printf("-------+\n");
            printf("| %-5d  |  %-5d   |\t %-4c|\n", mid+1, row[mid].id, row[mid].grade);
            printf("+--------+");
            printf("-----------+");
            printf("-------+\n");
            printf("\n");
            break;
        }
        else if(row[mid].id > key)
        {
            end = mid - 1;
        }
        else
        {
            start = mid + 1;
        }
    }
    while(start <= end);

    if(start > end)
    {
        printf("\n");
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("| Index  |  Student  | Grade |\n");
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("| N/A   |  N/A    |\t N/A|\n");
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("\n");
    }
}

int main()
{
    char* filename = "grades.csv";
    int rows = getSize(filename);
    printf("There are %d lines in file grades.csv.\n\n", rows);
    FILE* stream = fopen("grades.csv", "r");
    Row *row = malloc(sizeof(*row) * rows);
    char line[1024];
    int i = 0;

    printf("Original:\n");
    printf("+--------+");
    printf("-----------+");
    printf("-------+");
    printf("------+");
    printf("-------+\n");
    printf("| Student|    Exam 1 | Exam 2|Exam 3| Grade |\n");
    while(fgets(line, 1024, stream) != NULL)
    {
        printf("+--------+");
        printf("-----------+");
        printf("-------+");
        printf("------+");
        printf("-------+\n");
        sscanf(line, "%d,%d,%d,%d,%c", &row[i].id, &row[i].exam1, &row[i].exam2, &row[i].exam3, &row[i].grade);
        printf("| %d |\t %-4d|\t %-4d|\t%-4d|\t%-4c|\n", row[i].id, row[i].exam1, row[i].exam2, row[i].exam3, row[i].grade);
        i++;
    }
    printf("+--------+");
    printf("-----------+");
    printf("-------+");
    printf("------+");
    printf("-------+\n");
    printf("\n\n");

    printf("Sorted:\n");
    sort(row, rows);
    printf("+--------+");
    printf("-----------+");
    printf("-------+\n");
    printf("| Index  |  Student  | Grade |\n");
    for(i = 0; i < rows; i++)
    {
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("| %-5d  |  %-5d   |\t %-4c|\n", i+1, row[i].id, row[i].grade);
    }
    printf("+--------+");
    printf("-----------+");
    printf("-------+\n");

    int sid;
    int ex = 0;

    while(1)
    {
        printf("\n\nEnter student ID (-1 to quit): ");
start:
        scanf("%d", &sid);

        if(sid == -1)
        {
            return 0;
        }
        else if(sid > 100000 && sid < 999999)
        {
            binarySearch(row, rows, sid);
            printf("\n\nEnter student ID (-1 to quit): ");
            goto start;
        }
        else
        {
            printf("\nERROR and enter again ([100000,9999999] and -1 to quit): ");
            goto start;
        }
    }

    fclose(stream);
    free(row);

    return 0;
}
</code>```

Body:
In my csv file, currently i have data like

45454, 32, 78, C, 67
45452, 22, 38, C, 34

I want to add the data into 2d array and sort them.
Currently i am using this approach

#include<stdio.h>
#include<conio.h>
#include<String.h>

void getData(char *buff);
int main()
{
    FILE *fp = fopen("file1.csv", "r");
    int count = -1;
    do
    {
        char buff[1024];
        fgets(buff, 1024, (FILE*)fp);
        count++;
        if(count != 1)
        {
            printf(buff);
            getData(buff);
        }
    }
    while((getc(fp))!= EOF);

}
void getData(char buff[])
{
    char *token = strtok(buff,",");
    int counter=0;

    while( token != NULL )
    {
        counter++;
        printf(" %s\n",token);
        token = strtok(NULL,",");
    }
}

But i want to read data using fgets and sscanf and store them into single dimensional VLA’s (variable-length arrays)
How can i do that?

Body:
This is my working code

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct
{
    int id, exam1, exam2, exam3;
    char grade;
} Row;

int getSize(char* filename)
{
    int rows=0;
    FILE* file = fopen(filename, "r");
    char line[1024];
    while (fgets(line, 1024, file) != NULL)
    {
        rows++;
    }

    return rows;
}

void sort(Row *a, int length)
{
    int j;
    Row temp;
    int i;
    for (i = 1; i < length; i++)
    {
        j = i;
        while (j > 0 && a[j].id < a[j - 1].id || (a[j].id == a[j - 1].id && a[j].grade < a[j - 1].grade))
        {
            temp = a[j];
            a[j] = a[j - 1];
            a[j - 1] = temp;
            j--;
        }
    }
}

int binarySearch(Row *row, int size, int key)
{
    int i, start, end, mid;
    start = 0;
    end = size;

    do
    {
        mid = (int)((start + end)/2);
        if(row[mid].id == key)
        {
            printf("\n");
            printf("+--------+");
            printf("-----------+");
            printf("-------+\n");
            printf("| Index  |  Student  | Grade |\n");
            printf("+--------+");
            printf("-----------+");
            printf("-------+\n");
            printf("| %-5d  |  %-5d   |\t %-4c|\n", mid+1, row[mid].id, row[mid].grade);
            printf("+--------+");
            printf("-----------+");
            printf("-------+\n");
            printf("\n");
            break;
        }
        else if(row[mid].id > key)
        {
            end = mid - 1;
        }
        else
        {
            start = mid + 1;
        }
    }
    while(start <= end);

    if(start > end)
    {
        printf("\n");
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("| Index  |  Student  | Grade |\n");
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("| N/A   |  N/A    |\t N/A|\n");
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("\n");
    }
}

int main()
{
    char* filename = "grades.csv";
    int rows = getSize(filename);
    printf("There are %d lines in file grades.csv.\n\n", rows);
    FILE* stream = fopen("grades.csv", "r");
    Row *row = malloc(sizeof(*row) * rows);
    char line[1024];
    int i = 0;

    printf("Original:\n");
    printf("+--------+");
    printf("-----------+");
    printf("-------+");
    printf("------+");
    printf("-------+\n");
    printf("| Student|    Exam 1 | Exam 2|Exam 3| Grade |\n");
    while(fgets(line, 1024, stream) != NULL)
    {
        printf("+--------+");
        printf("-----------+");
        printf("-------+");
        printf("------+");
        printf("-------+\n");
        sscanf(line, "%d,%d,%d,%d,%c", &row[i].id, &row[i].exam1, &row[i].exam2, &row[i].exam3, &row[i].grade);
        printf("| %d |\t %-4d|\t %-4d|\t%-4d|\t%-4c|\n", row[i].id, row[i].exam1, row[i].exam2, row[i].exam3, row[i].grade);
        i++;
    }
    printf("+--------+");
    printf("-----------+");
    printf("-------+");
    printf("------+");
    printf("-------+\n");
    printf("\n\n");

    printf("Sorted:\n");
    sort(row, rows);
    printf("+--------+");
    printf("-----------+");
    printf("-------+\n");
    printf("| Index  |  Student  | Grade |\n");
    for(i = 0; i < rows; i++)
    {
        printf("+--------+");
        printf("-----------+");
        printf("-------+\n");
        printf("| %-5d  |  %-5d   |\t %-4c|\n", i+1, row[i].id, row[i].grade);
    }
    printf("+--------+");
    printf("-----------+");
    printf("-------+\n");

    int sid;
    int ex = 0;

    while(1)
    {
        printf("\n\nEnter student ID (-1 to quit): ");
start:
        scanf("%d", &sid);

        if(sid == -1)
        {
            return 0;
        }
        else if(sid > 100000 && sid < 999999)
        {
            binarySearch(row, rows, sid);
            printf("\n\nEnter student ID (-1 to quit): ");
            goto start;
        }
        else
        {
            printf("\nERROR and enter again ([100000,9999999] and -1 to quit): ");
            goto start;
        }
    }

    fclose(stream);
    free(row);

    return 0;
}


问:
Angular 2 - find instance in array
Im building a dummy login for an app, and I need to check for an instance of the user logging in, within an array

I have some mock data

```<code>import { User } from './user';

export const USERS: User[] = [
  {username: 'Seth', password: 'youwillneverknow'},
  {username: 'Peter', password: 'iforgot'},
  {username: 'Frank', password: 'test123'},
];
</code>```

Which I use in my user.service file

```<code>import { Injectable } from '@angular/core';
import { User } from './user';
import { USERS } from './users.mock';

@Injectable()
export class UserService {
  getUsers(): Promise<User[]> {
    return Promise.resolve(USERS);
  }

  <some method here>

}
</code>```

and in my component I need to write a method checking if the user exists in the array.

```<code>  logIn(value: string): void {

  }
</code>```

The string value comes from a input field in my HTML

I need some input on how to check for an instance of that username when calling the logIn function

答:
To find an instance of an array use:

```<code>users.find(x => x.username == value);
</code>```

This will return the object in the USER array that with the matching user name.  It will return undefined if it doesn't exist.

You can also use findIndex, which will return the index of the item in the array that matches the predicate or -1 if it doesn't exist:

```<code>users.findIndex(x => x.username == value);
</code>```

As for having a list of usernames and passwords, this is definitely not recommended authentication.  I hope you are doing something else for a production application.

Title: Angular 2 - find instance in array

Body:
Im building a dummy login for an app, and I need to check for an instance of the user logging in, within an array

I have some mock data

import { User } from './user';

export const USERS: User[] = [
  {username: 'Seth', password: 'youwillneverknow'},
  {username: 'Peter', password: 'iforgot'},
  {username: 'Frank', password: 'test123'},
];

Which I use in my user.service file

import { Injectable } from '@angular/core';
import { User } from './user';
import { USERS } from './users.mock';

@Injectable()
export class UserService {
  getUsers(): Promise<User[]> {
    return Promise.resolve(USERS);
  }

  <some method here>

}

and in my component I need to write a method checking if the user exists in the array.

  logIn(value: string): void {

  }

The string value comes from a input field in my HTML

I need some input on how to check for an instance of that username when calling the logIn function

Body:
To find an instance of an array use:

users.find(x => x.username == value);

This will return the object in the USER array that with the matching user name.  It will return undefined if it doesn't exist.

You can also use findIndex, which will return the index of the item in the array that matches the predicate or -1 if it doesn't exist:

users.findIndex(x => x.username == value);

As for having a list of usernames and passwords, this is definitely not recommended authentication.  I hope you are doing something else for a production application.


问:
How to understand "accidentally all objects" when in C++ loop?
I watched the Cpp conf talk: range for, and confused about the meaning of "accidentally all objects":

How to understand it?

答: The slide should have said "accidentally copy all the objects".  You usually don't want to copy the objects into v, which is why Dietmar recommends making v a reference instead.


问:
How to create two views in Android that use 50% height each, unless one is smaller?
Imagine a full Android device screen, I want it split in to two sections:

The upper half has text in it, which may be larger than the space available (or not) and so the text will scroll (i.e. TextView inside a ScrollView)

The lower half contains a MapView control.

Looking specifically at some scenarios:

If the text is small, I want the map to take up more space, i.e. more than 50%. So perhaps 20% text, 80% map.

If the text is larger, it only takes up a MAXIMUM of 50% of the screen space, and then scrolls. So 50% map, 50% text.

At the moment I've assigned weights to the two parts, and that isn't too bad, but if the text is small, the map doesn't expand to take the space, and the layout has a wasted gap that the map could usefully use.

I've tried loads of combinations but can't see how to make this happen. It seems to be a common experience for me that I know what I want, but can't see how to get the available views to deliver it. I'm hoping there's a nice easy way to do this.

Please feel free to make me look like a fool and point out the obvious attribute I've missed :-)

======================================================================

As far as I can see there's no way to do this just in declarative XML and it needs doing in the code. I set the text section height to wrap_content, weight to 0 (no resizing), and have the map set to weight=1 (i.e. take up the remaining space). I then check if the text section (in a ScrollView) is taking up too much space and if so, shrink it back. This code would need changing to support a different layout orientation.

```<code>private void fixLayoutProportions()
{
    float maxPercentageOfScreenForText = 50/100;
    LinearLayout container = (LinearLayout)findViewById(R.id.container);
    ScrollView eventText = (ScrollView)findViewById(R.id.text_scroller);
    int heightAvailable = container.getHeight();
    int scrollerHeight = eventText.getHeight();
    if ( scrollerHeight>(heightAvailable*maxPercentageOfScreenForText) )      // Text section using too much space
    {
        eventText.getLayoutParams().height = (int)(heightAvailable*maxPercentageOfScreenForText) ;
        eventText.invalidate();
    }
}
</code>```

答:
Did you try to measure your screen hight at run time:

```<code>Display display = ((WindowManager)
      getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getHeight();
</code>```

Then, set your top view max_height to width*0.5 and min_height to width*0.2. Your top view has to be control (like TextView) that has min_height and max_height properties. Also, set layout_weight to 0 or leave it empty.
On your bottom view set layout weight to 1.

Body:
Imagine a full Android device screen, I want it split in to two sections:

The upper half has text in it, which may be larger than the space available (or not) and so the text will scroll (i.e. TextView inside a ScrollView)

The lower half contains a MapView control.

Looking specifically at some scenarios:

If the text is small, I want the map to take up more space, i.e. more than 50%. So perhaps 20% text, 80% map.

If the text is larger, it only takes up a MAXIMUM of 50% of the screen space, and then scrolls. So 50% map, 50% text.

At the moment I've assigned weights to the two parts, and that isn't too bad, but if the text is small, the map doesn't expand to take the space, and the layout has a wasted gap that the map could usefully use.

I've tried loads of combinations but can't see how to make this happen. It seems to be a common experience for me that I know what I want, but can't see how to get the available views to deliver it. I'm hoping there's a nice easy way to do this.

Please feel free to make me look like a fool and point out the obvious attribute I've missed :-)

======================================================================

As far as I can see there's no way to do this just in declarative XML and it needs doing in the code. I set the text section height to wrap_content, weight to 0 (no resizing), and have the map set to weight=1 (i.e. take up the remaining space). I then check if the text section (in a ScrollView) is taking up too much space and if so, shrink it back. This code would need changing to support a different layout orientation.

private void fixLayoutProportions()
{
    float maxPercentageOfScreenForText = 50/100;
    LinearLayout container = (LinearLayout)findViewById(R.id.container);
    ScrollView eventText = (ScrollView)findViewById(R.id.text_scroller);
    int heightAvailable = container.getHeight();
    int scrollerHeight = eventText.getHeight();
    if ( scrollerHeight>(heightAvailable*maxPercentageOfScreenForText) )      // Text section using too much space
    {
        eventText.getLayoutParams().height = (int)(heightAvailable*maxPercentageOfScreenForText) ;
        eventText.invalidate();
    }
}

Body:
Did you try to measure your screen hight at run time:

Display display = ((WindowManager)
      getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getHeight();

Then, set your top view max_height to width*0.5 and min_height to width*0.2. Your top view has to be control (like TextView) that has min_height and max_height properties. Also, set layout_weight to 0 or leave it empty.
On your bottom view set layout weight to 1.


答:
A block element tolerates no HTML elements next to it, except when ordered otherwise (by adding a float declaration to another element, for instance).

That is the reason image goes to the next line. Try using the same with a span,image will not go to the next line. Simple reason being span is an inline element and can entertain another HTML element next to it provided the element is an inline element.

Hope this helps!

Title: Div with fixed width and inline element


问:
Add image from URL to Excel with Axlsx
I'm using the (Axlsx gem and it's working great, but I need to add an image to a cell.
I know it can be done with an image file (see Adding image to Excel file generated by Axlsx.?), but I'm having a lot of trouble using our images stored in S3 (through Carrierwave).

Things I've tried:

```<code># image.url = 'http://.../test.jpg'
ws.add_image(:image_src => image.url,:noSelect => true, :noMove => true) do |image|

# ArgumentError: File does not exist
</code>```

or

```<code>ws.add_image(:image_src => image,:noSelect => true, :noMove => true) do |image|
# Invalid Data #<Object ...>
</code>```

Not sure how to proceed

答:
To add an alternative answer for Paperclip & S3 as I couldn't find a reference for that besides this answer.

I'm using Rails 5.0.2 and Paperclip 4.3.1.

With image URLs like: http://s3.amazonaws.com/prod/accounts/logos/000/000/001/original/logo.jpg?87879987987987

```<code>@logo = @account.company_logo
if @logo.present?
  @logo_image = Tempfile.new(['', ".#{@logo.url.split('.').last.split('?').first}"])
  @logo_image.binmode # note that our tempfile must be in binary mode
  @logo_image.write open(@logo.url).read
  @logo_image.rewind
end
</code>```

In the .xlsx file

```<code>sheet.add_image(image_src:  @logo_image.path, noSelect: true, noMove: true, hyperlink: "#") do |image|...
</code>```

Reference link: http://mensfeld.pl/tag/tempfile/ for more reading.

The .split('.').last.split('?').first is to get .jpg from logo.jpg? 87879987987987.

Title: Add image from URL to Excel with Axlsx

Body:
I'm using the (Axlsx gem and it's working great, but I need to add an image to a cell.
I know it can be done with an image file (see Adding image to Excel file generated by Axlsx.?), but I'm having a lot of trouble using our images stored in S3 (through Carrierwave).

Things I've tried:

# image.url = 'http://.../test.jpg'
ws.add_image(:image_src => image.url,:noSelect => true, :noMove => true) do |image|

# ArgumentError: File does not exist

or

ws.add_image(:image_src => image,:noSelect => true, :noMove => true) do |image|
# Invalid Data #<Object ...>

Not sure how to proceed

Body:
To add an alternative answer for Paperclip & S3 as I couldn't find a reference for that besides this answer.

I'm using Rails 5.0.2 and Paperclip 4.3.1.

With image URLs like: http://s3.amazonaws.com/prod/accounts/logos/000/000/001/original/logo.jpg?87879987987987

@logo = @account.company_logo
if @logo.present?
  @logo_image = Tempfile.new(['', ".#{@logo.url.split('.').last.split('?').first}"])
  @logo_image.binmode # note that our tempfile must be in binary mode
  @logo_image.write open(@logo.url).read
  @logo_image.rewind
end

In the .xlsx file

sheet.add_image(image_src:  @logo_image.path, noSelect: true, noMove: true, hyperlink: "#") do |image|...

Reference link: http://mensfeld.pl/tag/tempfile/ for more reading.

The .split('.').last.split('?').first is to get .jpg from logo.jpg? 87879987987987.


问:
.htaccess files slugs from database
Really simple question about `.htaccess, slugs and rewriting urls.

If I have an article how can I replace the entire url in the address bar with something out of a database?

For example in my url I have /article.php?id=1
In ralation to the id of the article in this case with id 1, I have a field name in the database called 'art_url' which has a value of /article/my-url

How can I get that to become the address instead of /article.php?id=1
?

I get a PHP error when I try to use this URL dev.mywebaddress.com/article/my-url/. Is there an issue in my PHP with the htaccess file? Here is my code:

```<code>    <?php
    if(!empty($_GET['art_url']))
    {
    $sql = "

    SELECT articles.id AS articleid, articles.art_title AS title,  articles.art_url AS art_url, articles.art_content AS content, campaigns.id, campaigns.camp_title AS camptitle
FROM articles
LEFT JOIN campaigns ON articles.art_campaign = campaigns.id

";
}
    // then do the query, etc....

$results = $db->query($sql);

if($results->num_rows) {
    While($row = $results->fetch_object()) {
        $camptitle = nl2br(htmlentities($row->camptitle));
        $title = nl2br(htmlentities($row->title));
        $content = nl2br($row->content);
        $art_url = ($row->art_url);
        echo "
        <H2>{$camptitle}</H2>
    <H3>{$title}</H3>
    <p>{$content}</p>

";
    }
} else {
    echo 'No Results';
}
?>
</code>```

.htaccess file

```<code>    # Turn Rewrite Engine On
RewriteEngine On
#RewriteRule ^article/([0-9a-zA-Z-/]+) article.php?art_url=$1
</code>```

答:
You can add a 301 redirect within your PHP code. Look up the value of art_slug and then ..

```<code><?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.yourdomain.com/".$art_slug);
?>
</code>```

Your .htaccess file could be set up to pick up XXX/YYY using this:

```<code>RewriteEngine on
RewriteRule ^([^/\.]+)/([^/\.]+)$ index.php?firstSlug=$1&secondSlug=$2 [NC,L,QSA]
</code>```

You would then receive firstSlug=XXX and secondSlug=YYY at index.php

Title: .htaccess files slugs from database

Body:
Really simple question about `.htaccess, slugs and rewriting urls.

If I have an article how can I replace the entire url in the address bar with something out of a database?

For example in my url I have /article.php?id=1
In ralation to the id of the article in this case with id 1, I have a field name in the database called 'art_url' which has a value of /article/my-url

How can I get that to become the address instead of /article.php?id=1
?

I get a PHP error when I try to use this URL dev.mywebaddress.com/article/my-url/. Is there an issue in my PHP with the htaccess file? Here is my code:

    <?php
    if(!empty($_GET['art_url']))
    {
    $sql = "

    SELECT articles.id AS articleid, articles.art_title AS title,  articles.art_url AS art_url, articles.art_content AS content, campaigns.id, campaigns.camp_title AS camptitle
FROM articles
LEFT JOIN campaigns ON articles.art_campaign = campaigns.id

";
}
    // then do the query, etc....

$results = $db->query($sql);

if($results->num_rows) {
    While($row = $results->fetch_object()) {
        $camptitle = nl2br(htmlentities($row->camptitle));
        $title = nl2br(htmlentities($row->title));
        $content = nl2br($row->content);
        $art_url = ($row->art_url);
        echo "

{$camptitle}

{$title}

{$content}

";
    }
} else {
    echo 'No Results';
}
?>

.htaccess file

    # Turn Rewrite Engine On
RewriteEngine On
#RewriteRule ^article/([0-9a-zA-Z-/]+) article.php?art_url=$1

Body:
You can add a 301 redirect within your PHP code. Look up the value of art_slug and then ..

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.yourdomain.com/".$art_slug);
?>

Your .htaccess file could be set up to pick up XXX/YYY using this:

RewriteEngine on
RewriteRule ^([^/\.]+)/([^/\.]+)$ index.php?firstSlug=$1&secondSlug=$2 [NC,L,QSA]

You would then receive firstSlug=XXX and secondSlug=YYY at index.php


问:
Dynamic url for $http get
Here is what i try to do :
Json from "urldatas":

```<code>[{ "name" : "John" }]
</code>```

JS file:

```<code> var app = angular.module('app', []);
    app.service('service', function($http, $q){
        this.getDatas = function () {
            var datas = $http.get('urldatas', {cache: false});
            return $q.all({datas});
        };
    app.controller('FirstCtrl', function($scope, service, $http, $timeout) {
        var vm = this;
        vm.loadData = function () {
            var promise = service.getDatas();
            promise.then(function (data) {
                $scope.datas = data.datas.data;
                console.log($scope.datas);
            });
        };
    vm.loadPackages = function () {
            var url = "urlPackages" + datas.name;
            $http.get(url).then(function (response) {
            $scope.MyPackages = response.data;
        });
};
</code>```

So i try to dynamicly change url in $http.get in getPackages, by values from getDatas, but i don't know how to do it. url in console shows "urlPackagesundefinded". Thanks for answers in advance.

答:
$q send multiple requests as an array, not as an object.  remove the curly bracket and add a square bracket

```<code>var datas = $http.get('urldatas', {cache: false});
return $q.all([datas]);
</code>```

since you reference the controllerAs remove the scope variables and reference them through vm.

also in then promises response data comes under data property

```<code>var promise = service.getDatas();
promise.then(function (response) {
   vm.datas = response.data.datas.data;
   console.log(vm.datas);
});
</code>```

Title: Dynamic url for $http get

Body:
Here is what i try to do :
Json from "urldatas":

[{ "name" : "John" }]

JS file:

 var app = angular.module('app', []);
    app.service('service', function($http, $q){
        this.getDatas = function () {
            var datas = $http.get('urldatas', {cache: false});
            return $q.all({datas});
        };
    app.controller('FirstCtrl', function($scope, service, $http, $timeout) {
        var vm = this;
        vm.loadData = function () {
            var promise = service.getDatas();
            promise.then(function (data) {
                $scope.datas = data.datas.data;
                console.log($scope.datas);
            });
        };
    vm.loadPackages = function () {
            var url = "urlPackages" + datas.name;
            $http.get(url).then(function (response) {
            $scope.MyPackages = response.data;
        });
};

So i try to dynamicly change url in $http.get in getPackages, by values from getDatas, but i don't know how to do it. url in console shows "urlPackagesundefinded". Thanks for answers in advance.

Body:
$q send multiple requests as an array, not as an object.  remove the curly bracket and add a square bracket

var datas = $http.get('urldatas', {cache: false});
return $q.all([datas]);

since you reference the controllerAs remove the scope variables and reference them through vm.

also in then promises response data comes under data property

var promise = service.getDatas();
promise.then(function (response) {
   vm.datas = response.data.datas.data;
   console.log(vm.datas);
});


问:
js regex not support lookbehind how to implement this?
a = "1+2-3*4/5+(6+7^2)"
I want to get the pure number but not include second 2.
Because second 2 is exponent. It's fixed. I don't want it.
I written a regex.
var myRegx = (?<=[\+\-\*\/\(\^])\d+
JS don't support lookbehind.

Who can help me?
var r = a.match(yourRegx)
I want get=>
[1,2,3,4,5,6,7]

答:
I would break this into three separate functions. first replace any exponents, second get any numbers from the string. Finally map all the strings to numbers.

const a = '1+2-3*4/5+(6+7^2)'
const r = a.replace(/\^\d+/g).match(/\d+/g).map(Number)

console.log(r)```
</div>
</div>
</p>

<p>Using match has a flaw of not returning an empty array if there are no matches, so the above code will throw an error if you don't have any numbers in your string. If you need type safety and error handling you could use a functional pattern like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a = '1+2-3*4/5+(6+7^2)'
const b = 'word'

const extractNumbers = x =>
  [x].map(x => x.replace(/\^\d+/g))
     .map(x => x.match(/\d+/g))
     .map(x => x != null ? x.map(Number) : x)
     .pop()

console.log(extractNumbers(a))
console.log(extractNumbers(b))</code>```

Body:
I would break this into three separate functions. first replace any exponents, second get any numbers from the string. Finally map all the strings to numbers.

const a = '1+2-3*4/5+(6+7^2)'
const r = a.replace(/\^\d+/g).match(/\d+/g).map(Number)

console.log(r)

Using match has a flaw of not returning an empty array if there are no matches, so the above code will throw an error if you don't have any numbers in your string. If you need type safety and error handling you could use a functional pattern like this.

const a = '1+2-3*4/5+(6+7^2)'
const b = 'word'

const extractNumbers = x =>
  [x].map(x => x.replace(/\^\d+/g))
     .map(x => x.match(/\d+/g))
     .map(x => x != null ? x.map(Number) : x)
     .pop()

console.log(extractNumbers(a))
console.log(extractNumbers(b))


问:
For-looping VBA vectors
I'm trying to create a vector in VBA using a for loop. My problem is that VBA doesn't allow me to have a different equation for the first vector coordinate. When trying to run it I get "expected array" as an error message

```<code>'radius calculations
r(1) = (al * Log(al) / (al - 1)) * rb ' middle radius of block 1, trying to calculate first entry
'in r-vector, since this equation is different from the rest
r_m(1) = rb 'r_i-1/2 i=1

For i = 2 To n_r
    r(i) = al * r(i - 1) ' r_i
    r_m(i) = (r(i) - r(i - 1)) / (Log(r(i) / r(i - 1)))
Next i
</code>```

al and rb is defined as Double (Public Const), while r is defined as a string. I have only used Matlab in the past, and only read intro guides to VBA (VBA for Dummies etc.)

Greatly appreciate all help in the matter

E

答:
VBA doesn't treat strings the same way it treats arrays (like you'd see in other languages).  r(1) looks like array syntax to VBA (as can be seen here); therefore, it's going to error out if it's declared as a string.

So, essentially, VBA is interpreting r(1) to mean, "I have an array named r and I want to store something into element number 1".  But, instead, it's attempting to do this to an immutable string.

The Split function can be used to turn a string into an array, if that's what you need.

Still, it'll be best if you straight-up declare an array for your vector math.

```<code>Dim myArray() As Double
Dim myArray2(10, 10, 10) As Double
</code>```

The ReDim keyword can be used to resize an array, even within a for loop.  (Just don't forget to ReDim Preserve if you need to make sure that the contents don't get wiped during this operation).

Title: For-looping VBA vectors

Body:
I'm trying to create a vector in VBA using a for loop. My problem is that VBA doesn't allow me to have a different equation for the first vector coordinate. When trying to run it I get "expected array" as an error message

'radius calculations
r(1) = (al * Log(al) / (al - 1)) * rb ' middle radius of block 1, trying to calculate first entry
'in r-vector, since this equation is different from the rest
r_m(1) = rb 'r_i-1/2 i=1

For i = 2 To n_r
    r(i) = al * r(i - 1) ' r_i
    r_m(i) = (r(i) - r(i - 1)) / (Log(r(i) / r(i - 1)))
Next i

al and rb is defined as Double (Public Const), while r is defined as a string. I have only used Matlab in the past, and only read intro guides to VBA (VBA for Dummies etc.)

Greatly appreciate all help in the matter

E

Body:
VBA doesn't treat strings the same way it treats arrays (like you'd see in other languages).  r(1) looks like array syntax to VBA (as can be seen here); therefore, it's going to error out if it's declared as a string.

So, essentially, VBA is interpreting r(1) to mean, "I have an array named r and I want to store something into element number 1".  But, instead, it's attempting to do this to an immutable string.

The Split function can be used to turn a string into an array, if that's what you need.

Still, it'll be best if you straight-up declare an array for your vector math.

Dim myArray() As Double
Dim myArray2(10, 10, 10) As Double

The ReDim keyword can be used to resize an array, even within a for loop.  (Just don't forget to ReDim Preserve if you need to make sure that the contents don't get wiped during this operation).


问:
Write to google spreadsheet using Python
I an wondering is there is a way to write to google spreadsheet using Python.  Found python-gdata-client library,  installed it with all dependencies. Using this code below but it is not working

```<code>import time
import gdata.spreadsheet.service

email = 'email@gmail.com'
password = 'pwd'
weight = '180'
# Find this value in the url with 'key=XXX' and copy XXX below
spreadsheet_key = 'pRoiw3us3wh1FyEip46wYtW'
# All spreadsheets have worksheets. I think worksheet #1 by default always
# has a value of 'od6'
worksheet_id = 'Sheet1'

spr_client = gdata.spreadsheet.service.SpreadsheetsService()
spr_client.email = email
spr_client.password = password
spr_client.source = 'Example Spreadsheet Writing Application'
spr_client.ProgrammaticLogin()

# Prepare the dictionary to write
dict = {}
dict['date'] = time.strftime('%m/%d/%Y')
dict['time'] = time.strftime('%H:%M:%S')
dict['weight'] = weight
print dict

entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id)
if isinstance(entry, gdata.spreadsheet.SpreadsheetsList):
  print "Insert row succeeded."
else:
  print "Insert row failed."
</code>```

This is the error is says -

```<code>Traceback (most recent call last):
  File "D:/steve/test.py", line 28, in <module>
    entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id)
  File "C:\Python27\lib\site-packages\gdata\spreadsheet\service.py", line 338, in InsertRow
    converter=gdata.spreadsheet.SpreadsheetsListFromString)
  File "C:\Python27\lib\site-packages\gdata\service.py", line 1235, in Post
    media_source=media_source, converter=converter)
  File "C:\Python27\lib\site-packages\gdata\service.py", line 1346, in PostOrPut
    redirects_remaining - 1, media_source, converter=converter)
  File "C:\Python27\lib\site-packages\gdata\service.py", line 1328, in PostOrPut
    return converter(result_body)
  File "C:\Python27\lib\site-packages\gdata\spreadsheet\__init__.py", line 376, in SpreadsheetsListFromString
    xml_string)
  File "C:\Python27\lib\site-packages\atom\__init__.py", line 92, in optional_warn_function
    return f(*args, **kwargs)
  File "C:\Python27\lib\site-packages\atom\__init__.py", line 126, in CreateClassFromXMLString
    tree = ElementTree.fromstring(xml_string)
  File "<string>", line 124, in XML
ParseError: mismatched tag: line 944, column 4
</code>```

答:
as Alik mentioned above starting from 2015 u need to use oauth2client which you can install by running:

```<code>pip install oauth2client
</code>```

here is a sample code to login:

```<code>import gspread
from oauth2client.service_account import ServiceAccountCredentials

# trying to log in
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope) # u can download the json file from google's api manager
client = gspread.authorize(creds) # authorize access

# defining the sheet that we will work on
sheet = client.open('sheetName').sheet1  # getting a sheet to work on
</code>```

I know its been a year now since you asked your question, but i hope i helped some one else.

Body:
I an wondering is there is a way to write to google spreadsheet using Python.  Found python-gdata-client library,  installed it with all dependencies. Using this code below but it is not working

import time
import gdata.spreadsheet.service

email = 'email@gmail.com'
password = 'pwd'
weight = '180'
# Find this value in the url with 'key=XXX' and copy XXX below
spreadsheet_key = 'pRoiw3us3wh1FyEip46wYtW'
# All spreadsheets have worksheets. I think worksheet #1 by default always
# has a value of 'od6'
worksheet_id = 'Sheet1'

spr_client = gdata.spreadsheet.service.SpreadsheetsService()
spr_client.email = email
spr_client.password = password
spr_client.source = 'Example Spreadsheet Writing Application'
spr_client.ProgrammaticLogin()

# Prepare the dictionary to write
dict = {}
dict['date'] = time.strftime('%m/%d/%Y')
dict['time'] = time.strftime('%H:%M:%S')
dict['weight'] = weight
print dict

entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id)
if isinstance(entry, gdata.spreadsheet.SpreadsheetsList):
  print "Insert row succeeded."
else:
  print "Insert row failed."

This is the error is says -

Traceback (most recent call last):
  File "D:/steve/test.py", line 28, in <module>
    entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id)
  File "C:\Python27\lib\site-packages\gdata\spreadsheet\service.py", line 338, in InsertRow
    converter=gdata.spreadsheet.SpreadsheetsListFromString)
  File "C:\Python27\lib\site-packages\gdata\service.py", line 1235, in Post
    media_source=media_source, converter=converter)
  File "C:\Python27\lib\site-packages\gdata\service.py", line 1346, in PostOrPut
    redirects_remaining - 1, media_source, converter=converter)
  File "C:\Python27\lib\site-packages\gdata\service.py", line 1328, in PostOrPut
    return converter(result_body)
  File "C:\Python27\lib\site-packages\gdata\spreadsheet\__init__.py", line 376, in SpreadsheetsListFromString
    xml_string)
  File "C:\Python27\lib\site-packages\atom\__init__.py", line 92, in optional_warn_function
    return f(*args, **kwargs)
  File "C:\Python27\lib\site-packages\atom\__init__.py", line 126, in CreateClassFromXMLString
    tree = ElementTree.fromstring(xml_string)
  File "<string>", line 124, in XML
ParseError: mismatched tag: line 944, column 4

Body:
as Alik mentioned above starting from 2015 u need to use oauth2client which you can install by running:

pip install oauth2client

here is a sample code to login:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# trying to log in
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope) # u can download the json file from google's api manager
client = gspread.authorize(creds) # authorize access

# defining the sheet that we will work on
sheet = client.open('sheetName').sheet1  # getting a sheet to work on

I know its been a year now since you asked your question, but i hope i helped some one else.


问:
What do chained arrow functions mean in redux?
Looking at the real world example I see this setting up the api middleware:

```<code>export default store => next => action => {
  const callAPI = action[CALL_API]
  if (typeof callAPI === 'undefined') {
    return next(action)
  }
</code>```

What exactly is happening here?  I see that configureStore is importing whatever that is and passing it to applyMiddleware from redux, but what does this kind of statement mean in js?

I assume it's exporting an anonymous function that returns a function that returns a function?  Just tried this:

```<code>var a = b => c => d => {
    console.log('a:', a);
    console.log('b:', b);
    console.log('c:', c);
    console.log('d:', d);
};

a(5)(6)(7);

// outputs b: 5, c: 6, and d: 7
</code>```

答:
Function Specialization

The arrow function notation simplifies currying in JavaScript.

Here it's just a way to do partial applications, and permits to bind arguments to the function at different times, by using Closures instead of Function.prototype.bind.

When you call applyMiddleware during Store creation, Redux will specialize your Middleware with the current Store it's been applied to.

Then it becomes a new specialized function, that only takes two arguments:

next => action

Where next is the next middleware that will be called on the Action. (Just like in Express, which popularized the concept, for request handling)

Timeline

The important thing here is that all these function specializations are done at different times.

store can be bound during Store creation.

next can be bound once it knows the Store it's been bound to, so also during Store creation, but could be updated later.

action is known only when you effectively dispatch an Action, which can happen any time.

The specialized middleware (the one which has been bound to the Store, and is already aware of the Next middleware function) will be reusable, and called for each new dispatched Action.

Functional Programming

These concepts (currying and partial application) come from the Functional Programming world.

Redux relies heavily on this paradigm, and the most important thing in Redux is the sidelining of Side-Effects (especially mutations).

Capturing directly the context of the function, or using a global Store via require, is a side-effect as your function will directly after its declaration be bound to this Store.

Instead Redux uses Currying to permit sort of Dependency Injection, and it results in a stateless function, that can be reused and specialized at runtime.

This way your Middleware is Loosely Coupled to the Store.

Body:
Looking at the real world example I see this setting up the api middleware:

export default store => next => action => {
  const callAPI = action[CALL_API]
  if (typeof callAPI === 'undefined') {
    return next(action)
  }

What exactly is happening here?  I see that configureStore is importing whatever that is and passing it to applyMiddleware from redux, but what does this kind of statement mean in js?

I assume it's exporting an anonymous function that returns a function that returns a function?  Just tried this:

var a = b => c => d => {
    console.log('a:', a);
    console.log('b:', b);
    console.log('c:', c);
    console.log('d:', d);
};

a(5)(6)(7);

// outputs b: 5, c: 6, and d: 7


问:
Providing input for additional authentication using Plink
After logging into the Unix server, it again asks for user's id. I am not able to pass that userid using Plink from JavaScript file. I need to call a shell script placed in the Unix server after logging into the server. Can any one Please help me.

The code looks as below

Plink -l usernameforserverlogin -pw passwrdforserverlogin -batch servername shellscript.sh
```

答:
Plink is a console application. So you can use input redirection to provide an input:</p>

```<code>echo userid | plink -l username -pw password -batch host shellscript.sh
</code>```

Body:
Plink is a console application. So you can use input redirection to provide an input:

echo userid | plink -l username -pw password -batch host shellscript.sh


问:
Typescript - Calling a class exported from another file.
I have a file called searchBar.ts in which contains a init() function that I wish to call in a file called index.ts.

My searchBar.ts file looks like this:

```<code>class searchBar {
    init() {
        console.log('work you C*&*T')
    }
}

export let searchBarClass = new searchBar;
</code>```

I then want to be able to call this function in index.ts. I am currently trying to do this with the below code but init is never found with my intellisense:

```<code>import { searchBarClass } from './modules/searchBar';

class Main {
    searchBarClass.init()
}

let main = new Main();
export {main}
</code>```

Later on I then want to wrap the function in a global function that I'll call in the HTML file.

Let me know your thoughts

答:
If you want to export a class and call the init() method on the object instance:

```<code>export class SearchBar {
    init() {
        console.log('work you C*&*T')
    }
}
</code>```

Then accessing it from another file:

```<code>import { SearchBar } from './modules/searchBar';

export class Main {
    constructor() {
        let searchBar = new SearchBar();
        searchBar.init();
    }
}

let main = new Main();
</code>```

If you want to access the init() function statically:

```<code>export class SearchBar {
    static init() {
        console.log('work you C*&*T')
    }
}
</code>```

Then accessing it from another file:

```<code>import { SearchBar } from './modules/searchBar';

export class Main {
    constructor() {
        SearchBar.init();
    }
}

let main = new Main();
</code>```

Body:
I have a file called searchBar.ts in which contains a init() function that I wish to call in a file called index.ts.

My searchBar.ts file looks like this:

class searchBar {
    init() {
        console.log('work you C*&*T')
    }
}

export let searchBarClass = new searchBar;

I then want to be able to call this function in index.ts. I am currently trying to do this with the below code but init is never found with my intellisense:

import { searchBarClass } from './modules/searchBar';

class Main {
    searchBarClass.init()
}

let main = new Main();
export {main}

Later on I then want to wrap the function in a global function that I'll call in the HTML file.

Let me know your thoughts

Body:
If you want to export a class and call the init() method on the object instance:

export class SearchBar {
    init() {
        console.log('work you C*&*T')
    }
}

Then accessing it from another file:

import { SearchBar } from './modules/searchBar';

export class Main {
    constructor() {
        let searchBar = new SearchBar();
        searchBar.init();
    }
}

let main = new Main();

If you want to access the init() function statically:

export class SearchBar {
    static init() {
        console.log('work you C*&*T')
    }
}

Then accessing it from another file:

import { SearchBar } from './modules/searchBar';

export class Main {
    constructor() {
        SearchBar.init();
    }
}

let main = new Main();


问:
Looping over child selectors
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

```<code><div id="checker">
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
</div>
</code>```

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

```<code>$('#checker').children('checkbox').each( function(){ .... });
</code>```

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC

答:
```<code>$('#checker').children('input [type="checkbox"]').each(
  function(){
    ....
  });
</code>```

Title: Looping over child selectors

Body:
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

$('#checker').children('checkbox').each( function(){ .... });

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC


问:
csv to json with column data that needs to be grouped
I have a CSV file in a format similar to this

```<code>order_id, customer_name, item_1_id, item_1_quantity, Item_2_id, Item_2_quantity, Item_3_id, Item_3_quantity
1,        John,          4,         1,               24,        4,               16,        1
2,        Paul,          8,         3,               41,        1,               33,        1
3,        Andrew,        1,         1,               34,        4,               8,          2
</code>```

I want to export to json, currently I am doing this.

```<code>df = pd.read_csv('simple.csv')
print ( df.to_json(orient = 'records') )
</code>```

And the output is

```<code>[
    {
        "Item_2_id": 24,
        "Item_2_quantity": 4,
        "Item_3_id": 16,
        "Item_3_quantity": 1,
        "customer_name": "John",
        "item_1_id": 4,
        "item_1_quantity": 1,
        "order_id": 1
    },
......
</code>```

However, I would like the output to be

```<code>[
    {
        "customer_name": "John",
        "order_id": 1,
        "items": [
            { "id": 4, "quantity": 1 },
            { "id": 24, "quantity": 4 },
            { "id": 16, "quantity": 1 },
         ]
    },
......
</code>```

Any suggestions on a good way to do this?

In this particular project, there will not be more than 5 times per order

答:
```<code>j = df.set_index(['order_id','customer_name']) \
      .groupby(lambda x: x.split('_')[-1], axis=1) \
      .agg(lambda x: x.values.tolist()) \
      .reset_index() \
      .to_json(orient='records')

import json
</code>```

Beatufied result:

```<code>In [122]: print(json.dumps(json.loads(j), indent=2))
[
  {
    "order_id": 1,
    "customer_name": "John",
    "id": [
      4,
      24,
      16
    ],
    "quantity": [
      1,
      4,
      1
    ]
  },
  {
    "order_id": 2,
    "customer_name": "Paul",
    "id": [
      8,
      41,
      33
    ],
    "quantity": [
      3,
      1,
      1
    ]
  },
  {
    "order_id": 3,
    "customer_name": "Andrew",
    "id": [
      1,
      34,
      8
    ],
    "quantity": [
      1,
      4,
      2
    ]
  }
]
</code>```

Body:
I have a CSV file in a format similar to this

order_id, customer_name, item_1_id, item_1_quantity, Item_2_id, Item_2_quantity, Item_3_id, Item_3_quantity
1,        John,          4,         1,               24,        4,               16,        1
2,        Paul,          8,         3,               41,        1,               33,        1
3,        Andrew,        1,         1,               34,        4,               8,          2

I want to export to json, currently I am doing this.

df = pd.read_csv('simple.csv')
print ( df.to_json(orient = 'records') )

And the output is

[
    {
        "Item_2_id": 24,
        "Item_2_quantity": 4,
        "Item_3_id": 16,
        "Item_3_quantity": 1,
        "customer_name": "John",
        "item_1_id": 4,
        "item_1_quantity": 1,
        "order_id": 1
    },
......

However, I would like the output to be

[
    {
        "customer_name": "John",
        "order_id": 1,
        "items": [
            { "id": 4, "quantity": 1 },
            { "id": 24, "quantity": 4 },
            { "id": 16, "quantity": 1 },
         ]
    },
......

Any suggestions on a good way to do this?

In this particular project, there will not be more than 5 times per order

Body:
j = df.set_index(['order_id','customer_name']) \
      .groupby(lambda x: x.split('_')[-1], axis=1) \
      .agg(lambda x: x.values.tolist()) \
      .reset_index() \
      .to_json(orient='records')

import json

Beatufied result:

In [122]: print(json.dumps(json.loads(j), indent=2))
[
  {
    "order_id": 1,
    "customer_name": "John",
    "id": [
      4,
      24,
      16
    ],
    "quantity": [
      1,
      4,
      1
    ]
  },
  {
    "order_id": 2,
    "customer_name": "Paul",
    "id": [
      8,
      41,
      33
    ],
    "quantity": [
      3,
      1,
      1
    ]
  },
  {
    "order_id": 3,
    "customer_name": "Andrew",
    "id": [
      1,
      34,
      8
    ],
    "quantity": [
      1,
      4,
      2
    ]
  }
]