问:
What’s the best way to load a JSONObject from a json text file?
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

```<code>XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));
</code>```

The output is:

```<code>Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)
</code>```

答:
Another way of doing the same could be using the Gson Class

```<code>String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);
</code>```

This will give an object obtained after parsing the json string to work with.

Body:
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));

The output is:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)

Body:
Another way of doing the same could be using the Gson Class

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.


来源: stackexchange

问:
Google place api: Place Search filter by country
I'm working on Google Place API with Text Search Requests and I'm wondering how to filter results for a specific country. Is there a way?

What I'm trying to do is call the api with results filtered by country and then manage the json result with php.

So, this is a kind of query

```<code>https://maps.googleapis.com/maps/api/place/textsearch/json?query=pizza&sensor=true&key=mykey
</code>```

I wish to add a parameter like &country=us, but it seems it doesn't exists.

Thanks

答:
```<code>for API : country:in

AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
        .setCountry("IN")
        .build();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on Google Place API with Text Search Requests and I'm wondering how to filter results for a specific country. Is there a way?

What I'm trying to do is call the api with results filtered by country and then manage the json result with php.

So, this is a kind of query

https://maps.googleapis.com/maps/api/place/textsearch/json?query=pizza&sensor=true&key=mykey

I wish to add a parameter like &country=us, but it seems it doesn't exists.

Thanks


问:
How do I get basic jQuery tabs to work inside a .Net modal popup?
Really simple question: Am I missing something?  Seems like this should be all that is necessary for the basic setup...  currently I'm getting an un-stylized version (i.e. no tabs, just plain text/html).  So they don't look like tabs and when you click them nothing hides/shows as would be expected with tabs. Do I have to manually hook up javascript to show and hide the contents of the tabs or does the framework do this for me?

Update:

So I tested the code out and
  this works fine for basic tabs.
  However, I need to use this inside a
  .Net modal popup using their "Ajax"
  toolkit.  Essentially this is doing a
  postback which I've noticed tends to
  fight with jQuery.  In the past, I've
  used the jQuery live events, but
  I'm not sure what to bind it to...
  Usually you bind to an event on an
  object, like a click handler for a
  button.  Here, I need to attach the
  tab assignment/binding ( using .tabs()
  ) via a live event but I'm not sure
  which one.  I tried binding to the
  document load event but no luck with
  that:

```<code>$(document).live('load', bind_tabs);
</code>```

Any ideas?

Style sheet and Javascript links included on page:

```<code>https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
</code>```

Added the following line to my stylesheet:

```<code>.ui-tabs .ui-tabs-hide { display: none; }
</code>```

Added the following script to the page:

```<code><script type="text/javascript">
  $(function () {
  $("#tabs2").tabs();
  $("#tabs").tabs();
  });
</script>
</code>```

HTML:

```<code><div id="tabs">
   <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
      <li><a href="#tabs-3">Aenean lacinia</a></li>
   </ul>
   <div id="tabs-1">
      <p>Tab 1 content</p>
   </div>
   <div id="tabs-2">
      <p>Tab 2 content</p>
   </div>
   <div id="tabs-3">
      <p>Tab 3 content</p>
   </div>
</div>
</code>```

Also noticed on the "theming" documentation on the page (http://jqueryui.com/demos/tabs/#theming) that it states the following. Should I manually put in all those styles (like ui-widget) or rely on the framework to do it?

Sample markup with jQuery UI CSS
  Framework classes

```<code><div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs">
   <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
     <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">Nunc tincidunt</a></li>
      <li class="ui-state-default ui-corner-top"><a href="#tabs-2">Proin dolor</a></li>
   <div class="ui-tabs-panel ui-widget-content ui-corner-bottom" id="tabs-1">
      <p>Tab one content goes here.</p>
   </div>
    ...
</div>
</code>```

Note: This is a sample of markup
  generated by the tabs plugin, not
  markup you should use to create a
  tabs. The only markup needed for that
  is

```<code><div id="tabs">
   <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
      <li><a href="#tabs-3">Aenean lacinia</a></li>
   </ul>
   <div id="tabs-1">
      <p>Tab 1 content</p>
   </div>
   <div id="tabs-2">
      <p>Tab 2 content</p>
   </div>
   <div id="tabs-3">
      <p>Tab 3 content</p>
   </div>
</div>
</code>```

答:
Everything looks fine to me. Are you sure you are linking your files in correctly?

http://jsfiddle.net/GwnHq/

ContentLicense: CC BY-SA 2.5

Body:
Really simple question: Am I missing something?  Seems like this should be all that is necessary for the basic setup...  currently I'm getting an un-stylized version (i.e. no tabs, just plain text/html).  So they don't look like tabs and when you click them nothing hides/shows as would be expected with tabs. Do I have to manually hook up javascript to show and hide the contents of the tabs or does the framework do this for me?

Update:

So I tested the code out and
  this works fine for basic tabs.
  However, I need to use this inside a
  .Net modal popup using their "Ajax"
  toolkit.  Essentially this is doing a
  postback which I've noticed tends to
  fight with jQuery.  In the past, I've
  used the jQuery live events, but
  I'm not sure what to bind it to...
  Usually you bind to an event on an
  object, like a click handler for a
  button.  Here, I need to attach the
  tab assignment/binding ( using .tabs()
  ) via a live event but I'm not sure
  which one.  I tried binding to the
  document load event but no luck with
  that:

$(document).live('load', bind_tabs);

Any ideas?

Style sheet and Javascript links included on page:

https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

Added the following line to my stylesheet:

.ui-tabs .ui-tabs-hide { display: none; }

Added the following script to the page:

HTML:

Nunc tincidunt

Proin dolor

Aenean lacinia

Tab 1 content

Tab 2 content

Tab 3 content

Also noticed on the "theming" documentation on the page (http://jqueryui.com/demos/tabs/#theming) that it states the following. Should I manually put in all those styles (like ui-widget) or rely on the framework to do it?

Sample markup with jQuery UI CSS
  Framework classes

Nunc tincidunt

Proin dolor

Tab one content goes here.

    ...

Note: This is a sample of markup
  generated by the tabs plugin, not
  markup you should use to create a
  tabs. The only markup needed for that
  is

Nunc tincidunt

Proin dolor

Aenean lacinia

Tab 1 content

Tab 2 content

Tab 3 content


问:
Structuremap default registry dynamic values
i am trying to inject a string into structuremap registry at run time. i have successfully done it with a static string. like this

```<code>For<TestDAL>().Use<TestDAL>().Ctor<string>("connectionString").Is("randomStringData");
</code>```

but when i am trying to make the string dynamic at runtime i am not able to figure out how to send it, i have tried HttpContext and Session but they are always empty like the example below:

```<code>HttpContext.Current.GetOwinContext().Environment.TryGetValue("dynamicString", out object dynString);

For<TestDAL>().Use<TestDAL>().Ctor<string>("connectionString").Is(dynString);
</code>```

Please anyone has anyidea on how to do this?

答:
You're only evaluating the dynamicString completely upfront. You might need to do it lazy so it's evaluated just in time like so:

```<code>For<TestDAL>().Use<TestDAL>().Ctor<string>("connectionString").Is(() => {
    string dynString = null;

    HttpContext.Current.GetOwinContext()
        .Environment.TryGetValue("dynamicString", out object dynString);

    return dynString;
});
</code>```

Body:
i am trying to inject a string into structuremap registry at run time. i have successfully done it with a static string. like this

For<TestDAL>().Use<TestDAL>().Ctor<string>("connectionString").Is("randomStringData");

but when i am trying to make the string dynamic at runtime i am not able to figure out how to send it, i have tried HttpContext and Session but they are always empty like the example below:

HttpContext.Current.GetOwinContext().Environment.TryGetValue("dynamicString", out object dynString);

For<TestDAL>().Use<TestDAL>().Ctor<string>("connectionString").Is(dynString);

Please anyone has anyidea on how to do this?

Body:
You're only evaluating the dynamicString completely upfront. You might need to do it lazy so it's evaluated just in time like so:

For<TestDAL>().Use<TestDAL>().Ctor<string>("connectionString").Is(() => {
    string dynString = null;

    HttpContext.Current.GetOwinContext()
        .Environment.TryGetValue("dynamicString", out object dynString);

    return dynString;
});


问:
How to remove newly created directory not part of rpm package
I am new to rpm creation. I need to find a way to install/uninstall/upgrade a plugin in jenkins using rpm.I am able to install plugin using rpm , but on un-installation how can I delete new file/directory which was not part of the package.

Suppose my package only deploys xyz.jpi file on server which on server restart creates xyz.jpi and xyz folder . On uninstallation I want to remove both created folders .

答:
you can use the %ghost directive in the %files section; which means "this file/folder does not exist yet, but when it appears it will be mine."

```<code>%files
%ghost %dir /path/to/unexisting/xyz
</code>```

If there will be files present in that directory; I am not sure rpm will remove them. In that case it might be necessary to add another line (to be tested!)

```<code>%ghost /path/to/unexisting/xyz/*
</code>```

more information in the documentation

Body:
you can use the %ghost directive in the %files section; which means "this file/folder does not exist yet, but when it appears it will be mine."

%files
%ghost %dir /path/to/unexisting/xyz

If there will be files present in that directory; I am not sure rpm will remove them. In that case it might be necessary to add another line (to be tested!)

%ghost /path/to/unexisting/xyz/*

more information in the documentation


问:
Virtualenv and anaconda conflict
I've installed Anaconda recently. I have an virtual environment I am using for one of my projects. I try to activate it:

```<code>(vierualenv)Ilyas-Air-4:data_analysis ilyalapan$ source vierualenv/bin/activate
(vierualenv)Ilyas-Air-4:data_analysis ilyalapan$ which python
/anaconda/bin/python
</code>```

But which python returns me anaconda executable. Why could that be?

答:
I've just realized that this happened because my virtualenv was 2.7 environment.

```<code>which python2
</code>```

gave me the right python executable

Title: Virtualenv and anaconda conflict

Body:
I've installed Anaconda recently. I have an virtual environment I am using for one of my projects. I try to activate it:

(vierualenv)Ilyas-Air-4:data_analysis ilyalapan$ source vierualenv/bin/activate
(vierualenv)Ilyas-Air-4:data_analysis ilyalapan$ which python
/anaconda/bin/python

But which python returns me anaconda executable. Why could that be?

Body:
I've just realized that this happened because my virtualenv was 2.7 environment.

which python2

gave me the right python executable


问:
Observable that emit items on demand
I want to create an Observable that will emit items on demand, that means I want a single subscribe to Observable and notify Observable that I need new item based on my request.

This is what I have done using PublishSubject:

```<code>public class RecognizeSubject {

PublishSubject<Bitmap> mSubject;

private Context mContext;
private FaceDetector mFaceDetecor;

public RecognizeSubject(Context mContext) {
    this.mContext = mContext;
    this.mSubject = PublishSubject.create();
}

public void detect(Bitmap btm){
    mSubject.onNext(btm);
}

public Flowable<SinglePhotoId> execute() {
    return mSubject.toFlowable(BackpressureStrategy.DROP)
            .observeOn(Schedulers.newThread())
            .map(bitmap1 -> recognize(bitmap1))
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(disposable -> initialize())
            .doFinally(() -> release());
}

private void initialize() {
    mFaceDetecor = new FaceDetector.Builder(mContext)
            .setTrackingEnabled(false)
            .setLandmarkType(FaceDetector.ALL_LANDMARKS)
            .build();
}

private void release() {
    if (mFaceDetecor != null)
        mFaceDetecor.release();
}

private SinglePhotoId recognize(Bitmap bitmap) {
    //SystemClock.sleep(3000);
   //make hard background work and return SinglePhotoId object
}
</code>```

}

and here is a usage in Activity class:

```<code>private void takeSubjectSnap() {
    if (mSubject == null)
        mSubject = new RecognizeSubject(getBaseContext());

    if (mDisposable == null || mDisposable.isDisposed()) {
        mDisposable = mSubject.execute()
                .subscribe(this::handleDetectionSuccess,
                        this::handleDetectionError,
                        this::handleDetectionCompleted);
    }

    mSnapshotButton.setProgress(true);
    mSubject.detect(myVideoView.getBitmap());
}
</code>```

So basically I subscribe to Flowable object and pass Bitmap object to my Subject class to proceed and return result via Flowable, is that solution right or can produce some memory leaks?

Is there any better solution to send an object to Observable to proceed and return result via a standard onNext() method?

答:
(I'd put this as a comment because this is not an answer but it's too long)

I'm not really sure what is your use case here, and what exactly you're trying to achieve as the thing you described and implemented is little bit different.

What you described is a mechanism that is capable of processing some stuff and requesting new stuff when it's free/capable of processing/etc

What you implemented is a mechanism that is push-based processor processing items depending on data it receives from the clients.

So if the stuff you implemented is working as you want it's fine, but I'd suggest some little changes:

I'd renameexecute method to something else (as it doesn't execute anything)

I'd init disposable with Disposables.disposed() to avoid null check and

I'd rename RecognizeSubject to something else at as right now it's leaking information about it's internal implementation.

I'd make mSubject private and final

I'd get rid of hungarian notation

And I'm not really sure if flowable is appropriate thing in while working with bitmaps, are you sure you need that many bitmaps at once and process all of them (and drop the ones that were not processed?).

Title: Observable that emit items on demand

Body:
I want to create an Observable that will emit items on demand, that means I want a single subscribe to Observable and notify Observable that I need new item based on my request.

This is what I have done using PublishSubject:

public class RecognizeSubject {

PublishSubject<Bitmap> mSubject;

private Context mContext;
private FaceDetector mFaceDetecor;

public RecognizeSubject(Context mContext) {
    this.mContext = mContext;
    this.mSubject = PublishSubject.create();
}

public void detect(Bitmap btm){
    mSubject.onNext(btm);
}

public Flowable<SinglePhotoId> execute() {
    return mSubject.toFlowable(BackpressureStrategy.DROP)
            .observeOn(Schedulers.newThread())
            .map(bitmap1 -> recognize(bitmap1))
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(disposable -> initialize())
            .doFinally(() -> release());
}

private void initialize() {
    mFaceDetecor = new FaceDetector.Builder(mContext)
            .setTrackingEnabled(false)
            .setLandmarkType(FaceDetector.ALL_LANDMARKS)
            .build();
}

private void release() {
    if (mFaceDetecor != null)
        mFaceDetecor.release();
}

private SinglePhotoId recognize(Bitmap bitmap) {
    //SystemClock.sleep(3000);
   //make hard background work and return SinglePhotoId object
}

}

and here is a usage in Activity class:

private void takeSubjectSnap() {
    if (mSubject == null)
        mSubject = new RecognizeSubject(getBaseContext());

    if (mDisposable == null || mDisposable.isDisposed()) {
        mDisposable = mSubject.execute()
                .subscribe(this::handleDetectionSuccess,
                        this::handleDetectionError,
                        this::handleDetectionCompleted);
    }

    mSnapshotButton.setProgress(true);
    mSubject.detect(myVideoView.getBitmap());
}

So basically I subscribe to Flowable object and pass Bitmap object to my Subject class to proceed and return result via Flowable, is that solution right or can produce some memory leaks?

Is there any better solution to send an object to Observable to proceed and return result via a standard onNext() method?


问:
PowerShell select-xml xpath doesn't seem to work
I'm trying to use select-xml to root out a few things from a SharePoint solution.  I have a solution directory that contains a number of features, and rather than open each feature.xml and select names of features by hand and put them in a list, I was hoping to do the equivalent using powershell and select-xml.

My attempt went something like this:

```<code>ls -recurse -filter feature.xml | select-xml "/Feature"
</code>```

and I got nothing, so I tried this:

```<code>ls -recurse -filter feature.xml | select-xml "//*"
</code>```

which seemed to do what it was supposed to do.  I got a list of every XML node in all the feature.xml files in my solution.

I tried XPath expressions like "//Feature" and "Feature", none of which got any results.

It seems to me that my XPath expressions are right, but the behavior of select-xml is a bit bewildering.  Anyone know why this might be happening?

答:
Maybe the issue is with the xml namespace. Try using the -namespace to get the correct xpath query.

Test this by removing the xmlns from a feature.xml file and running your command.

Body:
I'm trying to use select-xml to root out a few things from a SharePoint solution.  I have a solution directory that contains a number of features, and rather than open each feature.xml and select names of features by hand and put them in a list, I was hoping to do the equivalent using powershell and select-xml.

My attempt went something like this:

ls -recurse -filter feature.xml | select-xml "/Feature"

and I got nothing, so I tried this:

ls -recurse -filter feature.xml | select-xml "//*"

which seemed to do what it was supposed to do.  I got a list of every XML node in all the feature.xml files in my solution.

I tried XPath expressions like "//Feature" and "Feature", none of which got any results.

It seems to me that my XPath expressions are right, but the behavior of select-xml is a bit bewildering.  Anyone know why this might be happening?


问:
Error in Code Newbie to Sql
Can you please tell me what is wrong with the code</p>

```<code>CREATE TABLE VISIT
PET_ID NUMBER (25),
VET_ID VARCHAR2(20),
VISIT_DATE DATE,
BASIC_COST NUMBER (8,2),
SYMPTOM VARCHAR2 (80),
TREATMENT VARCHAR2 (25),
);
</code>```

答:
First the opening bracket '(' is missing, ie CREATE TABLE VISIT ( .

Second ',' not required after the last column, ie TREATMENT VARCHAR2 (25).

```<code>CREATE TABLE VISIT (
PET_ID NUMBER (25),
VET_ID VARCHAR2(20),
VISIT_DATE DATE,
BASIC_COST NUMBER (8,2),
SYMPTOM VARCHAR2 (80),
TREATMENT VARCHAR2 (25)
);
</code>```

Title: Error in Code Newbie to Sql

Body:
Can you please tell me what is wrong with the code

CREATE TABLE VISIT
PET_ID NUMBER (25),
VET_ID VARCHAR2(20),
VISIT_DATE DATE,
BASIC_COST NUMBER (8,2),
SYMPTOM VARCHAR2 (80),
TREATMENT VARCHAR2 (25),
);

Body:
First the opening bracket '(' is missing, ie CREATE TABLE VISIT ( .

Second ',' not required after the last column, ie TREATMENT VARCHAR2 (25).

CREATE TABLE VISIT (
PET_ID NUMBER (25),
VET_ID VARCHAR2(20),
VISIT_DATE DATE,
BASIC_COST NUMBER (8,2),
SYMPTOM VARCHAR2 (80),
TREATMENT VARCHAR2 (25)
);


问:
Explaination - Image segmentation using feed forward neural network by clustering algorithm
Image segmentation using feed forward neural network by clustering algorithm.

I know the machine learning algorithms. (which algorithm goes what)

I wanted to know that what the following piece of line implies. Best would be an example. I want to know that how a person will go through this project?

答:
Image segmentation is the act of finding features in an image. Those features can then be analysed by a separate algorithm.

For example, if you had an image of a dog chasing a ball in a park, image segmentation would break up the pixels of the image into features such as the ball, the dog, the sky, ground and any trees. Once you have those features, you can ignore the ones you're not interested in.

Neural networks can be used to perform "k-means" clustering or edge detection to find your features. A feed forward network in this case would be a multi-layer perceptron (MLP).

As an aside, I would not use a feed forward network for this task as there are much simpler algorithms that can perform image segmentation. Instead, neural networks usually act on the result of image segmentation.

References: Wikipedia on Image Segmentation


问:
SQL - Order by time, then text on beginning
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

```<code>TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
</code>```

When I use ORDER BY TimeSched, it returns this result:

```<code>TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day
</code>```

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

```<code>TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
</code>```

答:
Try to make use of the below code :</p>

```<code>    DECLARE @TimeSched TABLE
    (ID INT IDENTITY(1,1),TimeSched VARCHAR(20))

    INSERT INTO @TimeSched
    VALUES
    ('Rest Day'),
    ('11:00 AM - 08:00 PM'),
    ('No Schedule'),
    ('09:00 AM - 06:00 PM'),
    ('10:00 AM - 07:00 PM')

    SELECT * FROM @TimeSched
    ORDER BY
    CASE
        WHEN TimeSched ='Rest Day' THEN 1
        WHEN TimeSched ='No Schedule' THEN 2
        ELSE 3 END
</code>```

Body:
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM

When I use ORDER BY TimeSched, it returns this result:

TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM

Body:
Try to make use of the below code :

    DECLARE @TimeSched TABLE
    (ID INT IDENTITY(1,1),TimeSched VARCHAR(20))

    INSERT INTO @TimeSched
    VALUES
    ('Rest Day'),
    ('11:00 AM - 08:00 PM'),
    ('No Schedule'),
    ('09:00 AM - 06:00 PM'),
    ('10:00 AM - 07:00 PM')

    SELECT * FROM @TimeSched
    ORDER BY
    CASE
        WHEN TimeSched ='Rest Day' THEN 1
        WHEN TimeSched ='No Schedule' THEN 2
        ELSE 3 END


问:
How can I completely remove new Microsoft Visual Studio for Mac?
I recently installed Visual Studio for Mac right after the day it was launched. It consumed 20 gb of my disc space, so I decided to remove it. I went in to the applications folder and moved recently installed components associated with the installation to the trash. But it did not free any space at all. So I searched online and followed the following link for uninstallation: Uninstalling Xamarin

After following the link and entering all the terminal commands, I was only able to free up 10 gb of storage. How do I free up the rest 10 gb of the storage ?

答:
Current version Of MS VS takes 20GB on a macOs drive.

Please read the script to avoid removing shared stuff like Mono, NuGet & Visual Studio Code traces if it is needed by another app on your Mac.

Following script will free 20GB of space. Just put it in "uninstall.sh" file and run via terminal as "sudo ./uninstall.sh" (Do not forget to set to set execute permission on the file):

```<code>#!/bin/bash
# Complete uninstall Microsoft Visual Studio (Xamarin) including Mono and Microsoft NuGet traces:

# Uninstall Xamarin Studio
rm -rf "/Applications/Xamarin Studio.app"
rm -rf "/Applications/Xamarin Profiler.app"
rm -rf "/Applications/Xamarin Workbooks.app"
rm -rf ~/Library/Caches/XamarinStudio-*
rm -rf ~/Library/Logs/XamarinStudio-*
rm -rf ~/Library/Preferences/XamarinStudio-*
rm -rf ~/Library/XamarinStudio-*
rm -rf ~/Library/Caches/Xamarin
rm -rf ~/Library/Caches/VisualStudio
rm -rf ~/Library/Developer/Xamarin
rm -rf ~/Library/Developer/XamarinStudio
rm -rf ~/Library/Developer/VisualStudio
rm -rf ~/Library/Logs/Xamarin
rm -rf ~/Library/Logs/VisualStudio
rm -rf ~/Library/Preferences/Xamarin
rm -rf ~/Library/Preferences/VisualStudio
rm -rf ~/Library/Xamarin
rm -rf ~/Library/MonoAndroid
rm -rf ~/Library/XamarinStudio-*
rm -rf ~/Library/VisualStudio
rm -rf ~/Library/Application\ Support/XamarinStudio-*
rm -rf ~/Library/Application\ Support/VisualStudio
rm -rf ~/.templateengine/Visual\ Studio
rm -rf ~/.share/Xamarin
rm -rf ~/.local/share/Xamarin

sudo rm -f /private/var/db/receipts/com.xamarin.*
sudo rm -f /private/var/db/receipts/xamarin.*

# Uninstall Mono MDK
# You will also want to make sure that there are no other dependencies on Mono
sudo rm -rf /Library/Frameworks/Mono.framework
sudo pkgutil --forget com.xamarin.mono-MDK.pkg
rm -rf ~/.local/share/MonoForAndroid
rm -rf ~/.config/.mono
rm -rf ~/.android

# Uninstall Xamarin.Android
sudo rm -rf /Developer/MonoDroid
sudo rm -rf /Library/Frameworks/Xamarin.Android.framework
sudo pkgutil --forget com.xamarin.android.pkg
rm -rf ~/Library/MonoAndroid

# Uninstall Xamarin.iOS
rm -rf ~/Library/MonoTouch
sudo rm -rf /Library/Frameworks/Xamarin.iOS.framework
sudo rm -rf /Developer/MonoTouch
sudo rm -rf /Developer/MonoAndroid
sudo pkgutil --forget com.xamarin.monotouch.pkg
sudo pkgutil --forget com.xamarin.xamarin-ios-build-host.pkg

## To Uninstall the Xamarin Build Host
 sudo rm -rf "/Applications/Xamarin.iOS Build Host.app"

## To unload and remove the Xamarin Build Host launchd job
 launchctl unload /Library/LaunchAgents/com.xamarin.mtvs.buildserver.plist
sudo rm -f /Library/LaunchAgents/com.xamarin.mtvs.buildserver.plist

# Uninstall Xamarin.Mac
sudo rm -rf /Library/Frameworks/Xamarin.Mac.framework
rm -rf ~/Library/Xamarin.Mac
sudo rm -rf /Library/Frameworks/Xamarin.Interactive.framework

# Uninstall Xamarin Installer
rm -rf ~/Library/Caches/XamarinInstaller/
rm -rf ~/Library/Logs/XamarinInstaller/
rm -rf ~/Library/Preferences/Xamarin/

# Uninstall Microsoft NuGet
rm -rf ~/.local/share/NuGet
rm -rf ~/.config/NuGet
rm -rf ~/.config/.NuGet
rm -rf ~/.NuGet

# Uninstall traces of visual studio code
rm -rf ~/.vscode
</code>```

Body:
Current version Of MS VS takes 20GB on a macOs drive.

Please read the script to avoid removing shared stuff like Mono, NuGet & Visual Studio Code traces if it is needed by another app on your Mac.

Following script will free 20GB of space. Just put it in "uninstall.sh" file and run via terminal as "sudo ./uninstall.sh" (Do not forget to set to set execute permission on the file):

#!/bin/bash
# Complete uninstall Microsoft Visual Studio (Xamarin) including Mono and Microsoft NuGet traces:

# Uninstall Xamarin Studio
rm -rf "/Applications/Xamarin Studio.app"
rm -rf "/Applications/Xamarin Profiler.app"
rm -rf "/Applications/Xamarin Workbooks.app"
rm -rf ~/Library/Caches/XamarinStudio-*
rm -rf ~/Library/Logs/XamarinStudio-*
rm -rf ~/Library/Preferences/XamarinStudio-*
rm -rf ~/Library/XamarinStudio-*
rm -rf ~/Library/Caches/Xamarin
rm -rf ~/Library/Caches/VisualStudio
rm -rf ~/Library/Developer/Xamarin
rm -rf ~/Library/Developer/XamarinStudio
rm -rf ~/Library/Developer/VisualStudio
rm -rf ~/Library/Logs/Xamarin
rm -rf ~/Library/Logs/VisualStudio
rm -rf ~/Library/Preferences/Xamarin
rm -rf ~/Library/Preferences/VisualStudio
rm -rf ~/Library/Xamarin
rm -rf ~/Library/MonoAndroid
rm -rf ~/Library/XamarinStudio-*
rm -rf ~/Library/VisualStudio
rm -rf ~/Library/Application\ Support/XamarinStudio-*
rm -rf ~/Library/Application\ Support/VisualStudio
rm -rf ~/.templateengine/Visual\ Studio
rm -rf ~/.share/Xamarin
rm -rf ~/.local/share/Xamarin

sudo rm -f /private/var/db/receipts/com.xamarin.*
sudo rm -f /private/var/db/receipts/xamarin.*

# Uninstall Mono MDK
# You will also want to make sure that there are no other dependencies on Mono
sudo rm -rf /Library/Frameworks/Mono.framework
sudo pkgutil --forget com.xamarin.mono-MDK.pkg
rm -rf ~/.local/share/MonoForAndroid
rm -rf ~/.config/.mono
rm -rf ~/.android

# Uninstall Xamarin.Android
sudo rm -rf /Developer/MonoDroid
sudo rm -rf /Library/Frameworks/Xamarin.Android.framework
sudo pkgutil --forget com.xamarin.android.pkg
rm -rf ~/Library/MonoAndroid

# Uninstall Xamarin.iOS
rm -rf ~/Library/MonoTouch
sudo rm -rf /Library/Frameworks/Xamarin.iOS.framework
sudo rm -rf /Developer/MonoTouch
sudo rm -rf /Developer/MonoAndroid
sudo pkgutil --forget com.xamarin.monotouch.pkg
sudo pkgutil --forget com.xamarin.xamarin-ios-build-host.pkg

## To Uninstall the Xamarin Build Host
 sudo rm -rf "/Applications/Xamarin.iOS Build Host.app"

## To unload and remove the Xamarin Build Host launchd job
 launchctl unload /Library/LaunchAgents/com.xamarin.mtvs.buildserver.plist
sudo rm -f /Library/LaunchAgents/com.xamarin.mtvs.buildserver.plist

# Uninstall Xamarin.Mac
sudo rm -rf /Library/Frameworks/Xamarin.Mac.framework
rm -rf ~/Library/Xamarin.Mac
sudo rm -rf /Library/Frameworks/Xamarin.Interactive.framework

# Uninstall Xamarin Installer
rm -rf ~/Library/Caches/XamarinInstaller/
rm -rf ~/Library/Logs/XamarinInstaller/
rm -rf ~/Library/Preferences/Xamarin/

# Uninstall Microsoft NuGet
rm -rf ~/.local/share/NuGet
rm -rf ~/.config/NuGet
rm -rf ~/.config/.NuGet
rm -rf ~/.NuGet

# Uninstall traces of visual studio code
rm -rf ~/.vscode


问:
How to add Web Service Response into NSDictionary in objective C, IOS
I am getting response form asp.net web services and when I try to convert that NSData response in NSDictionary format that time it stores nil. Then how to convert it into NSDictionary?
Thanks in Advance

Here is my code:

```<code>  -(void)jsonresponse:(NSMutableString *)json
   {
    NSData *data=[json dataUsingEncoding:NSUTF8StringEncoding];

NSError *error=nil;

NSDictionary *json1=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

tableArray= [NSMutableArray array];
   // menuArray=[NSMutableArray array];

for (NSDictionary *dic in [json1 objectForKey:@"Table"])
{
    [tableArray addObject:@{@"StudentId" : [dic objectForKey:@"StudentId"],
                         @"UserID" : [dic objectForKey:@"UserID"],
                         @"StudentName" : [dic objectForKey:@"StudentName"],
                         @"UserTypeName" : [dic objectForKey:@"UserTypeName"],
                         @"Path" : [dic objectForKey:@"Path"],
                         @"UnreadMessageCount" : [dic objectForKey:@"UnreadMessageCount"],
                         @"LastMessageTime" : [dic objectForKey:@"LastMessageTime"],
                         @"Image" : [dic objectForKey:@"Image"]}];

}

NSLog(@"table Array is==%@",tableArray);

for (NSDictionary *dic in [json1 objectForKey:@"Table1"])
{
    [menuArray addObject:@{@"MenuName":[dic objectForKey:@"MenuName"],
                           @"MenuName1" : [dic objectForKey:@"UserID"],
                           @"Icon" : [dic objectForKey:@"Icon"],
                           @"URL" : [dic objectForKey:@"URL"],
                           @"UserTypeConst" : [dic objectForKey:@"Path"]}];
}
 //   [self performSegueWithIdentifier:@"loginbutton" sender:nil];

NSLog(@"Menu Array is==%@",menuArray);
}
</code>```

Here is my response

```<code>{
"Table": [{
    "StudentId": "755",
    "UserID": "1618",
    "StudentName": "VRITEE SHAH",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "103",
    "LastMessageTime": "12/02/2016 16:52:30",
    "Image": ""
}, {
    "StudentId": "2629",
    "UserID": "5380",
    "StudentName": "NILESH PINGALE",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "68",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2630",
    "UserID": "5386",
    "StudentName": "MEGAN ABRAHANM",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "190",
    "LastMessageTime": "12/07/2016 17:04:06",
    "Image": ""
}, {
    "StudentId": "2828",
    "UserID": "5784",
    "StudentName": "VAIBHAVI JOSHI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "21",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2866",
    "UserID": "5856",
    "StudentName": "ISHITA BACHANI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "2",
    "LastMessageTime": "10/30/2016 10:52:48",
    "Image": ""
}],
"Table1": [{
    "MenuName": "Student Info",
    "MenuName1": "Profile ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/student_info.png ",
    "URL": "StudentProfile ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Calendar ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/calender.png ",
    "URL": "Calendar ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Time Table ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/timetable.png ",
    "URL": "TimeTable ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "View Attendance ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_attendance.png ",
    "URL": "ViewAttendance ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Map View ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/map_view.png ",
    "URL": "MapView ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Alerts & Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/alerts&notification.png ",
    "URL": "AlertsNotification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Transportation Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/transportation_desk.png ",
    "URL": "TransportationDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/notification.png ",
    "URL": "Notification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Principal’s Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/principal_desk.png ",
    "URL": "PrincipalDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Digital Diary ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/digital_diary.png ",
    "URL": "DigitalDiary ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Assignment ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/assignment.png ",
    "URL": "Assignment ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "View Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_bill.png ",
    "URL": "ViewBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Pay Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/pay_bill.png ",
    "URL": "PayBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Online Payment History ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/onlinepayment_history.png ",
    "URL": "OnlinePaymentHistory ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Change Password",
    "MenuName1": "Change Password ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/change_password.png ",
    "URL": "ChangePassword ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Delete User",
    "MenuName1": "Delete User ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/delete.png ",
    "URL": "DeleteUser ",
    "UserTypeConst": "PAR"
}]
</code>```

}

答:
Why You are converting NSMutableString to NSData?

You can Directly convert NSMutableString to NSDictionary.

```<code>NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSLog(@"JSON %@",json1);
</code>```

Try This:

```<code>NSString* string = [[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] stringByReplacingOccurrencesOfString:@"\t" withString:@""] stringByReplacingOccurrencesOfString:@"\0" withString:@""];
data = [string dataUsingEncoding:NSUTF8StringEncoding];
</code>```

Body:
I am getting response form asp.net web services and when I try to convert that NSData response in NSDictionary format that time it stores nil. Then how to convert it into NSDictionary?
Thanks in Advance

Here is my code:

  -(void)jsonresponse:(NSMutableString *)json
   {
    NSData *data=[json dataUsingEncoding:NSUTF8StringEncoding];

NSError *error=nil;

NSDictionary *json1=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

tableArray= [NSMutableArray array];
   // menuArray=[NSMutableArray array];

for (NSDictionary *dic in [json1 objectForKey:@"Table"])
{
    [tableArray addObject:@{@"StudentId" : [dic objectForKey:@"StudentId"],
                         @"UserID" : [dic objectForKey:@"UserID"],
                         @"StudentName" : [dic objectForKey:@"StudentName"],
                         @"UserTypeName" : [dic objectForKey:@"UserTypeName"],
                         @"Path" : [dic objectForKey:@"Path"],
                         @"UnreadMessageCount" : [dic objectForKey:@"UnreadMessageCount"],
                         @"LastMessageTime" : [dic objectForKey:@"LastMessageTime"],
                         @"Image" : [dic objectForKey:@"Image"]}];

}

NSLog(@"table Array is==%@",tableArray);

for (NSDictionary *dic in [json1 objectForKey:@"Table1"])
{
    [menuArray addObject:@{@"MenuName":[dic objectForKey:@"MenuName"],
                           @"MenuName1" : [dic objectForKey:@"UserID"],
                           @"Icon" : [dic objectForKey:@"Icon"],
                           @"URL" : [dic objectForKey:@"URL"],
                           @"UserTypeConst" : [dic objectForKey:@"Path"]}];
}
 //   [self performSegueWithIdentifier:@"loginbutton" sender:nil];

NSLog(@"Menu Array is==%@",menuArray);
}

Here is my response

{
"Table": [{
    "StudentId": "755",
    "UserID": "1618",
    "StudentName": "VRITEE SHAH",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "103",
    "LastMessageTime": "12/02/2016 16:52:30",
    "Image": ""
}, {
    "StudentId": "2629",
    "UserID": "5380",
    "StudentName": "NILESH PINGALE",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "68",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2630",
    "UserID": "5386",
    "StudentName": "MEGAN ABRAHANM",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "190",
    "LastMessageTime": "12/07/2016 17:04:06",
    "Image": ""
}, {
    "StudentId": "2828",
    "UserID": "5784",
    "StudentName": "VAIBHAVI JOSHI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "21",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2866",
    "UserID": "5856",
    "StudentName": "ISHITA BACHANI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "2",
    "LastMessageTime": "10/30/2016 10:52:48",
    "Image": ""
}],
"Table1": [{
    "MenuName": "Student Info",
    "MenuName1": "Profile ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/student_info.png ",
    "URL": "StudentProfile ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Calendar ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/calender.png ",
    "URL": "Calendar ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Time Table ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/timetable.png ",
    "URL": "TimeTable ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "View Attendance ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_attendance.png ",
    "URL": "ViewAttendance ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Map View ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/map_view.png ",
    "URL": "MapView ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Alerts & Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/alerts&notification.png ",
    "URL": "AlertsNotification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Transportation Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/transportation_desk.png ",
    "URL": "TransportationDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/notification.png ",
    "URL": "Notification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Principal’s Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/principal_desk.png ",
    "URL": "PrincipalDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Digital Diary ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/digital_diary.png ",
    "URL": "DigitalDiary ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Assignment ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/assignment.png ",
    "URL": "Assignment ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "View Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_bill.png ",
    "URL": "ViewBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Pay Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/pay_bill.png ",
    "URL": "PayBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Online Payment History ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/onlinepayment_history.png ",
    "URL": "OnlinePaymentHistory ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Change Password",
    "MenuName1": "Change Password ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/change_password.png ",
    "URL": "ChangePassword ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Delete User",
    "MenuName1": "Delete User ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/delete.png ",
    "URL": "DeleteUser ",
    "UserTypeConst": "PAR"
}]

}

Body:
Why You are converting NSMutableString to NSData?

You can Directly convert NSMutableString to NSDictionary.

NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSLog(@"JSON %@",json1);

Try This:

NSString* string = [[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] stringByReplacingOccurrencesOfString:@"\t" withString:@""] stringByReplacingOccurrencesOfString:@"\0" withString:@""];
data = [string dataUsingEncoding:NSUTF8StringEncoding];


问:
How to use QAxWidget browser to open url with WebGl content
I'm using QT 5.8 and trying to load webpage using QAxWidget (set to IE) that displays HTML 5 empty canvas.

```<code>QString url = "https://h3manth.com/demo/canvas/full-page.html";
ui.browser->dynamicCall("Navigate(const QString&)", url);
</code>```

Running the same url directly in IE works fine.
But when running it from my simple QT application I'm getting script error:

And getting the blank view as a result even when pressing 'Yes' in the dialog.

Any ideas for possible solution?

答: Modifying the reg keys as described on msdn: msdn.microsoft.com/en-us/library/ee330730(v=vs.85).asp ensures using the intended IE version for "embedded" browser </p>

Body:
I'm using QT 5.8 and trying to load webpage using QAxWidget (set to IE) that displays HTML 5 empty canvas.

QString url = "https://h3manth.com/demo/canvas/full-page.html";
ui.browser->dynamicCall("Navigate(const QString&)", url);

Running the same url directly in IE works fine.
But when running it from my simple QT application I'm getting script error:

And getting the blank view as a result even when pressing 'Yes' in the dialog.

Any ideas for possible solution?


问:
SQOOP Export failure
I am trying to export a table from HDFS to SQOOP but I am getting java exceptions.
The query I'm using is as follows:

```<code>sqoop export --connect jdbc:mysql://172.31.54.174/Database --driver com.mysql.jdbc.Driver --username user --password userpassword --table accounts --export-dir /user/pri/accounts
</code>```

While execution this query gives me below error:

```<code>17/03/29 07:54:26 INFO mapreduce.Job:  map 0% reduce 0%
17/03/29 07:54:30 INFO mapreduce.Job: Task Id : attempt_1489328678238_4886_m_000002_0, Status : FAILED
Error: java.io.IOException: Can't export data, please check failed map task logs
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:112)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:39)
        at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:146)
        at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
        at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
Caused by: java.lang.RuntimeException: Can't parse input data: '\N'
        at accounts.__loadFromFields(accounts.java:691)
        at accounts.parse(accounts.java:584)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:83)
        ... 10 more
Caused by: java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
        at java.sql.Timestamp.valueOf(Timestamp.java:204)
        at accounts.__loadFromFields(accounts.java:643)
        ... 12 more
</code>```

The file that I am exporting contains data as below :

```<code>1,2008-10-23 16:05:05.0,\N,Donald,Becton,2275 Washburn Street,Oakland,CA,94660,5100032418,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0

2,2008-11-12 03:00:01.0,\N,Donna,Jones,3885 Elliott Street,San Francisco,CA,94171,4150835799,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0
</code>```

I have also created the table accounts and its structure is as follows:

+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| acct_num       | varchar(20) | NO   | PRI |         |       |
| acct_create_dt | datetime    | NO   |     | NULL    |       |
| acc_close_dt   | datetime    | YES  |     | NULL    |       |
| first_name     | varchar(20) | NO   |     | NULL    |       |
| last_name      | varchar(20) | NO   |     | NULL    |       |
| address        | varchar(30) | NO   |     | NULL    |       |
| city           | varchar(20) | NO   |     | NULL    |       |
| state          | varchar(20) | NO   |     | NULL    |       |
| zipcode        | varchar(20) | NO   |     | NULL    |       |
| phone_number   | varchar(20) | YES  |     | NULL    |       |
| created        | datetime    | NO   |     | NULL    |       |
| modified       | datetime    | NO   |     | NULL    |       |
+----------------+-------------+------+-----+---------+-------+

I am also attaching a screenshot of the error.

答: Add --input-null-string '\\N' --input-null-non-string '\\N' in your sqoop export command.

Title: SQOOP Export failure

Body:
I am trying to export a table from HDFS to SQOOP but I am getting java exceptions.
The query I'm using is as follows:

sqoop export --connect jdbc:mysql://172.31.54.174/Database --driver com.mysql.jdbc.Driver --username user --password userpassword --table accounts --export-dir /user/pri/accounts

While execution this query gives me below error:

17/03/29 07:54:26 INFO mapreduce.Job:  map 0% reduce 0%
17/03/29 07:54:30 INFO mapreduce.Job: Task Id : attempt_1489328678238_4886_m_000002_0, Status : FAILED
Error: java.io.IOException: Can't export data, please check failed map task logs
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:112)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:39)
        at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:146)
        at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
        at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
Caused by: java.lang.RuntimeException: Can't parse input data: '\N'
        at accounts.__loadFromFields(accounts.java:691)
        at accounts.parse(accounts.java:584)
        at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:83)
        ... 10 more
Caused by: java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
        at java.sql.Timestamp.valueOf(Timestamp.java:204)
        at accounts.__loadFromFields(accounts.java:643)
        ... 12 more

The file that I am exporting contains data as below :

1,2008-10-23 16:05:05.0,\N,Donald,Becton,2275 Washburn Street,Oakland,CA,94660,5100032418,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0

2,2008-11-12 03:00:01.0,\N,Donna,Jones,3885 Elliott Street,San Francisco,CA,94171,4150835799,2014-03-18 13:29:47.0,2014-03-18 13:29:47.0

I have also created the table accounts and its structure is as follows:

+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| acct_num       | varchar(20) | NO   | PRI |         |       |
| acct_create_dt | datetime    | NO   |     | NULL    |       |
| acc_close_dt   | datetime    | YES  |     | NULL    |       |
| first_name     | varchar(20) | NO   |     | NULL    |       |
| last_name      | varchar(20) | NO   |     | NULL    |       |
| address        | varchar(30) | NO   |     | NULL    |       |
| city           | varchar(20) | NO   |     | NULL    |       |
| state          | varchar(20) | NO   |     | NULL    |       |
| zipcode        | varchar(20) | NO   |     | NULL    |       |
| phone_number   | varchar(20) | YES  |     | NULL    |       |
| created        | datetime    | NO   |     | NULL    |       |
| modified       | datetime    | NO   |     | NULL    |       |
+----------------+-------------+------+-----+---------+-------+

I am also attaching a screenshot of the error.


问:
Surrogate key in Oracle DB best practices
I have a few systems and I need to import data from these systems into a common table. But ID is unique only within source system. So I need to create my own primary key to uniquely identify this data in the target table.

What is best practice to resolve the problem? I don't want to create primary key  as character and I don't want to generate an ID  for instance by adding 1000000000. Concatenation with name of system will build character data type. Do you have an idea or some solution?

Thanks for help.

答:
Primary keys created with concatenation is not good practice, you are right. It will bring you problems in the future too find out and resolve the keys.
The best practice I think its to create the key which consists of 2 attributes like SYSTEMID , ID there ID you can keep old ID from system, the pair of 2 attributes gives you unique PK.</p>


问:
white space in filename python 3.4.2
I have created this small prog to search all PDF's in a directory, determine if they are searchable or not and then move them to the appropriate directory.

I am new to Python and it is probably not the best way but it does work until the file name has White Space in it and I get the following returned.

Any help would be appreciated.

```<code>>>> os.system("pdffonts.exe " + pdfFile + "> output.txt")
99

import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory
numFiles = len(fileDir) # Lenght of list
startFile = 0 # Counter variable
seekWord = "TrueType"
while startFile < numFiles:
    pdfFile=fileDir[startFile]
    os.system("pdffonts.exe " + pdfFile + "> output.txt")
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else: shutil.move(pdfFile, "OCR")
    startFile = startFile + 1
</code>```

答:
os.system() uses the shell to execute your command. You'd have to quote your filename for the shell to recognise spaces as part of the file, you could do so with the shlex.quote() function:

```<code>os.system("pdffonts.exe " + shlex.quote(pdfFile) + "> output.txt")
</code>```

However, there is no reason at all to use os.system() and the shell. You should use the subprocess.run() function and configure that to pass back the output without using redirection or a shell:

```<code>import subprocess

seekWord = b"TrueType"
for pdfFile in fileDir:
    result = subprocess.run(["pdffonts.exe", pdfFile], stdout=subprocess.PIPE)
    fileContent = result.stdout
    if seekWord in fileContent:
        # ...
</code>```

Because pdfFile is passed to pdffonts.exe directly there is no need to worry about a shell parsing and whitespace no longer matters.

Note that I changed seekWord to be a bytes literal instead as result.stdout is a bytes value (no need to try to decode the result to Unicode here).

Title: white space in filename python 3.4.2

Body:
I have created this small prog to search all PDF's in a directory, determine if they are searchable or not and then move them to the appropriate directory.

I am new to Python and it is probably not the best way but it does work until the file name has White Space in it and I get the following returned.

Any help would be appreciated.

>>> os.system("pdffonts.exe " + pdfFile + "> output.txt")
99

import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory
numFiles = len(fileDir) # Lenght of list
startFile = 0 # Counter variable
seekWord = "TrueType"
while startFile < numFiles:
    pdfFile=fileDir[startFile]
    os.system("pdffonts.exe " + pdfFile + "> output.txt")
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else: shutil.move(pdfFile, "OCR")
    startFile = startFile + 1

Body:
os.system() uses the shell to execute your command. You'd have to quote your filename for the shell to recognise spaces as part of the file, you could do so with the shlex.quote() function:

os.system("pdffonts.exe " + shlex.quote(pdfFile) + "> output.txt")

However, there is no reason at all to use os.system() and the shell. You should use the subprocess.run() function and configure that to pass back the output without using redirection or a shell:

import subprocess

seekWord = b"TrueType"
for pdfFile in fileDir:
    result = subprocess.run(["pdffonts.exe", pdfFile], stdout=subprocess.PIPE)
    fileContent = result.stdout
    if seekWord in fileContent:
        # ...

Because pdfFile is passed to pdffonts.exe directly there is no need to worry about a shell parsing and whitespace no longer matters.

Note that I changed seekWord to be a bytes literal instead as result.stdout is a bytes value (no need to try to decode the result to Unicode here).


问:
Bundling an Angular 2 application in a subfolder of an ASP.NET project
I have an Angular 2 application in a subfolder of an ASP.NET project, and would like to bundle the Angular 2 application using the techniques from How to bundle an Angular app for production

The recommended approach there is to set up a project using Angular CLI. However I am having some trouble using that approach since it makes some assumptions about the project structure.

Assuming that the Angular 2 application is located in the subfolder /Angular2App/ it seems Angular CLI would like the index.html to be located in /Angular2App/src/, and when bundling the result is located in /Angular2App/dist/ and all references there from that folder's index.html assume that bundles are located at /.

However I would simply like the Angular 2 application to be available at /Angular2App/.

Any ideas as to how I can configure Angular CLI in this way?

答:
You should set deployUrl when you build your angular application and then all path variables will have prefix /Angular2App/. For example;

```<code>ng build --deployUrl "/Angular2App/"
</code>```

Body:
You should set deployUrl when you build your angular application and then all path variables will have prefix /Angular2App/. For example;

ng build --deployUrl "/Angular2App/"


问:
getElementByTagName(a) for autoscroll
What I have now is:

```<code>var a = document.getElementsByTagName('a');
</code>```

I use this to get all elements with an 'a' and when I scroll it autoscrolls to the next 'a' element.

The problem with that is that I also use links (that use an a href="") so sometimes it scrolls to a link instead of an . Is their anyway to fix this? Like:

```<code>var a = document.getElementsByTagName('a name=""');
</code>```

(this one doesnt work)

If full code is needed I will add it below, but its probably not needed.

```<code>(function () {
    var delay = false;

    $(document).on('mousewheel DOMMouseScroll', function (event) {
        event.preventDefault();
        if (delay) return;

        delay = true;
        setTimeout(function () {
            delay = false
        }, 800);

        var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;

        var a = document.getElementsByTagName('a');
        if (wd < 0) {
            for (var i = 0; i < a.length; i++) {
                var t = a[i].getClientRects()[0].top;
                if (t >= window.innerHeight * 0.95) break;
            }
        }
        else {
            for (var i = a.length - 1; i >= 0; i--) {
                var t = a[i].getClientRects()[0].top;
                if (t < -window.innerHeight * 0.5) break;
            }
        }
        $('html,body').animate({
            scrollTop: a[i].offsetTop
        }, 800);
    });
})();
</code>```

答:
Try with   querySelectorAll()

```<code>document.querySelectorAll("a[name='examplename']");
</code>```

find a empty

```<code>document.querySelectorAll("a[name='']");
</code>```

Title: getElementByTagName(a) for autoscroll

Body:
What I have now is:

var a = document.getElementsByTagName('a');

I use this to get all elements with an 'a' and when I scroll it autoscrolls to the next 'a' element.

The problem with that is that I also use links (that use an a href="") so sometimes it scrolls to a link instead of an . Is their anyway to fix this? Like:

var a = document.getElementsByTagName('a name=""');

(this one doesnt work)

If full code is needed I will add it below, but its probably not needed.

(function () {
    var delay = false;

    $(document).on('mousewheel DOMMouseScroll', function (event) {
        event.preventDefault();
        if (delay) return;

        delay = true;
        setTimeout(function () {
            delay = false
        }, 800);

        var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;

        var a = document.getElementsByTagName('a');
        if (wd < 0) {
            for (var i = 0; i = window.innerHeight * 0.95) break;
            }
        }
        else {
            for (var i = a.length - 1; i >= 0; i--) {
                var t = a[i].getClientRects()[0].top;
                if (t < -window.innerHeight * 0.5) break;
            }
        }
        $('html,body').animate({
            scrollTop: a[i].offsetTop
        }, 800);
    });
})();

Body:
Try with   querySelectorAll()

document.querySelectorAll("a[name='examplename']");

find a empty

document.querySelectorAll("a[name='']");


问:
Cast Enumeration Value to Integer in Delphi
Is it possible to cast/convert an Enumeration Value to Integer in Delphi?

If yes, then how?

答:
This is called out explicitly at the documentation for enumerated types:

Several predefined functions operate on ordinal values and type identifiers. The most important of them are summarized below.

```
| Function |                       Parameter                       |                      Return value | Remarks                                           |
|----------|:-----------------------------------------------------:|----------------------------------:|---------------------------------------------------|
| Ord      |                   Ordinal expression                  |  Ordinality of expression's value | Does not take Int64 arguments.                    |
| Pred     |                   Ordinal expression                  | Predecessor of expression's value |                                                   |
| Succ     |                   Ordinal expression                  |   Successor of expression's value |                                                   |
| High     | Ordinal type identifier or   variable of ordinal type | Highest value in type             | Also operates on short-string   types and arrays. |
| Low      | Ordinal type identifier or   variable of ordinal type | Lowest value in type              | Also operates on short-string   types and arrays. |
```

Body:
This is called out explicitly at the documentation for enumerated types:

Several predefined functions operate on ordinal values and type identifiers. The most important of them are summarized below.

| Function |                       Parameter                       |                      Return value | Remarks                                           |
|----------|:-----------------------------------------------------:|----------------------------------:|---------------------------------------------------|
| Ord      |                   Ordinal expression                  |  Ordinality of expression's value | Does not take Int64 arguments.                    |
| Pred     |                   Ordinal expression                  | Predecessor of expression's value |                                                   |
| Succ     |                   Ordinal expression                  |   Successor of expression's value |                                                   |
| High     | Ordinal type identifier or   variable of ordinal type | Highest value in type             | Also operates on short-string   types and arrays. |
| Low      | Ordinal type identifier or   variable of ordinal type | Lowest value in type              | Also operates on short-string   types and arrays. |


问:
Building client api for integration within a react project
I'm wondering what is the most efficient way to build an API client, to integrate that client in my react project.

Questions are :

1 Do i need to just develop a basic client api using fetch or await/sync ?
2 Coupling with redux, using reducers, any method or best practices ?
3 Accessing env varibale for setting API_URL depending on environnement

Tools used : react-scripts for now.

答:
1 Do i need to just develop a basic client api using fetch or await/sync ?

Yes.  Use the http framework of your choice.  JQuery, fetch, axios, whatever.  I won't go into any more detail on this one because it's prone to opinion and won't go any constructive.

2 Coupling with redux, using reducers, any method or best practices ?

There are quite a few redux middlewares out there for handling API calls (or more generally async actions).  redux-thunk is one of most widely used and easiest to understand and it can also be used to inject your API into you action creators.  redux-saga is another good option, but is more complicated than thunk.

3 Accessing env varibale for setting API_URL depending on environnement

This isn't my forte, so there will be a better way to do this, but I've used a seperate script ("configuration.js" generally) that has a templated variable which I replace with the env variable's value before startup and link to it with a script tag in the html.  How you deploy might make this easier or harder.  I generally deploy a docker container so running a few extra commands on startup is not difficult.


问:
can't open my oracle database in a browser
Excuse me but I am new in oracle 11g. Here is my problem: I finished creating my database with the assistant dbca. In the end it gives me a link with which I can try to open my Database on a browser but when I try anything. I'm lost pardon help me</p>

答:
When Oracle database is installed, it is accessed by many ways most commonly using sqlplus utility from command prompt. Other way around you are asking it to open in a browser! right it could't be ,oracle provides OEM usually named as dbconsole.
check from command prompt

emctl dbconsole status

emctl dbconsole start

then find the link for dbconsole link which is like as following
https://localhost:1158/em

openning this will as you credentials , hope so it will work!


问:
How to break powershell script execution on first error?
I am using a PowerShell script that completes 5 different interdependent tasks sequentially. I want the script to stop execution as soon as it hits a catch block and send an email. Also, this script executes a console app. How do I stop execution of the PowerShell script in case of a console exception? I am logging console exceptions using the -RedirectStandardError parameter.

答:
Stopping execution in the catch block is accomplished by using the Break keyword, this should be added last, e.g.:

```<code>    Catch
{
    Send-MailMessage -From ExpensesBot@MyCompany.Com -To WinAdmin@MyCompany.Com -Subject "HR File Read Failed!" -SmtpServer EXCH01.AD.MyCompany.Com
    Break
}
</code>```

If you want to catch non-terminating errors as well, you'll need:

```<code>-ErrorAction Stop
</code>```

at the end of your commandlet (or set it as a preference / session setting)

https://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell

Body:
Stopping execution in the catch block is accomplished by using the Break keyword, this should be added last, e.g.:

    Catch
{
    Send-MailMessage -From ExpensesBot@MyCompany.Com -To WinAdmin@MyCompany.Com -Subject "HR File Read Failed!" -SmtpServer EXCH01.AD.MyCompany.Com
    Break
}

If you want to catch non-terminating errors as well, you'll need:

-ErrorAction Stop

at the end of your commandlet (or set it as a preference / session setting)

https://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell


问:
AttributeError: 'bool' object has no attribute 'pop' - Odoo v8 to Odoo v10 community
I have this method, which is a button:

```<code>@api.multi
def search_partner_seniat(self):
    """ Check vat of the partner and update iva rate
    """
    self.ensure_one()
    vat = self.vat.upper()
    res = {
        'name': _('The requested contributor does not exist'),
        'vat_subjected': False,
        'vat': vat,
        'wh_iva_agent': False,
        'wh_iva_rate': 0.0
    }

    if 'VE' in vat:
        vat = vat[2:]

    # assumption: both methods in new api style
    if self.env['res.partner'].check_vat_ve(vat):
        res = self.env['seniat.url']._dom_giver(vat)
    self.write(res)

    return {
        'type': 'ir.actions.act_window',
        'res_model': 'search.info.partner.seniat',
        'view_mode': 'form',
        'view_type': 'form',
        'res_id': self.id,
        'views': [(False, 'form')],
        'target': 'new',
    }
</code>```

It should return the NIF of a res.partner, bt every time I click on it, it throws me this:

```<code>Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 866, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 681, in call_kw
return call_kw_multi(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 672, in call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/search_info_partner_seniat.py", line 65, in search_partner_seniat
self.write(res)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 3518, in write
vals.pop(field, None)
AttributeError: 'bool' object has no attribute 'pop'
</code>```

The error comes here:

```<code>    if self.env['res.partner'].check_vat_ve(vat):
        res = self.env['seniat.url']._dom_giver(vat)
    self.write(res)
</code>```

I don't know if these two models might be the cause, they are working fine as I recall, on partner:

```<code>@api.model
def check_vat_ve(self, vat): #, context=None
    """ Check Venezuelan VAT number, locally called RIF.
    RIF: JXXXXXXXXX RIF VENEZOLAN
         IDENTIFICATION CARD: VXXXXXXXXX
         FOREIGN IDENTIFICATION CARD: EXXXXXXXXX
    """

    #if context is None:
        #context = {}
    if re.search(r'^[VJEGP][0-9]{9}$', vat):
        return True
    if re.search(r'^([VE][0-9]{1,8}|[D][0-9]{9})$', vat):
        return True
    return False
</code>```

On seniat_url:

```<code>@api.multi
def _dom_giver(self, vat):
    """ Check and validates that the vat is a passport,
    id or rif, to send information to SENIAT and returns the
    partner info that provides.
    """
    #if context is None:
        #context = {}
    name = ''
    url_seniat = ''

    url_obj = self.search([], limit=1) #self.browse(self.search([]))#[0] #(cr, uid, self.search(cr, uid, []))[0]
    #url1 = url_obj.name + '%s' %(value or '')
    #url2 = url_obj.url_seniat + '%s' %(value or '')
    if url_obj.name:
        name = url_obj.name

    if url_obj.url_seniat:
        url_seniat = url_obj.url_seniat
    url1 = name + '%s'
    url2 = url_seniat + '%s'
    vat = self._validate_rif(vat) #cr, uid, vat, context=None
    if vat:
        return self._get_rif(vat, url1, url2) #cr, uid, vat, url1, url2, context=context
    else:
        return False
</code>```

Any ideas?

These are methods migrated from v8 to v10 community.

答:
on the write you should define which fields you want to write the value to.
so res must be a dictionary. When you replace that dictionary for something else like the False from your method call it won't be able to write that as a dictionary.

I suggest that you use res.update({'dom' : self.env['seniat.url']._dom_giver(vat) })
replace 'dom' with the variable you'd like to set

if the result could also be a dict you could use the following:

```<code>update_vals = self.env['seniat.url']._dom_giver(vat)
if update_vals:
    res.update(update_vals)
</code>```

Body:
I have this method, which is a button:

@api.multi
def search_partner_seniat(self):
    """ Check vat of the partner and update iva rate
    """
    self.ensure_one()
    vat = self.vat.upper()
    res = {
        'name': _('The requested contributor does not exist'),
        'vat_subjected': False,
        'vat': vat,
        'wh_iva_agent': False,
        'wh_iva_rate': 0.0
    }

    if 'VE' in vat:
        vat = vat[2:]

    # assumption: both methods in new api style
    if self.env['res.partner'].check_vat_ve(vat):
        res = self.env['seniat.url']._dom_giver(vat)
    self.write(res)

    return {
        'type': 'ir.actions.act_window',
        'res_model': 'search.info.partner.seniat',
        'view_mode': 'form',
        'view_type': 'form',
        'res_id': self.id,
        'views': [(False, 'form')],
        'target': 'new',
    }

It should return the NIF of a res.partner, bt every time I click on it, it throws me this:

Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 866, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 681, in call_kw
return call_kw_multi(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 672, in call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/search_info_partner_seniat.py", line 65, in search_partner_seniat
self.write(res)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/models.py", line 3518, in write
vals.pop(field, None)
AttributeError: 'bool' object has no attribute 'pop'

The error comes here:

    if self.env['res.partner'].check_vat_ve(vat):
        res = self.env['seniat.url']._dom_giver(vat)
    self.write(res)

I don't know if these two models might be the cause, they are working fine as I recall, on partner:

@api.model
def check_vat_ve(self, vat): #, context=None
    """ Check Venezuelan VAT number, locally called RIF.
    RIF: JXXXXXXXXX RIF VENEZOLAN
         IDENTIFICATION CARD: VXXXXXXXXX
         FOREIGN IDENTIFICATION CARD: EXXXXXXXXX
    """

    #if context is None:
        #context = {}
    if re.search(r'^[VJEGP][0-9]{9}$', vat):
        return True
    if re.search(r'^([VE][0-9]{1,8}|[D][0-9]{9})$', vat):
        return True
    return False

On seniat_url:

@api.multi
def _dom_giver(self, vat):
    """ Check and validates that the vat is a passport,
    id or rif, to send information to SENIAT and returns the
    partner info that provides.
    """
    #if context is None:
        #context = {}
    name = ''
    url_seniat = ''

    url_obj = self.search([], limit=1) #self.browse(self.search([]))#[0] #(cr, uid, self.search(cr, uid, []))[0]
    #url1 = url_obj.name + '%s' %(value or '')
    #url2 = url_obj.url_seniat + '%s' %(value or '')
    if url_obj.name:
        name = url_obj.name

    if url_obj.url_seniat:
        url_seniat = url_obj.url_seniat
    url1 = name + '%s'
    url2 = url_seniat + '%s'
    vat = self._validate_rif(vat) #cr, uid, vat, context=None
    if vat:
        return self._get_rif(vat, url1, url2) #cr, uid, vat, url1, url2, context=context
    else:
        return False

Any ideas?

These are methods migrated from v8 to v10 community.

Body:
on the write you should define which fields you want to write the value to.
so res must be a dictionary. When you replace that dictionary for something else like the False from your method call it won't be able to write that as a dictionary.

I suggest that you use res.update({'dom' : self.env['seniat.url']._dom_giver(vat) })
replace 'dom' with the variable you'd like to set

if the result could also be a dict you could use the following:

update_vals = self.env['seniat.url']._dom_giver(vat)
if update_vals:
    res.update(update_vals)


问:
cassandra getendpoints with partition key has space
my partition keys are id(int) and name(text).
Below command works fine until there is no space in name(text).
nodetool getendpoints test testtable2 1:aaa;

if am using
nodetool getendpoints test testtable2 3:aac cc;
it throws an error as :nodetool: getendpoints requires keyspace, table and partition key arguments
See 'nodetool help' or 'nodetool help '.

i got token by executing
SELECT id,name, token(id,name) FROM test.testtable2 where name='aac cc'AND id=3;
and tried to search
nodetool getendpoints test testtable2 -7072928299163215694;
error: For input string: "-7072928299163215694"
-- StackTrace --
java.lang.NumberFormatException: For input string: "-7072928299163215694"

how can i search if partition key (name) has space?

答:
Which Cassandra version you are using.

I have tested it from Cassandra 2.x and Cassandra 3.x version. It is working properly.

```
root@cqlsh:test_db> SELECT token(name) from test_temp ;

 system.token(name)
---------------------
 -907920378987128470

nodetool getendpoints test_db test_temp -907920378987128470;
192.168.8.52

```

Updated Answer: Got the issue

Issue is generated for when 1st part of partition key is int.

```
CREATE TABLE test6 (
    age int PRIMARY KEY,
    name text
);

bin/nodetool getendpoints test test6 -7072928299163215694
```

```<code>error: For input string: "-7072928299163215694"java.lang.NumberFormatException: For input string:"-
7072928299163215694"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)
</code>```

But works properly for below input

```
bin/nodetool getendpoints test test6 -7072
127.0.0.1
```

From DataStax Doc:

Provides the end points that own the partition key. The partitioner returns a token for the key. Cassandra will return an endpoint whether or not data exists on the identified node for that token.
    ** key is the partition key of the end points you want to get.

nodetool getendpoints actually takes the value of the partition key as input. In this case '-7072928299163215694' it is parsing it as an Integer thus end up thowing exception. It is working for long or String (it is taking '-7072928299163215694' value as a String) cause it has taken this as value of the key not actual token. It is not parsing tokens. So providing tokens as an input will not work.

getendpoints generates tokens from the value of the key and provide you the endpoints (nodes) the key is residing.

Please check this link:
What node does Cassandra store data on?

A patch has been provided for this:

https://issues.apache.org/jira/browse/CASSANDRA-4551

Hope this helps.

Body:
Which Cassandra version you are using.

I have tested it from Cassandra 2.x and Cassandra 3.x version. It is working properly.

root@cqlsh:test_db> SELECT token(name) from test_temp ;

 system.token(name)
---------------------
 -907920378987128470

nodetool getendpoints test_db test_temp -907920378987128470;
192.168.8.52

Updated Answer: Got the issue

Issue is generated for when 1st part of partition key is int.

CREATE TABLE test6 (
    age int PRIMARY KEY,
    name text
);

bin/nodetool getendpoints test test6 -7072928299163215694

error: For input string: "-7072928299163215694"java.lang.NumberFormatException: For input string:"-
7072928299163215694"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)

But works properly for below input

bin/nodetool getendpoints test test6 -7072
127.0.0.1

From DataStax Doc:

Provides the end points that own the partition key. The partitioner returns a token for the key. Cassandra will return an endpoint whether or not data exists on the identified node for that token.
    ** key is the partition key of the end points you want to get.

nodetool getendpoints actually takes the value of the partition key as input. In this case '-7072928299163215694' it is parsing it as an Integer thus end up thowing exception. It is working for long or String (it is taking '-7072928299163215694' value as a String) cause it has taken this as value of the key not actual token. It is not parsing tokens. So providing tokens as an input will not work.

getendpoints generates tokens from the value of the key and provide you the endpoints (nodes) the key is residing.

Please check this link:
What node does Cassandra store data on?

A patch has been provided for this:

https://issues.apache.org/jira/browse/CASSANDRA-4551

Hope this helps.


问:
SQLAlchemy Falcon Class error
I am trying to set up an API using Falcon and SQLAlchemy using a postgresql database. Using gunicorn to start the API

I am getting the following error when trying to access /v1/users.

I tried to browse the SQLAlchemy documentation but could not find any working solution.

Thanks

```<code>[2017-03-15 10:20:26 +0100] [20516] [ERROR] Error handling request /v1/users
    Traceback (most recent call last):
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 135, in handle
        self.handle_request(listener, req, client, addr)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
        respiter = self.wsgi(environ, resp.start_response)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/falcon/api.py", line 209, in __call__
        responder(req, resp, **params)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/app/api/v1/users.py", line 50, in on_get
        users = session.query(User).all()
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
        return getattr(self.registry(), name)(*args, **kwargs)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1330, in query
        return self._query_cls(entities, self, **kwargs)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 139, in __init__
        self._set_entities(entities)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 148, in _set_entities
        entity_wrapper(self, ent)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 3947, in __init__
        "expected - got '%r'" % (column, )
    sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '<function User at 0x1040216a8>'
</code>```

My projects files

main.py

```<code>import falcon
from app.api.v1 import users
from app.middleware import DatabaseSessionManager
from app.database import db_session, init_session
from app.api.common import base

class App(falcon.API):

    def __init__(self,*args, **kwargs):
        super(App, self).__init__(*args, **kwargs)
        self.add_route('/',base.BaseResource())
        self.add_route('/v1/users',users.Collection())

init_session()
mdlw = [DatabaseSessionManager(db_session)]
application = App(middleware=mdlw)
</code>```

session.py

```<code>import sqlalchemy.orm.scoping as scoping
from sqlalchemy.exc import SQLAlchemyError

from app import config

class DatabaseSessionManager(object):
    def __init__(self, db_session):
        self._session_factory = db_session
        self._scoped = isinstance(db_session, scoping.ScopedSession)

    def process_request(self, req, res, resource=None):
        req.context['session'] = self._session_factory

    def process_response(self, req, res, resource=None):
        session = req.context['session']

        if config.DB_AUTOCOMMIT:
            try:
                session.commit()
            except SQLAlchemyError as ex:
                session.rollback()

        if self._scoped:
            session.remove()
        else:
            session.close()
</code>```

database init.py

```<code>from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import psycopg2
from app import config

db_session = scoped_session(sessionmaker())
engine = create_engine('postgresql+psycopg2://xxxxx@localhost/falcon_api')

def init_session():
    db_session.configure(bind=engine)
</code>```

user.py

```<code>from sqlalchemy import Column
from sqlalchemy import String, Integer,Text
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

def User(Base):
    __tablename__ = 'user'

    id = Column('id', UUID, primary_key=True)
    firstname = Column('firstname', String)
    lastname = Column('lastname', String)

    #It tells python how to print the class, used for debugging
    def __repr__(self):
        return "<User(id='%s', name='%s', lastname='%s')>"% \
            (self.id, self.firstname, self.lastname)

    def __init__(self, id , firstname, lastname):
        self.id = id
        self.firstname = firstname
        self.lastname = lastname
</code>```

api/v1/users.py

```<code>import falcon
import json
from sqlalchemy.ext.declarative import declarative_base
try:
    from collections import OrderedDict
except ImportError:
    OrderedDict = dict
from app.models import User
class Collection():
    """
    Handle for endpoint: /v1/users
    """

    def to_json(self, body_dict):
        return json.dumps(body_dict)

    def on_error(self, resp, error=None):
        resp.status = error['status']
        meta = OrderedDict()
        meta['code'] = error['code']
        meta['message'] = error['message']

        obj = OrderedDict()
        obj['meta'] = meta
        resp.body = self.to_json(obj)

    def on_success(self, resp, data=None):
        resp.status = falcon.HTTP_200
        meta = OrderedDict()
        meta['code'] = 200
        meta['message'] = 'OK'

        obj = OrderedDict()
        obj['meta'] = meta
        obj['data'] = data
        resp.body = self.to_json(obj)

    def on_get(self, req, resp):
        session = req.context['session']

        #Bugging here
        users = session.query(User).all()
</code>```

答:
I have faced same problem..It got fixed in my case for the following changes..
instead session.remove() use the following code.

```<code>if self._scoped:
     self._session_factory.remove()
</code>```

This will work.

Title: SQLAlchemy Falcon Class error

Body:
I am trying to set up an API using Falcon and SQLAlchemy using a postgresql database. Using gunicorn to start the API

I am getting the following error when trying to access /v1/users.

I tried to browse the SQLAlchemy documentation but could not find any working solution.

Thanks

[2017-03-15 10:20:26 +0100] [20516] [ERROR] Error handling request /v1/users
    Traceback (most recent call last):
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 135, in handle
        self.handle_request(listener, req, client, addr)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
        respiter = self.wsgi(environ, resp.start_response)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/falcon/api.py", line 209, in __call__
        responder(req, resp, **params)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/app/api/v1/users.py", line 50, in on_get
        users = session.query(User).all()
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
        return getattr(self.registry(), name)(*args, **kwargs)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1330, in query
        return self._query_cls(entities, self, **kwargs)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 139, in __init__
        self._set_entities(entities)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 148, in _set_entities
        entity_wrapper(self, ent)
      File "/Users/juliencourtes/Documents/projects/FalconAPI/venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 3947, in __init__
        "expected - got '%r'" % (column, )
    sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '<function User at 0x1040216a8>'

My projects files

main.py

import falcon
from app.api.v1 import users
from app.middleware import DatabaseSessionManager
from app.database import db_session, init_session
from app.api.common import base

class App(falcon.API):

    def __init__(self,*args, **kwargs):
        super(App, self).__init__(*args, **kwargs)
        self.add_route('/',base.BaseResource())
        self.add_route('/v1/users',users.Collection())

init_session()
mdlw = [DatabaseSessionManager(db_session)]
application = App(middleware=mdlw)

session.py

import sqlalchemy.orm.scoping as scoping
from sqlalchemy.exc import SQLAlchemyError

from app import config

class DatabaseSessionManager(object):
    def __init__(self, db_session):
        self._session_factory = db_session
        self._scoped = isinstance(db_session, scoping.ScopedSession)

    def process_request(self, req, res, resource=None):
        req.context['session'] = self._session_factory

    def process_response(self, req, res, resource=None):
        session = req.context['session']

        if config.DB_AUTOCOMMIT:
            try:
                session.commit()
            except SQLAlchemyError as ex:
                session.rollback()

        if self._scoped:
            session.remove()
        else:
            session.close()

database init.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import psycopg2
from app import config

db_session = scoped_session(sessionmaker())
engine = create_engine('postgresql+psycopg2://xxxxx@localhost/falcon_api')

def init_session():
    db_session.configure(bind=engine)

user.py

from sqlalchemy import Column
from sqlalchemy import String, Integer,Text
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

def User(Base):
    __tablename__ = 'user'

    id = Column('id', UUID, primary_key=True)
    firstname = Column('firstname', String)
    lastname = Column('lastname', String)

    #It tells python how to print the class, used for debugging
    def __repr__(self):
        return "<User(id='%s', name='%s', lastname='%s')>"% \
            (self.id, self.firstname, self.lastname)

    def __init__(self, id , firstname, lastname):
        self.id = id
        self.firstname = firstname
        self.lastname = lastname

api/v1/users.py

import falcon
import json
from sqlalchemy.ext.declarative import declarative_base
try:
    from collections import OrderedDict
except ImportError:
    OrderedDict = dict
from app.models import User
class Collection():
    """
    Handle for endpoint: /v1/users
    """

    def to_json(self, body_dict):
        return json.dumps(body_dict)

    def on_error(self, resp, error=None):
        resp.status = error['status']
        meta = OrderedDict()
        meta['code'] = error['code']
        meta['message'] = error['message']

        obj = OrderedDict()
        obj['meta'] = meta
        resp.body = self.to_json(obj)

    def on_success(self, resp, data=None):
        resp.status = falcon.HTTP_200
        meta = OrderedDict()
        meta['code'] = 200
        meta['message'] = 'OK'

        obj = OrderedDict()
        obj['meta'] = meta
        obj['data'] = data
        resp.body = self.to_json(obj)

    def on_get(self, req, resp):
        session = req.context['session']

        #Bugging here
        users = session.query(User).all()

Body:
I have faced same problem..It got fixed in my case for the following changes..
instead session.remove() use the following code.

if self._scoped:
     self._session_factory.remove()

This will work.