问:
Asynchronous web request not working in WCF
I am using third party API to add log API Call, i want to call this API Asynchronously to does not affect timing for main API call, also this process is low priority (even API result will not used.)

I have tried below code but it seems not work to me:

```<code>string strLogURL = "www.example.com";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(strLogURL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(objAPILog);
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}
httpWebRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), httpWebRequest);
</code>```

Can anyone have idea how to call API from WCF asynchronously?

答:
you can create a method like this:

```<code>private static T Call<T>(string url, string body, int timeOut = 60)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = timeOut * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "DELETE";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        reader.BaseStream.ReadTimeout = timeOut * 1000;
        responseString = reader.ReadToEnd();
    }

    return JsonConvert.DeserializeObject<T>(responseString);
}
</code>```

then you can call it asynchronously like this:

```<code>    Task.Run(() => Call<dynamic>("www.example.com", "body"));
</code>```

Body:
I am using third party API to add log API Call, i want to call this API Asynchronously to does not affect timing for main API call, also this process is low priority (even API result will not used.)

I have tried below code but it seems not work to me:

string strLogURL = "www.example.com";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(strLogURL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(objAPILog);
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}
httpWebRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), httpWebRequest);

Can anyone have idea how to call API from WCF asynchronously?

Body:
you can create a method like this:

private static T Call<T>(string url, string body, int timeOut = 60)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = timeOut * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "DELETE";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        reader.BaseStream.ReadTimeout = timeOut * 1000;
        responseString = reader.ReadToEnd();
    }

    return JsonConvert.DeserializeObject<T>(responseString);
}

then you can call it asynchronously like this:

    Task.Run(() => Call<dynamic>("www.example.com", "body"));


来源: stackexchange

问:
How to notify front-end from backend?
I am using multer for file uploading. On the server I have this:

```<code>stream.on('finish', () => {
  console.log('finished')
  next()
})
</code>```

What would be the best way (with what command) to notify the frontend that 'finished' has happened? I want to know this in order to have a loading bar.

答:
While Jeremy Thille 's answer works well, beware of broadcasting event to all.

Socket.emit() simply broadcasts message to all connected clients.

So you need to store the client id of the uploader and notify the progress only to that client and not all.
Refer this.

ContentLicense: CC BY-SA 3.0

Title: How to notify front-end from backend?

Body:
I am using multer for file uploading. On the server I have this:

stream.on('finish', () => {
  console.log('finished')
  next()
})

What would be the best way (with what command) to notify the frontend that 'finished' has happened? I want to know this in order to have a loading bar.


问:
Jenkins Xcode build works but aichive failed with Command /usr/bin/codesign failed with exit code 1
error is:
unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1

I can run build shell success in my own mac, but when I use it by Jenkins and use my mac as a node of Jenkins, it has the above mistakes. The root Jenkins is build on linux.

I have tried many method, but it doesn't work, for example:

cd ~/Library/Developer/Xcode/DerivedData

xattr -dr com.apple.FinderInfo *

cd project

find . -type f -name '*.png' -exec xattr -c {} \;

xattr -rc project

答:
I solved this question by unlocking my keychain before codesign:

security -v unlock-keychain -p password ~/Library/Keychains/login.keychain


问:
How to use boost::asio::io_service::run_one()
I was reading up on boost::asio::io_service::run_one() and am confused by what it means by the function block. What has been blocked and where is the handler defined?</p>

答:
I was reading up on boost::asio::io_service::run_one() and am confused by what it means by the function block. What has been blocked

Blocked means run_one() blocks until it completes one handler.

and where is the handler defined?

It isn't. Logically it's described in the documentation. A handler is whatever action is pending in the service. So, if you do:

```<code> void foo() { /*.... */ }
 void bar() { /*.... */ }

 io_service svc;
 svc.post(foo);
 svc.post(bar);
</code>```

Now the first time you call

```<code> svc.run_one();
</code>```

blocks until foo is completed. The second time

```<code> svc.run_one();
</code>```

will block until bar is completed. After that, run_one() will NOT block and just return 0. If you make the service stay around, e.g.:

```<code> io_service::work keep_around(svc);
 svc.run_one();
</code>```

would block until some other action was posted.

Body:
I was reading up on boost::asio::io_service::run_one() and am confused by what it means by the function block. What has been blocked

Blocked means run_one() blocks until it completes one handler.

and where is the handler defined?

It isn't. Logically it's described in the documentation. A handler is whatever action is pending in the service. So, if you do:

 void foo() { /*.... */ }
 void bar() { /*.... */ }

 io_service svc;
 svc.post(foo);
 svc.post(bar);

Now the first time you call

 svc.run_one();

blocks until foo is completed. The second time

 svc.run_one();

will block until bar is completed. After that, run_one() will NOT block and just return 0. If you make the service stay around, e.g.:

 io_service::work keep_around(svc);
 svc.run_one();

would block until some other action was posted.


问:
Node Modules not generated
I have created a new node (MERN) app on my mac osx. Im learning (from rails).

I don't know why, but whilst I do have a package.json file, I cannot generate a node_modules folder. I have tried all of the suggested answers in this post.

When I go to the terminal and test:

```<code>ls node_modules
</code>```

I get a long list of all the modules listed in my package.json (but no node modules folder in my app file in atom).

That list includes all of my babel modules.

When I try to start the app, I get an error that arises out of my using import statements instead of require (which I should be able to do if babel were working).

```<code>node server.js
/Users/mr_may/server.js:1
(function (exports, require, module, __filename, __dirname) { import express from 'express';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:390:7)
    at startup (bootstrap_node.js:150:9)
</code>```

Does anyone know how to configure a new node app so that it generates the node modules folder? Apart from the post above, I can't find any suggestions on how to work through this problem. The answers in the post linked above haven't worked.

答:
hi you may want to make sure you are in the directory of your folder
e.g.

```<code>cd Desktop/My_Project
</code>```

The safest way is the then run npm init get all the required things fill out and run npm install --save babel-core at this point you should be able to see the node_modules folder found in "Desktop/My_Project/node_modules"

Try this out and hope this helps :D

Title: Node Modules not generated

Body:
I have created a new node (MERN) app on my mac osx. Im learning (from rails).

I don't know why, but whilst I do have a package.json file, I cannot generate a node_modules folder. I have tried all of the suggested answers in this post.

When I go to the terminal and test:

ls node_modules

I get a long list of all the modules listed in my package.json (but no node modules folder in my app file in atom).

That list includes all of my babel modules.

When I try to start the app, I get an error that arises out of my using import statements instead of require (which I should be able to do if babel were working).

node server.js
/Users/mr_may/server.js:1
(function (exports, require, module, __filename, __dirname) { import express from 'express';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:390:7)
    at startup (bootstrap_node.js:150:9)

Does anyone know how to configure a new node app so that it generates the node modules folder? Apart from the post above, I can't find any suggestions on how to work through this problem. The answers in the post linked above haven't worked.

Body:
hi you may want to make sure you are in the directory of your folder
e.g.

cd Desktop/My_Project

The safest way is the then run npm init get all the required things fill out and run npm install --save babel-core at this point you should be able to see the node_modules folder found in "Desktop/My_Project/node_modules"

Try this out and hope this helps :D


问:
How to add my app's icon into the status bar when my app is running?
I tried to use the Notification.Builder and the Notification classes.

I tried using this code :

```<code>Notification notification = new Notification.Builder(this).build();
notification.icon = R.drawable.ic_launcher;
notification.notify();
</code>```

but it seems useless.

I only want my app's icon to be added next to the battery icon,wifi icon and 3g icons.. Any way to do that? I appreciate your help.

答:
You can add your app icon for status bar notification. Try this one</p>

```<code>Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher).build();
</code>```

Body:
I tried to use the Notification.Builder and the Notification classes.

I tried using this code :

Notification notification = new Notification.Builder(this).build();
notification.icon = R.drawable.ic_launcher;
notification.notify();

but it seems useless.

I only want my app's icon to be added next to the battery icon,wifi icon and 3g icons.. Any way to do that? I appreciate your help.

Body:
You can add your app icon for status bar notification. Try this one

Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher).build();


问:
Javascript variable checking: (null or undefined) vs boolean
I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).

Is there an easy way in JS or Underscore to check this without doing

```<code>(obj.x != null || obj.x != undefined)
</code>```

???

答:
Try this Hope it will help you,

JavaScript

```<code>function test(v) {
        let type = typeof v;
        if(type === 'undefined') {
            return true;
        }
        if(type=== 'boolean') {
            return false;
        }
        if(v === null) {
            return true;
        }
        if(v === undefined) {
            return true;
        }
        if(v instanceof Array) {
            if(v.length < 1) {
                return true;
            }
        }
        else if(type === 'string') {
            if(v.length < 1) {
                return true;
            }
        }
        else if(type === 'object') {
            if(Object.keys(v).length < 1) {
                return true;
            }
        }
        else if(type === 'number') {
            if(isNaN(v)) {
                return true;
            }
        }
        return false;
    }
</code>```

Body:
I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).

Is there an easy way in JS or Underscore to check this without doing

(obj.x != null || obj.x != undefined)

???

Body:
Try this Hope it will help you,

JavaScript

function test(v) {
        let type = typeof v;
        if(type === 'undefined') {
            return true;
        }
        if(type=== 'boolean') {
            return false;
        }
        if(v === null) {
            return true;
        }
        if(v === undefined) {
            return true;
        }
        if(v instanceof Array) {
            if(v.length < 1) {
                return true;
            }
        }
        else if(type === 'string') {
            if(v.length < 1) {
                return true;
            }
        }
        else if(type === 'object') {
            if(Object.keys(v).length < 1) {
                return true;
            }
        }
        else if(type === 'number') {
            if(isNaN(v)) {
                return true;
            }
        }
        return false;
    }


问:
'function' object has no attribute 'name' when registering blueprint
Here is my project layout:

```<code>baseflask/
   baseflask/
      __init__.py
      views.py
      resources/
          health.py/
   wsgi.py/
</code>```

Here is my print

```<code>from flask import Blueprint
from flask import Response
health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():
    jd = {'status': 'OK'}
    data = json.dumps(jd)
    resp = Response(data, status=200, mimetype='application/json')
    return resp
</code>```

How I register in __init__.py:

```<code>import os
basedir = os.path.abspath(os.path.dirname(__file__))
from flask import Blueprint
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.debug = True

CORS(app)

from baseflask.health import health
app.register_blueprint(health)
</code>```

Here is the error:

```<code>Traceback (most recent call last):
  File "/home/ubuntu/workspace/baseflask/wsgi.py", line 10, in <module>
    from baseflask import app
  File "/home/ubuntu/workspace/baseflask/baseflask/__init__.py", line 18, in <module>
    app.register_blueprint(health)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 62, in wrapper_func
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 880, in register_blueprint
    if blueprint.name in self.blueprints:
AttributeError: 'function' object has no attribute 'name'
</code>```

答:
```<code>health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():
</code>```

Your blueprint name is same with your function name, try to rename the function name instead.

```<code>health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def check_health():
</code>```

Body:
Here is my project layout:

baseflask/
   baseflask/
      __init__.py
      views.py
      resources/
          health.py/
   wsgi.py/

Here is my print

from flask import Blueprint
from flask import Response
health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():
    jd = {'status': 'OK'}
    data = json.dumps(jd)
    resp = Response(data, status=200, mimetype='application/json')
    return resp

How I register in __init__.py:

import os
basedir = os.path.abspath(os.path.dirname(__file__))
from flask import Blueprint
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.debug = True

CORS(app)

from baseflask.health import health
app.register_blueprint(health)

Here is the error:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/baseflask/wsgi.py", line 10, in <module>
    from baseflask import app
  File "/home/ubuntu/workspace/baseflask/baseflask/__init__.py", line 18, in <module>
    app.register_blueprint(health)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 62, in wrapper_func
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 880, in register_blueprint
    if blueprint.name in self.blueprints:
AttributeError: 'function' object has no attribute 'name'

Body:
health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():

Your blueprint name is same with your function name, try to rename the function name instead.

health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def check_health():


问:
ASP.NET MVC: Routing needs exact url to work
I have a Products Controller with Details action that has an Id and Slug that works as follows:

```<code>     routes.MapRoute(
            "ProductDetails", // Route name
            "{controller}/{action}/{id}/{title}", // URL with parameters
            new { controller = "Products", action = "Details", id = "", title = UrlParameter.Optional } // Parameter defaults
            );
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
</code>```

The url: localhost/Products/Details/1 and localhost/Products/Details/1/my-slug works.
But putting ProductDetails route at the top breaks my whole application. To get to my home page, my url has to look like: localhost/Home/Index.

localhost/Home or any controller of that matter does not work. It asks for a nullable parameter to be in those actions.

The error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MyProject.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

答: Adding a number constraints (\d) to the first route would solve the problem, since the route on the top would be useless without a valid id.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a Products Controller with Details action that has an Id and Slug that works as follows:

     routes.MapRoute(
            "ProductDetails", // Route name
            "{controller}/{action}/{id}/{title}", // URL with parameters
            new { controller = "Products", action = "Details", id = "", title = UrlParameter.Optional } // Parameter defaults
            );
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

The url: localhost/Products/Details/1 and localhost/Products/Details/1/my-slug works.
But putting ProductDetails route at the top breaks my whole application. To get to my home page, my url has to look like: localhost/Home/Index.

localhost/Home or any controller of that matter does not work. It asks for a nullable parameter to be in those actions.

The error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MyProject.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.


问:
Angular 2 'component' is not a known element
I'm trying to use a component I created inside the AppModule in other modules. I get the following error though:

"Uncaught (in promise): Error: Template parse errors:

'contacts-box' is not a known element:

If 'contacts-box' is an Angular component, then verify that it is part of this module.

If 'contacts-box' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

My project structure is quite simple:

I keep my pages in pages directory, where each page is kept in different module (e.g. customers-module) and each module has multiple components (like customers-list-component, customers-add-component and so on). I want to use my ContactBoxComponent inside those components (so inside customers-add-component for example).

As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

What am I missing?

答:
These are the 5 steps I perform when I get such an error.

Are you sure the name is correct? (Also check the selector defined in the component)

Declare the component in a module?

If it is in another module, export the component?

If it is in another module, import that module?

Restart the cli?

When the error occurs during unit testing, make sure your declared the component or imported the module in TestBed.configureTestingModule

I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

You can't declare a component twice. You should declare and export your component in a new separate module. Next you should import this new module in every module you want to use your component.

It is hard to tell when you should create new module and when you shouldn't. I usually create a new module for every component I reuse. When I have some components that I use almost everywhere I put them in a single module. When I have a component that I don't reuse I won't create a separate module until I need it somewhere else.

Though it might be tempting to put all you components in a single module, this is bad for the performance.  While developing, a module has to recompile every time changes are made. The bigger the module (more components) the more time it takes. Making a small change to big module takes more time than making a small change in a small module.

ContentLicense: CC BY-SA 4.0


问:
onclick slide to page down not working
In this website

www.homepreneurawards.com

when navbar menu is clicked it wont slide to the specific div content what could be the issue

```<code> <header class="header type-1">
        <div class="container">
            <div class="logo-block">
                <a class="logo" href="#"><img src="http://homepreneurawards.com/Homepreneur/img/logo.gif" alt=""></a>
            </div>
            <nav class="main-nav">
                <ul class="anchor-navigation">
                    <li><a class="anchor-scroll" href="#aboutbrandavatar">ABOUT</a></li>
                    <li><a class="anchor-scroll" href="#whoishomepreneur">HOMEPRENEUR ?</a></li>
                    <li><a class="anchor-scroll" href="#categories">CATEGORIES</a></li>
                    <li><a class="anchor-scroll" href="#jurymembers">JURY MEMBERS</a></li>
                    <li><a class="anchor-scroll" href="#timeline">PROCESS FLOW</a></li>
                    <li><a class="anchor-scroll" href="#organizers">ORGANIZERS</a></li>
                    <li><a class="anchor-scroll" href="#sponsorspartners">SPONSORS</a></li>
                    <li><a class="anchor-scroll" href="#partnerscontent">PARTNERS</a></li>
                    <li><a class="anchor-scroll" href="#contact">CONTACT US</a></li>
                </ul>
            </nav>
            <button class="cmn-toggle-switch"><span></span></button>
        </div>
    </header>
</code>```

答:
It looks as though you may be preventing the default click action of the link? If you manually go to the link URL e.g. http://www.homepreneurawards.com/#/aboutbrandavatar you will see that the scroll works as expected and further clicks work without an issue.

The URL structure does not look the same as a standard anchor link either and this could be causing you some issues?
Instead of /#/aboutbrandavatar I would expect to see #aboutbrandavatar

Title: onclick slide to page down not working

Body:
In this website

www.homepreneurawards.com

when navbar menu is clicked it wont slide to the specific div content what could be the issue

ABOUT

HOMEPRENEUR ?

CATEGORIES

JURY MEMBERS

PROCESS FLOW

ORGANIZERS

SPONSORS

PARTNERS

CONTACT US

            <button class="cmn-toggle-switch"></button>


问:
Query with more results works fine but with less results taking time
```<code>SELECT COUNT(*) AS ct
FROM TABLEA _tablea
LEFT OUTER JOIN
  (SELECT DISTINCT CM_CASE_ID,
    LOG_TIMESTAMP,
    ACTION_PERFORMED_BY,
    CASE_FOLLOW_UP_DATE,
    ACTION_PICKLIST_ID,
    CASE_REQUEST_NOTE_VALUE,
    CASE_STATUS_ID,
    RESOLUTION_PICKLIST_ID,
    PREVIOUS_REQUEST_OWNER,
    CURRENT_REQUEST_OWNER,
    CASE_FOLLOW_UP_NOTE_VALUE,
    CM_PENDING_REASON_ID,
    ACCOUNT_STATUS
  FROM TABLEB _tableb
  WHERE _tableb.LOG_TIMESTAMP
    ||_tableb.CM_CASE_ID IN
    (SELECT MIN(_tableb.LOG_TIMESTAMP)
      ||_tableb.CM_CASE_ID AS col_0_0_
    FROM TABLEB _tableb
    WHERE _tableb.CASE_STATUS_ID='A'
    GROUP BY _tableb.CM_CASE_ID
    )
  ) _tableb
ON _tablea.CM_CASE_ID=_tableb.CM_CASE_ID
WHERE _tablea.CASE_CREATION_DATE BETWEEN to_date('12/01/2016', 'mm/dd/yyyy') AND to_date('06/07/2017', 'mm/dd/yyyy') + 1
AND _tablea.CASE_REQUEST_TYPE                                                                                IN (1,2,3)
AND _tablea.CASE_STATUS_ID                                                                                IN ('A','B')
</code>```

the above query which expects records between 12/01/2016 and 06/07/2017 is work fine in less time

```<code>SELECT COUNT(*) AS ct
FROM TABLEA _tablea
LEFT OUTER JOIN
  (SELECT DISTINCT CM_CASE_ID,
    LOG_TIMESTAMP,
    ACTION_PERFORMED_BY,
    CASE_FOLLOW_UP_DATE,
    ACTION_PICKLIST_ID,
    CASE_REQUEST_NOTE_VALUE,
    CASE_STATUS_ID,
    RESOLUTION_PICKLIST_ID,
    PREVIOUS_REQUEST_OWNER,
    CURRENT_REQUEST_OWNER,
    CASE_FOLLOW_UP_NOTE_VALUE,
    CM_PENDING_REASON_ID,
    ACCOUNT_STATUS
  FROM TABLEB _tableb
  WHERE _tableb.LOG_TIMESTAMP
    ||_tableb.CM_CASE_ID IN
    (SELECT MIN(_tableb.LOG_TIMESTAMP)
      ||_tableb.CM_CASE_ID AS col_0_0_
    FROM TABLEB _tableb
    WHERE _tableb.CASE_STATUS_ID='A'
    GROUP BY _tableb.CM_CASE_ID
    )
  ) _tableb
ON _tablea.CM_CASE_ID=_tableb.CM_CASE_ID
WHERE _tablea.CASE_CREATION_DATE BETWEEN to_date('05/01/2017', 'mm/dd/yyyy') AND to_date('06/07/2017', 'mm/dd/yyyy') + 1
AND _tablea.CASE_REQUEST_TYPE                                                                                IN (1,2,3)
AND _tablea.CASE_STATUS_ID   IN ('A','B')
</code>```

this query which expects records between 05/01/2017 and 06/07/2017  is taking too much time around 20 minutes...

Pls help out why the query which expect more result working fine and less not.

答:
you are making sql confuse. put each table as CTE Table like this : but also there is messy in where condition that should be fixed .I suggested to put every select in separate CTE and every JOIN condition in ON part and every other Condition in WHERE and avoid mix too many things .part by part select, join ,on ,where ... ,then at the end group by the result. Then just compare Execution plan for each query you will find out diffrences </p>

```<code>;with cte_tablea as (
 SELECT  CM_CASE_ID, CASE_CREATION_DATE,
 CASE_REQUEST_TYPE , CASE_STATUS_ID
  FROM TABLEA )
,cte_tableb as  (
  SELECT DISTINCT CM_CASE_ID,
  LOG_TIMESTAMP,
  ACTION_PERFORMED_BY,
  CASE_FOLLOW_UP_DATE,
  ACTION_PICKLIST_ID,
  CASE_REQUEST_NOTE_VALUE,
  CASE_STATUS_ID,
  RESOLUTION_PICKLIST_ID,
  PREVIOUS_REQUEST_OWNER,
  CURRENT_REQUEST_OWNER,
  CASE_FOLLOW_UP_NOTE_VALUE,
  CM_PENDING_REASON_ID,
  ACCOUNT_STATUS
 FROM TABLEB
)

SELECT COUNT(*) AS ct
 FROM cte_tablea _tablea
 LEFT OUTER JOIN
   cte_tablea  _tableb
    on _tablea.CM_CASE_ID=_tableb.CM_CASE_ID
  WHERE _tableb.LOG_TIMESTAMP
    ||_tableb.CM_CASE_ID IN
     (SELECT MIN(_tableb.LOG_TIMESTAMP)
    ||_tableb.CM_CASE_ID AS col_0_0_
       FROM TABLEB cte_tablea
      WHERE _tableb.CASE_STATUS_ID='A'
      GROUP BY _tableb.CM_CASE_ID
    )
  and _tablea.CASE_CREATION_DATE BETWEEN to_date('05/01/2017',
 'mm/dd/yyyy') AND to_date('06/07/2017', 'mm/dd/yyyy') + 1
  AND _tablea.CASE_REQUEST_TYPE
  IN (1,2,3)
  AND _tablea.CASE_STATUS_ID   IN ('A','B')
</code>```

Body:
SELECT COUNT(*) AS ct
FROM TABLEA _tablea
LEFT OUTER JOIN
  (SELECT DISTINCT CM_CASE_ID,
    LOG_TIMESTAMP,
    ACTION_PERFORMED_BY,
    CASE_FOLLOW_UP_DATE,
    ACTION_PICKLIST_ID,
    CASE_REQUEST_NOTE_VALUE,
    CASE_STATUS_ID,
    RESOLUTION_PICKLIST_ID,
    PREVIOUS_REQUEST_OWNER,
    CURRENT_REQUEST_OWNER,
    CASE_FOLLOW_UP_NOTE_VALUE,
    CM_PENDING_REASON_ID,
    ACCOUNT_STATUS
  FROM TABLEB _tableb
  WHERE _tableb.LOG_TIMESTAMP
    ||_tableb.CM_CASE_ID IN
    (SELECT MIN(_tableb.LOG_TIMESTAMP)
      ||_tableb.CM_CASE_ID AS col_0_0_
    FROM TABLEB _tableb
    WHERE _tableb.CASE_STATUS_ID='A'
    GROUP BY _tableb.CM_CASE_ID
    )
  ) _tableb
ON _tablea.CM_CASE_ID=_tableb.CM_CASE_ID
WHERE _tablea.CASE_CREATION_DATE BETWEEN to_date('12/01/2016', 'mm/dd/yyyy') AND to_date('06/07/2017', 'mm/dd/yyyy') + 1
AND _tablea.CASE_REQUEST_TYPE                                                                                IN (1,2,3)
AND _tablea.CASE_STATUS_ID                                                                                IN ('A','B')

the above query which expects records between 12/01/2016 and 06/07/2017 is work fine in less time

SELECT COUNT(*) AS ct
FROM TABLEA _tablea
LEFT OUTER JOIN
  (SELECT DISTINCT CM_CASE_ID,
    LOG_TIMESTAMP,
    ACTION_PERFORMED_BY,
    CASE_FOLLOW_UP_DATE,
    ACTION_PICKLIST_ID,
    CASE_REQUEST_NOTE_VALUE,
    CASE_STATUS_ID,
    RESOLUTION_PICKLIST_ID,
    PREVIOUS_REQUEST_OWNER,
    CURRENT_REQUEST_OWNER,
    CASE_FOLLOW_UP_NOTE_VALUE,
    CM_PENDING_REASON_ID,
    ACCOUNT_STATUS
  FROM TABLEB _tableb
  WHERE _tableb.LOG_TIMESTAMP
    ||_tableb.CM_CASE_ID IN
    (SELECT MIN(_tableb.LOG_TIMESTAMP)
      ||_tableb.CM_CASE_ID AS col_0_0_
    FROM TABLEB _tableb
    WHERE _tableb.CASE_STATUS_ID='A'
    GROUP BY _tableb.CM_CASE_ID
    )
  ) _tableb
ON _tablea.CM_CASE_ID=_tableb.CM_CASE_ID
WHERE _tablea.CASE_CREATION_DATE BETWEEN to_date('05/01/2017', 'mm/dd/yyyy') AND to_date('06/07/2017', 'mm/dd/yyyy') + 1
AND _tablea.CASE_REQUEST_TYPE                                                                                IN (1,2,3)
AND _tablea.CASE_STATUS_ID   IN ('A','B')

this query which expects records between 05/01/2017 and 06/07/2017  is taking too much time around 20 minutes...

Pls help out why the query which expect more result working fine and less not.

Body:
you are making sql confuse. put each table as CTE Table like this : but also there is messy in where condition that should be fixed .I suggested to put every select in separate CTE and every JOIN condition in ON part and every other Condition in WHERE and avoid mix too many things .part by part select, join ,on ,where ... ,then at the end group by the result. Then just compare Execution plan for each query you will find out diffrences

;with cte_tablea as (
 SELECT  CM_CASE_ID, CASE_CREATION_DATE,
 CASE_REQUEST_TYPE , CASE_STATUS_ID
  FROM TABLEA )
,cte_tableb as  (
  SELECT DISTINCT CM_CASE_ID,
  LOG_TIMESTAMP,
  ACTION_PERFORMED_BY,
  CASE_FOLLOW_UP_DATE,
  ACTION_PICKLIST_ID,
  CASE_REQUEST_NOTE_VALUE,
  CASE_STATUS_ID,
  RESOLUTION_PICKLIST_ID,
  PREVIOUS_REQUEST_OWNER,
  CURRENT_REQUEST_OWNER,
  CASE_FOLLOW_UP_NOTE_VALUE,
  CM_PENDING_REASON_ID,
  ACCOUNT_STATUS
 FROM TABLEB
)

SELECT COUNT(*) AS ct
 FROM cte_tablea _tablea
 LEFT OUTER JOIN
   cte_tablea  _tableb
    on _tablea.CM_CASE_ID=_tableb.CM_CASE_ID
  WHERE _tableb.LOG_TIMESTAMP
    ||_tableb.CM_CASE_ID IN
     (SELECT MIN(_tableb.LOG_TIMESTAMP)
    ||_tableb.CM_CASE_ID AS col_0_0_
       FROM TABLEB cte_tablea
      WHERE _tableb.CASE_STATUS_ID='A'
      GROUP BY _tableb.CM_CASE_ID
    )
  and _tablea.CASE_CREATION_DATE BETWEEN to_date('05/01/2017',
 'mm/dd/yyyy') AND to_date('06/07/2017', 'mm/dd/yyyy') + 1
  AND _tablea.CASE_REQUEST_TYPE
  IN (1,2,3)
  AND _tablea.CASE_STATUS_ID   IN ('A','B')


问:
How to get Attribute Value in C# for the class property
```<code> [System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
    sealed class ColumnName : Attribute
    {
        // See the attribute guidelines at
        //  http://go.microsoft.com/fwlink/?LinkId=85236

        readonly string Column;

        // This is a positional argument
        public ColumnName(string columnName)
        {
            this.Column = columnName;
        }
    }

    public class Comment
    {
        [ColumnName("ID1")]
        public int Id;
        [ColumnName("NAME1")]
        public string Name;
        [ColumnName("TEST1")]
        public string Test;
    }
</code>```

In this code you can see I have create a class comment which have an attribute ColumnName. ColumnName is my custom class which I used to define the attirubte.

Now I am looking for a sollution to find the ColumnName value for all the properties.

```<code>public static List<T> ExecuteReader<T>(string str)
        {
            var res = typeof(T);

            return new List<T>();
        }
</code>```

I tried run some Stack Overflow code on my issue but it doesn't work well. What thing I am missing in my code?

答:
Given

```<code>[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public sealed class ColumnNameAttribute : Attribute
{
    public readonly string Column;

    public ColumnNameAttribute(string columnName)
    {
        this.Column = columnName;
    }
}
</code>```

(by convention attributes should have a name ending in Attribute, and note that I've restricted the AttributeTargets to Propertyes and Fields) you can

```<code>public static class ColumnsCache<T>
{
    public static readonly IReadOnlyDictionary<MemberInfo, string> Columns = BuildColumnsDictionary();

    public static Dictionary<MemberInfo, string> BuildColumnsDictionary()
    {
        var dict = new Dictionary<MemberInfo, string>();

        var members = typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance)
            .Where(x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property);

        foreach (MemberInfo member in members)
        {
            var attr = member.GetCustomAttribute<ColumnNameAttribute>(true);

            if (attr != null)
            {
                dict.Add(member, attr.Column);
            }
        }

        return dict;
    }
}
</code>```

(note the trick: we are caching the list of column names (and of fields/properties having the ColumnNameAttribute) through the usage of a generic static class. The .NET runtime will create various distinct ColumnsCache<T1>, ColumnsCache<T2>, ColumnsCache<T3>, each one with a different dictionary of columns)

Then you can

```<code>var cols = ColumnsCache<Comment>.Columns;
var colNames = cols.Values;
</code>```

The cols variable will reference a dictionary MemberInfo -> string (colum name), while the colNames is a IEnumerable<string> with only the column names. If you want to use reflection with a MemberInfo you have to check if the MemberInfo is a FieldInfo or a PropertyInfo, cast it and use the FieldInfo or PropertyInfo.

Body:
 [System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
    sealed class ColumnName : Attribute
    {
        // See the attribute guidelines at
        //  http://go.microsoft.com/fwlink/?LinkId=85236

        readonly string Column;

        // This is a positional argument
        public ColumnName(string columnName)
        {
            this.Column = columnName;
        }
    }

    public class Comment
    {
        [ColumnName("ID1")]
        public int Id;
        [ColumnName("NAME1")]
        public string Name;
        [ColumnName("TEST1")]
        public string Test;
    }

In this code you can see I have create a class comment which have an attribute ColumnName. ColumnName is my custom class which I used to define the attirubte.

Now I am looking for a sollution to find the ColumnName value for all the properties.

public static List<T> ExecuteReader<T>(string str)
        {
            var res = typeof(T);

            return new List<T>();
        }

I tried run some Stack Overflow code on my issue but it doesn't work well. What thing I am missing in my code?

Body:
Given

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public sealed class ColumnNameAttribute : Attribute
{
    public readonly string Column;

    public ColumnNameAttribute(string columnName)
    {
        this.Column = columnName;
    }
}

(by convention attributes should have a name ending in Attribute, and note that I've restricted the AttributeTargets to Propertyes and Fields) you can

public static class ColumnsCache<T>
{
    public static readonly IReadOnlyDictionary<MemberInfo, string> Columns = BuildColumnsDictionary();

    public static Dictionary<MemberInfo, string> BuildColumnsDictionary()
    {
        var dict = new Dictionary<MemberInfo, string>();

        var members = typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance)
            .Where(x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property);

        foreach (MemberInfo member in members)
        {
            var attr = member.GetCustomAttribute<ColumnNameAttribute>(true);

            if (attr != null)
            {
                dict.Add(member, attr.Column);
            }
        }

        return dict;
    }
}

(note the trick: we are caching the list of column names (and of fields/properties having the ColumnNameAttribute) through the usage of a generic static class. The .NET runtime will create various distinct ColumnsCache<T1>, ColumnsCache<T2>, ColumnsCache<T3>, each one with a different dictionary of columns)

Then you can

var cols = ColumnsCache<Comment>.Columns;
var colNames = cols.Values;

The cols variable will reference a dictionary MemberInfo -> string (colum name), while the colNames is a IEnumerable<string> with only the column names. If you want to use reflection with a MemberInfo you have to check if the MemberInfo is a FieldInfo or a PropertyInfo, cast it and use the FieldInfo or PropertyInfo.


问:
Uima Ruta CW Annotation
I'm using Uima Ruta 2.5.0 Version. In this, Symbols like Γ,Δ were coming under CW .Why its Happening?

Input
Γ
Δ

答:
The CW annotation like the other TokenSeed annotations is created by a JFlex lexer. The rule for CW is [:uppercase:][:lowercase:]* whereas [:uppercase:]  is defined by the Unicode properties \p{Uppercase}. Both of your example symbols are greek uppercase letters.

DISCLAIMER: I am a developer of UIMA Ruta

Title: Uima Ruta CW Annotation


问:
Using "KexAlgorithms diffie-hellman-group1-sha1" did not resolve "no matching key exchange method found" error
There's a lot of questions about the following error, but they all have same solution which did not have any effect:

```<code>$ git push
Unable to negotiate with 192.168.XXX.XXX: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

There is an article on openssh.com that didn't help. Particularly this was suggested:

... in the ~/.ssh/config file:

```<code>Host somehost.example.org
KexAlgorithms +diffie-hellman-group1-sha1
</code>```

I did exactly that. I assume that ~ resolves to %userprofile% on windows. My file is in C:\Users\MY_USERNAME\.ssh\config:

```<code>## use kex algorithm ##
Host 192.168.XXX.XXX
KexAlgorithms diffie-hellman-group1-sha1
</code>```

The result is that nothing changed. There is also suggestion to use ssh -o but I'm yet to find an answer that bothers to describe how exactly yo do that. I tried this:

```<code>$ ssh -oKexAlgorithms=+diffie-hellman-group1-sha1
usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
</code>```

I need to connect to that GIT repository. I am on windows. The repository uses Gerrit. I also use SourceTree and it has no problems pushing into the repository. So the repository works, but git or openSSH in my bash is broken.

What did I do wrong that this solution didn't work for me?

答: I resolved a similar problem on Windows 10 by updating my version of Open SSH to the latest (7.5p1-1) and then making sure that C:Program Files\OpenSSH\bin was the first entry in the system path so it used that ssh.exe and not any others.</p>

Body:
There's a lot of questions about the following error, but they all have same solution which did not have any effect:

$ git push
Unable to negotiate with 192.168.XXX.XXX: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

There is an article on openssh.com that didn't help. Particularly this was suggested:

... in the ~/.ssh/config file:

Host somehost.example.org
KexAlgorithms +diffie-hellman-group1-sha1

I did exactly that. I assume that ~ resolves to %userprofile% on windows. My file is in C:\Users\MY_USERNAME\.ssh\config:

## use kex algorithm ##
Host 192.168.XXX.XXX
KexAlgorithms diffie-hellman-group1-sha1

The result is that nothing changed. There is also suggestion to use ssh -o but I'm yet to find an answer that bothers to describe how exactly yo do that. I tried this:

$ ssh -oKexAlgorithms=+diffie-hellman-group1-sha1
usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]

I need to connect to that GIT repository. I am on windows. The repository uses Gerrit. I also use SourceTree and it has no problems pushing into the repository. So the repository works, but git or openSSH in my bash is broken.

What did I do wrong that this solution didn't work for me?


问:
When i add this thing in my onCreate method why my app is unfortunately stopped
when i add this thing in my oncreate method why my app is unfortunately stopped

ListView mylistview = (ListView) findViewById(R.id.listview);

```<code>    ArrayList<String> myfamily = new ArrayList<String>();
    myfamily.add("PAPA");
    myfamily.add("BHAI");
    myfamily.add("MUMMA");
    myfamily.add("ME");
</code>```

ArrayAdapter arrayAdapter = new ArrayAdapter(this , android.R.layout.simple_list_item_1, myfamily);

```<code>    mylistview.setAdapter(arrayAdapter);
</code>```

答: I think you're initialising your lsitview in onCreateView and setting it in onCreate which won't work as onCreate will be called first.</p>

Body:
when i add this thing in my oncreate method why my app is unfortunately stopped

ListView mylistview = (ListView) findViewById(R.id.listview);

    ArrayList<String> myfamily = new ArrayList<String>();
    myfamily.add("PAPA");
    myfamily.add("BHAI");
    myfamily.add("MUMMA");
    myfamily.add("ME");

ArrayAdapter arrayAdapter = new ArrayAdapter(this , android.R.layout.simple_list_item_1, myfamily);

    mylistview.setAdapter(arrayAdapter);


问:
Convert string dates in java
I need to compare two string dates in java:

```<code>String date1 = "2017-05-02";
String date2 = "5/2/2017";
//formatter for the first date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date formattedDate1 = formatter.parse(date1);
//formatter for the second date
formatter = new SimpleDateFormat("m/d/yyyy");
Date formattedDate2 = formatter.parse(date2);
//Wrong results
String formatted1 = formattedDate1.toString(); //Mon Jan 02 00:05:00 EET 2017
String formatted2 = formattedDate2.toString(); //Mon Jan 02 00:05:00 EET 2017
</code>```

Actually if i compare those 2 i probably will get 'true' but my dates are not the January, it's 'May 5th 2017'.

The other question is that I can't use Date object, I need to actually convert "2017-05-02" into "5/2/2017" and then pass it to another function

答:
m - minutes

M - month

Please read date and time patterns
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Title: Convert string dates in java

Body:
I need to compare two string dates in java:

String date1 = "2017-05-02";
String date2 = "5/2/2017";
//formatter for the first date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date formattedDate1 = formatter.parse(date1);
//formatter for the second date
formatter = new SimpleDateFormat("m/d/yyyy");
Date formattedDate2 = formatter.parse(date2);
//Wrong results
String formatted1 = formattedDate1.toString(); //Mon Jan 02 00:05:00 EET 2017
String formatted2 = formattedDate2.toString(); //Mon Jan 02 00:05:00 EET 2017

Actually if i compare those 2 i probably will get 'true' but my dates are not the January, it's 'May 5th 2017'.

The other question is that I can't use Date object, I need to actually convert "2017-05-02" into "5/2/2017" and then pass it to another function


问:
Cannot execute properly "apt-get update" when installing MongoDB under Ubuntu 15.04
i'm trying to install MongoDB underr my Ubuntu 15.04 , i fulfilled those steps :

import the MongoDB public GPG Key:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

create the /etc/apt/sources.list.d/mongodb-org-3.0.list list-file to get the package from debian wheezy repository

echo "deb http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

Now when trying to execute apt-get update  i got this error :

Atteint http://security.ubuntu.com vivid-security InRelease Réception
  de : 1 http://repo.mongodb.org wheezy/mongodb-org/3.0 InRelease

  79% [1 InRelease gpgv 109 B] [Attente des fichiers d'en-tête] [Attente
  des ficSplitting up
  /var/lib/apt/lists/partial/repo.mongodb.org_apt_debian_dists_wheezy_mIgn
  http://repo.mongodb.org wheezy/mongodb-org/3.0 InRelease

  E: Erreur de GPG : http://repo.mongodb.org wheezy/mongodb-org/3.0
  InRelease : Le fichier signé en clair n'est pas valable, ce qui a été
  reçu est « NODATA ». Peut-être le réseau nécessite-t-il une
  authentification.

i ve checked my sources files  , and its contains this :

```<code># deb cdrom:[Ubuntu 14.10 _Utopic Unicorn_ - Release amd64 (20141022.1)]/ utopic main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid main restricted
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-updates main restricted
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid universe
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid universe
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-updates universe
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid multiverse
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid multiverse
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-updates multiverse
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-backports main restricted universe multiverse
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-backports main restricted universe multiverse

deb http://security.ubuntu.com/ubuntu vivid-security main restricted
deb-src http://security.ubuntu.com/ubuntu vivid-security main restricted
deb http://security.ubuntu.com/ubuntu vivid-security universe
deb-src http://security.ubuntu.com/ubuntu vivid-security universe
deb http://security.ubuntu.com/ubuntu vivid-security multiverse
deb-src http://security.ubuntu.com/ubuntu vivid-security multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu utopic partner
# deb-src http://archive.canonical.com/ubuntu utopic partner

deb http://archive.canonical.com/ vivid partner
# deb-src http://archive.canonical.com/ utopic partner
</code>```

Since i haven't know the problem origin , and how to solve it , any suggestions ??

答:
Try,

```<code>sudo apt-get update
</code>```

You're now running the command as administration, so it might help.

Body:
i'm trying to install MongoDB underr my Ubuntu 15.04 , i fulfilled those steps :

import the MongoDB public GPG Key:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

create the /etc/apt/sources.list.d/mongodb-org-3.0.list list-file to get the package from debian wheezy repository

echo "deb http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

Now when trying to execute apt-get update  i got this error :

Atteint http://security.ubuntu.com vivid-security InRelease Réception
  de : 1 http://repo.mongodb.org wheezy/mongodb-org/3.0 InRelease

  79% [1 InRelease gpgv 109 B] [Attente des fichiers d'en-tête] [Attente
  des ficSplitting up
  /var/lib/apt/lists/partial/repo.mongodb.org_apt_debian_dists_wheezy_mIgn
  http://repo.mongodb.org wheezy/mongodb-org/3.0 InRelease

  E: Erreur de GPG : http://repo.mongodb.org wheezy/mongodb-org/3.0
  InRelease : Le fichier signé en clair n'est pas valable, ce qui a été
  reçu est « NODATA ». Peut-être le réseau nécessite-t-il une
  authentification.

i ve checked my sources files  , and its contains this :

# deb cdrom:[Ubuntu 14.10 _Utopic Unicorn_ - Release amd64 (20141022.1)]/ utopic main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid main restricted
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-updates main restricted
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid universe
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid universe
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-updates universe
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid multiverse
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid multiverse
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-updates multiverse
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://tn.archive.ubuntu.com/ubuntu/ vivid-backports main restricted universe multiverse
deb-src http://tn.archive.ubuntu.com/ubuntu/ vivid-backports main restricted universe multiverse

deb http://security.ubuntu.com/ubuntu vivid-security main restricted
deb-src http://security.ubuntu.com/ubuntu vivid-security main restricted
deb http://security.ubuntu.com/ubuntu vivid-security universe
deb-src http://security.ubuntu.com/ubuntu vivid-security universe
deb http://security.ubuntu.com/ubuntu vivid-security multiverse
deb-src http://security.ubuntu.com/ubuntu vivid-security multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu utopic partner
# deb-src http://archive.canonical.com/ubuntu utopic partner

deb http://archive.canonical.com/ vivid partner
# deb-src http://archive.canonical.com/ utopic partner

Since i haven't know the problem origin , and how to solve it , any suggestions ??

Body:
Try,

sudo apt-get update

You're now running the command as administration, so it might help.


问:
how to restart horizontal progressbar
I've a horizontal progressbar which shows progress from 0 to 100. What I want is to restart the progressbar again from 0 when it reaches 100. I'll be showing this in a Fragmentdialog. For now I'm checking it in activity itself. How to do that?</p>

```<code>    public class MainActivity extends AppCompatActivity{
    private Button startbtn, stopbtn;
    ProgressBar pb;
    private TextView progressTxt;

    int progressBarValue = 0;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        show = new CShowProgress(MainActivity.this);

        btn = (Button)findViewById(R.id.btn);
        startbtn = (Button)findViewById(R.id.startbtn);
        stopbtn = (Button)findViewById(R.id.stopbtn);
        pb = (ProgressBar)findViewById(R.id.progressBar);
        progressTxt = (TextView)findViewById(R.id.progressTxt);

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(true);
            }
        });

        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(false);
            }
        });
    }

    private void myprogress(final Boolean isStart){
        handler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                if(isStart && progressBarValue<100)
                {
                    progressBarValue+=1;
                    pb.setProgress(progressBarValue);
                    progressTxt.setText(String.valueOf(progressBarValue));

                    handler.sendEmptyMessageDelayed(0, 100);
                }

            }
        };

        handler.sendEmptyMessage(0);
    }
}
</code>```

答:
I assume this chunk of code will work for your use case:</p>

```<code>private void myprogress(final Boolean isStart) {
  handler = new Handler() {
    public void handleMessage(Message msg) {
      if (isStart && progressBarValue < 100) {
          ...
      } else if (isStart) {
        // progressBarValue is equal to 100
        // make it zero and do the same thing again
        progressBarValue = 0;
        progressBarValue += 1;
        pb.setProgress(progressBarValue);
        progressTxt.setText(String.valueOf(progressBarValue));

        handler.sendEmptyMessageDelayed(0, 100);
      }
    }
  };

  handler.sendEmptyMessage(0);
}
</code>```

Title: how to restart horizontal progressbar

Body:
I've a horizontal progressbar which shows progress from 0 to 100. What I want is to restart the progressbar again from 0 when it reaches 100. I'll be showing this in a Fragmentdialog. For now I'm checking it in activity itself. How to do that?

    public class MainActivity extends AppCompatActivity{
    private Button startbtn, stopbtn;
    ProgressBar pb;
    private TextView progressTxt;

    int progressBarValue = 0;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        show = new CShowProgress(MainActivity.this);

        btn = (Button)findViewById(R.id.btn);
        startbtn = (Button)findViewById(R.id.startbtn);
        stopbtn = (Button)findViewById(R.id.stopbtn);
        pb = (ProgressBar)findViewById(R.id.progressBar);
        progressTxt = (TextView)findViewById(R.id.progressTxt);

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(true);
            }
        });

        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(false);
            }
        });
    }

    private void myprogress(final Boolean isStart){
        handler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                if(isStart && progressBarValue<100)
                {
                    progressBarValue+=1;
                    pb.setProgress(progressBarValue);
                    progressTxt.setText(String.valueOf(progressBarValue));

                    handler.sendEmptyMessageDelayed(0, 100);
                }

            }
        };

        handler.sendEmptyMessage(0);
    }
}

Body:
I assume this chunk of code will work for your use case:

private void myprogress(final Boolean isStart) {
  handler = new Handler() {
    public void handleMessage(Message msg) {
      if (isStart && progressBarValue < 100) {
          ...
      } else if (isStart) {
        // progressBarValue is equal to 100
        // make it zero and do the same thing again
        progressBarValue = 0;
        progressBarValue += 1;
        pb.setProgress(progressBarValue);
        progressTxt.setText(String.valueOf(progressBarValue));

        handler.sendEmptyMessageDelayed(0, 100);
      }
    }
  };

  handler.sendEmptyMessage(0);
}


问:
Unhide objects/legends in Dashboard tableau
I have objects on the dashboards - filters and legends, I've click 'x' on some of the objects because I dont want to display them. Now I want to display them - how can I make them appear on the dashboard again? I've tried remove and add the sheet again, but doesn't bring back everything anymore.

gemmo

答:
To unhide Legends, Follow steps as under in the image:

Select floating and adjust Legends as per your requirement and you will get desired results.


问:
Substring a String depending on int
I wanted to substring a String depending on int that I will passed on the method. I used nested loop for this. But everytime it loops I wanted to substring only from last substring to int the I passed in the method and get also the last string. How can I achieve this?

```<code>private static void input(String s, int I)
{
    List list = new ArrayList();

    for(int a = 0; a < s.length(); a++)
    {
        for(int position = 0; position < s.length(); position++)
        {
            if(position + a + I <= s.length())
            {
                list.add(s.substring(position, position + a + I));
            }
        }
    }

}

input("abaca", 2);
</code>```

Expected output: "ab", "ac", "a"

答:
You can also simply split the string:

```<code>private static void input(String s, int i){
    List list = Arrays.asList(s.split("(?<=\\G.{"+i+"})"));
    System.out.println(list);
}
</code>```

\\G means The end of the previous match

?<= means positive lookbehind

Thanks to positive lookbehind (?<=) it will split on all zero length strings (without cutting off anything from the input string) preceded by where previous match ends (\\G) followed by i signs (.{"+i+"}).

Title: Substring a String depending on int

Body:
I wanted to substring a String depending on int that I will passed on the method. I used nested loop for this. But everytime it loops I wanted to substring only from last substring to int the I passed in the method and get also the last string. How can I achieve this?

private static void input(String s, int I)
{
    List list = new ArrayList();

    for(int a = 0; a < s.length(); a++)
    {
        for(int position = 0; position < s.length(); position++)
        {
            if(position + a + I <= s.length())
            {
                list.add(s.substring(position, position + a + I));
            }
        }
    }

}

input("abaca", 2);

Expected output: "ab", "ac", "a"

Body:
You can also simply split the string:

private static void input(String s, int i){
    List list = Arrays.asList(s.split("(?<=\\G.{"+i+"})"));
    System.out.println(list);
}

\\G means The end of the previous match

?<= means positive lookbehind

Thanks to positive lookbehind (?<=) it will split on all zero length strings (without cutting off anything from the input string) preceded by where previous match ends (\\G) followed by i signs (.{"+i+"}).


问:
How can we run the unit tests of civicrm from script?
I execute this commande line to run a unit tests :

hatem.hadrich@pc_Hatem_Hadrich:/projet/tools$ php /scripts/phpunit CRM_AllTests

I have this error when i run a unit test from my local instance and i can not find a way to resolve it anyone can help me to fix this bug.

```<code>PHP Fatal error:  Class 'CiviTestSuite' not found in /projet/../civicrm/tests/phpunit/CRM/AllTests.php on line 39
PHP Stack trace:
PHP   1. {main}() /usr/local/bin/phpunit:0
PHP   2. PHPUnit_TextUI_Command::main() /usr/local/bin/phpunit:569
PHP   3. PHPUnit_TextUI_Command->run()
phar:///usr/local/bin/phpunit/phpunit/TextUI/Command.php:115
PHP   4. PHPUnit_Runner_BaseTestRunner->getTest()
phar:///usr/local/bin/phpunit/phpunit/TextUI/Command.php:137
PHP   5. PHPUnit_Runner_BaseTestRunner->loadSuiteClass()
phar:///usr/local/bin/phpunit/phpunit/Runner/BaseTestRunner.php:65
PHP   6. PHPUnit_Runner_StandardTestSuiteLoader->load()
phar:///usr/local/bin/phpunit/phpunit/Runner/BaseTestRunner.php:124
PHP   7. PHPUnit_Util_Fileloader::checkAndLoad() phar:///usr/local/bin/phpunit/phpunit/Runner/StandardTestSuiteLoader.php:39
PHP   8. PHPUnit_Util_Fileloader::load() phar:///usr/local/bin/phpunit/phpunit/Util/Fileloader.php:38
PHP   9. include_once() phar:///usr/local/bin/phpunit/phpunit/Util/Fileloader.php:56
</code>```

答:
i have find a way to fix this bug, you must require_one for the bootstrap file inside CiviTest :</p>

```<code>define('DRUPAL_ROOT', '/path_to_project');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
</code>```

Body:
I execute this commande line to run a unit tests :

hatem.hadrich@pc_Hatem_Hadrich:/projet/tools$ php /scripts/phpunit CRM_AllTests

I have this error when i run a unit test from my local instance and i can not find a way to resolve it anyone can help me to fix this bug.

PHP Fatal error:  Class 'CiviTestSuite' not found in /projet/../civicrm/tests/phpunit/CRM/AllTests.php on line 39
PHP Stack trace:
PHP   1. {main}() /usr/local/bin/phpunit:0
PHP   2. PHPUnit_TextUI_Command::main() /usr/local/bin/phpunit:569
PHP   3. PHPUnit_TextUI_Command->run()
phar:///usr/local/bin/phpunit/phpunit/TextUI/Command.php:115
PHP   4. PHPUnit_Runner_BaseTestRunner->getTest()
phar:///usr/local/bin/phpunit/phpunit/TextUI/Command.php:137
PHP   5. PHPUnit_Runner_BaseTestRunner->loadSuiteClass()
phar:///usr/local/bin/phpunit/phpunit/Runner/BaseTestRunner.php:65
PHP   6. PHPUnit_Runner_StandardTestSuiteLoader->load()
phar:///usr/local/bin/phpunit/phpunit/Runner/BaseTestRunner.php:124
PHP   7. PHPUnit_Util_Fileloader::checkAndLoad() phar:///usr/local/bin/phpunit/phpunit/Runner/StandardTestSuiteLoader.php:39
PHP   8. PHPUnit_Util_Fileloader::load() phar:///usr/local/bin/phpunit/phpunit/Util/Fileloader.php:38
PHP   9. include_once() phar:///usr/local/bin/phpunit/phpunit/Util/Fileloader.php:56

Body:
i have find a way to fix this bug, you must require_one for the bootstrap file inside CiviTest :

define('DRUPAL_ROOT', '/path_to_project');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';


问:
How can I fit a nonlinear line in R?
I am new to R and can't find an answer to this (seemingly) simple question. I have been searching for a couple of days, and did read a couple of papers and the help pages.

I have been able to plot one line (in red).

I want to plot another line fitted to the back dots. I expect the line to look like the black line in this image (by Křivan and Priyadarshi, 2015).

However, I have not been able to plot the line.

I have tried to fit the line using the following code, but nothing shows on the graph:

Values that I want to fit a line through:

```<code>Prey_isocline_x     <- c(8.2, 7.15, 7.65, 10.6, 7.947368421, 5.35,
                         6, 8.2, 7.473684211, 1.5, 1.3, 0.95, 1.85,
                         1.15, 0.6, 2.7, 1.3, 0.25, 0.25, 6.263157895,
                         4, 0.3, 5.1, 4.15, 1.15, 1.6, 1.6, 1.55)
Prey_isocline_y     <- c(0.45, 0.3, 0.2, 0.2, 0.105263158, 0.8, 0.5,
                         0.15, 0.052631579, 0.642857143, 1, 1, 1.15,
                         0.7, 0.55, 0.35, 0.8, 1.15, 1.55, 0.578947368,
                         0.5, 2.55, 0.15, 0.25, 0.45, 2.45, 2.45, 1.3)
Prey_isocline       <- data.frame(Prey_isocline_x, Prey_isocline_y)

Predator_isocline_x <- c(0.25, 0.15, 0.3, 0.7, 0.25, 0.25, 0.05, 0.5, 0.45,
                         0.5, 0.5, 0.15, 0.6, 1.4, 0.85, 0.15, 0.15, 0.6)
Predator_isocline_y <- c(2.35, 2.9, 3.6, 3.6, 2.35, 4.45, 1.45, 1.7, 1.65,
                         1.7, 2.9, 1.8, 1.9, 2.35, 2.9, 2.8, 2.5, 3.05)
Predator_isocline   <- data.frame(Predator_isocline_x, Predator_isocline_y)
</code>```

First attempt to plot:

```<code>plot(Prey_isocline_x, Prey_isocline_y,
        axes = F,
        xlab= "",
        ylab= "",
        pch=1, col="black")
fit <- nls(Prey_isocline_y ~ SSlogis(Prey_isocline_x, Asym, xmid, scal),
       data=Prey_isocline,
       trace = TRUE)
summary(fit)
curve(predict(fit, newdata = data.frame(Prey_isocline_y=x)), add=TRUE)
</code>```

Output first attempt:

```<code>> par(new=T)
> plot(Prey_isocline_x, Prey_isocline_y,
+         axes = F,
+         xlab= "",
+         ylab= "",
+         pch=1, col="black")
> fit <- nls(Prey_isocline_y ~ SSlogis(Prey_isocline_x, Asym, xmid, scal),
+            data=Prey_isocline,
+            trace = TRUE)
Error in nls(y ~ 1/(1 + exp((xmid - x)/scal)), data = xy, start = list(xmid = aux[1L],  :
  step factor 0.000488281 reduced below 'minFactor' of 0.000976562
> summary(fit)
Error in summary(fit) : object 'fit' not found
> curve(predict(fit, newdata = data.frame(Prey_isocline_y=x)), add=TRUE)
Error in predict(fit, newdata = data.frame(Prey_isocline_y = x)) :
  object 'fit' not found
</code>```

Second try:

```<code>model <- loess(formula=Prey_isocline_x~Prey_isocline_y,
data=Predator_isocline)
abline(model, col="black")
</code>```

Second output:

```<code>> model <- loess(formula=Prey_isocline_x~Prey_isocline_y, data=Predator_isocline)
> abline(model, col="black")
</code>```

Third attempt:

```<code>nls_fit <- nls(Prey_isocline_y ~ (b*Prey_isocline_x) - (b*Prey_isocline_x*Prey_isocline_x/K) -
              (Predator_isocline_y*(Prey_isocline_x^k/(x^k+C^k)*(l*x/(1+l*h*x)))),
               data = Prey_isocline,
               start = list(b = 2.2,
                            e = 1.5,
                            K = 30,
                            k = 20,
                            l = 0.1,
                            h = 0.25,
                            C = 1,
                            m = 1.0))
lines(Prey_isocline_x, predict(nls_fit), col = "green")
</code>```

Third output:

```<code>> nls_fit <- nls(Prey_isocline_y ~ (b*Prey_isocline_x) - (b*Prey_isocline_x*Prey_isocline_x/K) -
+               (Predator_isocline_y*(Prey_isocline_x^k/(x^k+C^k)*(l*x/(1+l*h*x)))),
+                data = Prey_isocline,
+                start = list(b = 2.2,
+                             e = 1.5,
+                             K = 30,
+                             k = 20,
+                             l = 0.1,
+                             h = 0.25,
+                             C = 1,
+                             m = 1.0))
Error in nlsModel(formula, mf, start, wts) :
  singular gradient matrix at initial parameter estimates
In addition: There were 30 warnings (use warnings() to see them)
> lines(Prey_isocline_x, predict(nls_fit), col = "green")
Error in predict(nls_fit) : object 'nls_fit' not found
</code>```

Fourth try:

```<code>nls_fit <- nls(Prey_isocline_y ~ a + b * Prey_isocline_x^(-c), Prey_isocline,
               start = list(a = 80, b = 20, c = 0.2))
lines(Prey_isocline_x, predict(nls_fit), col = "green")
</code>```

Fourth output:

```<code>> nls_fit <- nls(Prey_isocline_y ~ a + b * Prey_isocline_x^(-c), Prey_isocline,
+                start = list(a = 80, b = 20, c = 0.2))
Error in nls(Prey_isocline_y ~ a + b * Prey_isocline_x^(-c), Prey_isocline,  :
  step factor 0.000488281 reduced below 'minFactor' of 0.000976562
> lines(Prey_isocline_x, predict(nls_fit), col = "green")
Error in predict(nls_fit) : object 'nls_fit' not found
</code>```

I am completely lost and I hope someone can help me.

答:
Here's a partial answer on how to use plot a loess fit for your points.

```<code># to prevent typing in messy codes, change "X_isocline_x" to "x" & "X_isocline_y" to "y"
names(Prey_isocline) <- c("x", "y")
names(Predator_isocline) <- c("x", "y")
</code>```

Generate a loess model based on the Prey_isocline data:

```<code>model <- loess(y ~ x , Prey_isocline)
</code>```

Create a new data frame for the loess line to be plotted:

```<code>new.prey <- data.frame(x=Prey_isocline$x)
new.prey$fit <- predict(model, new.prey)
new.prey <- new.prey[order(new.prey$x),]
</code>```

Plotting loess line against the prey isocline values:

```<code>with(Prey_isocline, plot(x, y, ylim=c(0,5)))
with(new.prey, lines(x, fit))
</code>```

Repeat the steps for the predator

```<code>model <- loess(y ~ x , Predator_isocline)
new.prd <- data.frame(x=Predator_isocline$x)
new.prd$fit <- predict(model, new.prd)
new.prd <- new.prd[order(new.prd$x),]
</code>```

Add points for predator and loess line:

```<code>with(Predator_isocline, points(x,y, col="red", pch=16))
with(new.prd, lines(x, fit))
</code>```

Edit:

It would be easier to plot if both data-frames are combined.

```<code>dat <- list(prey=Prey_isocline, predator=Predator_isocline)

#to add type column for each data.frame, indicating "prey" or "predator"
dat.list <- lapply(names(dat), function(x){
                tmp <- dat[[x]]
                tmp$type <- x
                tmp
             })

df <- do.call(rbind, dat.list)

library(ggplot2)
ggplot(df, aes(x,y, colour=type)) + geom_point() +
   stat_smooth(method="loess", se=FALSE)
</code>```

Title: How can I fit a nonlinear line in R?

Body:
I am new to R and can't find an answer to this (seemingly) simple question. I have been searching for a couple of days, and did read a couple of papers and the help pages.

I have been able to plot one line (in red).

I want to plot another line fitted to the back dots. I expect the line to look like the black line in this image (by Křivan and Priyadarshi, 2015).

However, I have not been able to plot the line.

I have tried to fit the line using the following code, but nothing shows on the graph:

Values that I want to fit a line through:

Prey_isocline_x     <- c(8.2, 7.15, 7.65, 10.6, 7.947368421, 5.35,
                         6, 8.2, 7.473684211, 1.5, 1.3, 0.95, 1.85,
                         1.15, 0.6, 2.7, 1.3, 0.25, 0.25, 6.263157895,
                         4, 0.3, 5.1, 4.15, 1.15, 1.6, 1.6, 1.55)
Prey_isocline_y     <- c(0.45, 0.3, 0.2, 0.2, 0.105263158, 0.8, 0.5,
                         0.15, 0.052631579, 0.642857143, 1, 1, 1.15,
                         0.7, 0.55, 0.35, 0.8, 1.15, 1.55, 0.578947368,
                         0.5, 2.55, 0.15, 0.25, 0.45, 2.45, 2.45, 1.3)
Prey_isocline       <- data.frame(Prey_isocline_x, Prey_isocline_y)

Predator_isocline_x <- c(0.25, 0.15, 0.3, 0.7, 0.25, 0.25, 0.05, 0.5, 0.45,
                         0.5, 0.5, 0.15, 0.6, 1.4, 0.85, 0.15, 0.15, 0.6)
Predator_isocline_y <- c(2.35, 2.9, 3.6, 3.6, 2.35, 4.45, 1.45, 1.7, 1.65,
                         1.7, 2.9, 1.8, 1.9, 2.35, 2.9, 2.8, 2.5, 3.05)
Predator_isocline   <- data.frame(Predator_isocline_x, Predator_isocline_y)

First attempt to plot:

plot(Prey_isocline_x, Prey_isocline_y,
        axes = F,
        xlab= "",
        ylab= "",
        pch=1, col="black")
fit <- nls(Prey_isocline_y ~ SSlogis(Prey_isocline_x, Asym, xmid, scal),
       data=Prey_isocline,
       trace = TRUE)
summary(fit)
curve(predict(fit, newdata = data.frame(Prey_isocline_y=x)), add=TRUE)

Output first attempt:

> par(new=T)
> plot(Prey_isocline_x, Prey_isocline_y,
+         axes = F,
+         xlab= "",
+         ylab= "",
+         pch=1, col="black")
> fit <- nls(Prey_isocline_y ~ SSlogis(Prey_isocline_x, Asym, xmid, scal),
+            data=Prey_isocline,
+            trace = TRUE)
Error in nls(y ~ 1/(1 + exp((xmid - x)/scal)), data = xy, start = list(xmid = aux[1L],  :
  step factor 0.000488281 reduced below 'minFactor' of 0.000976562
> summary(fit)
Error in summary(fit) : object 'fit' not found
> curve(predict(fit, newdata = data.frame(Prey_isocline_y=x)), add=TRUE)
Error in predict(fit, newdata = data.frame(Prey_isocline_y = x)) :
  object 'fit' not found

Second try:

model <- loess(formula=Prey_isocline_x~Prey_isocline_y,
data=Predator_isocline)
abline(model, col="black")

Second output:

> model <- loess(formula=Prey_isocline_x~Prey_isocline_y, data=Predator_isocline)
> abline(model, col="black")

Third attempt:

nls_fit <- nls(Prey_isocline_y ~ (b*Prey_isocline_x) - (b*Prey_isocline_x*Prey_isocline_x/K) -
              (Predator_isocline_y*(Prey_isocline_x^k/(x^k+C^k)*(l*x/(1+l*h*x)))),
               data = Prey_isocline,
               start = list(b = 2.2,
                            e = 1.5,
                            K = 30,
                            k = 20,
                            l = 0.1,
                            h = 0.25,
                            C = 1,
                            m = 1.0))
lines(Prey_isocline_x, predict(nls_fit), col = "green")

Third output:

> nls_fit <- nls(Prey_isocline_y ~ (b*Prey_isocline_x) - (b*Prey_isocline_x*Prey_isocline_x/K) -
+               (Predator_isocline_y*(Prey_isocline_x^k/(x^k+C^k)*(l*x/(1+l*h*x)))),
+                data = Prey_isocline,
+                start = list(b = 2.2,
+                             e = 1.5,
+                             K = 30,
+                             k = 20,
+                             l = 0.1,
+                             h = 0.25,
+                             C = 1,
+                             m = 1.0))
Error in nlsModel(formula, mf, start, wts) :
  singular gradient matrix at initial parameter estimates
In addition: There were 30 warnings (use warnings() to see them)
> lines(Prey_isocline_x, predict(nls_fit), col = "green")
Error in predict(nls_fit) : object 'nls_fit' not found

Fourth try:

nls_fit <- nls(Prey_isocline_y ~ a + b * Prey_isocline_x^(-c), Prey_isocline,
               start = list(a = 80, b = 20, c = 0.2))
lines(Prey_isocline_x, predict(nls_fit), col = "green")

Fourth output:

> nls_fit <- nls(Prey_isocline_y ~ a + b * Prey_isocline_x^(-c), Prey_isocline,
+                start = list(a = 80, b = 20, c = 0.2))
Error in nls(Prey_isocline_y ~ a + b * Prey_isocline_x^(-c), Prey_isocline,  :
  step factor 0.000488281 reduced below 'minFactor' of 0.000976562
> lines(Prey_isocline_x, predict(nls_fit), col = "green")
Error in predict(nls_fit) : object 'nls_fit' not found

I am completely lost and I hope someone can help me.

Body:
Here's a partial answer on how to use plot a loess fit for your points.

# to prevent typing in messy codes, change "X_isocline_x" to "x" & "X_isocline_y" to "y"
names(Prey_isocline) <- c("x", "y")
names(Predator_isocline) <- c("x", "y")

Generate a loess model based on the Prey_isocline data:

model <- loess(y ~ x , Prey_isocline)

Create a new data frame for the loess line to be plotted:

new.prey <- data.frame(x=Prey_isocline$x)
new.prey$fit <- predict(model, new.prey)
new.prey <- new.prey[order(new.prey$x),]

Plotting loess line against the prey isocline values:

with(Prey_isocline, plot(x, y, ylim=c(0,5)))
with(new.prey, lines(x, fit))

Repeat the steps for the predator

model <- loess(y ~ x , Predator_isocline)
new.prd <- data.frame(x=Predator_isocline$x)
new.prd$fit <- predict(model, new.prd)
new.prd <- new.prd[order(new.prd$x),]

Add points for predator and loess line:

with(Predator_isocline, points(x,y, col="red", pch=16))
with(new.prd, lines(x, fit))

Edit:

It would be easier to plot if both data-frames are combined.

dat <- list(prey=Prey_isocline, predator=Predator_isocline)

#to add type column for each data.frame, indicating "prey" or "predator"
dat.list <- lapply(names(dat), function(x){
                tmp <- dat[[x]]
                tmp$type <- x
                tmp
             })

df <- do.call(rbind, dat.list)

library(ggplot2)
ggplot(df, aes(x,y, colour=type)) + geom_point() +
   stat_smooth(method="loess", se=FALSE)


问:
Kubernetes MySQL replication - Master service host inquiry
I currently have a working MySQL master and slave with asynchronous replication set up on a Kubernetes cluster.

I'm trying to plan for a contingency if the master goes down, the slave will pick up the slack and what not. I figured the first step would be to review the Dockerfiles and scripts that define the ENTRYPOINT within the Dockerfiles.

When I kubectl get svc, this is the information I get about the services.

This tells me on the cluster, the master has an IP 10.0.156.209.

Now when I flicked through the helper script docker-entrypoint.sh for the MySQL slave Docker image, I noticed this line which helps set up the master-slave scenario (I trimmed the line just to highlight this)

and when I boot into the slave pod on Kubernetes, the environment variable $MYSQL_MASTER_SERVICE_HOST is set to 10.0.156.209

My question: How did the MySQL slave pod know to use the master's cluster IP as the value for $MYSQL_MASTER_SERVICE_HOST? Is this a Kubernetes thing or a SQL thing?

Thank you :)

答:
These environment variables are created automatically by Kubernetes for each Service. See: https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#environment-variables

When a Pod is run on a Node, the kubelet adds a set of environment variables for each active Service.

On another note, mysql on Kubernetes is a complex topic. You probably don't want to roll your own solution. Have you looked at Vitess?


问:
Building a shared library created a static library instead
I am trying to build libass into a shared library with static linking under MinGW-w64. When I configure with

```<code>./configure --disable-static --enable-shared
</code>```

it generates the shared library (dynamically-linked) as expected. However, when I attempt to force static linking by setting

```<code>LDFLAGS=-static
</code>```

instead of generating a statically-linked shared library (.dll with no dependency), it generates a static library (.a).

I am almost certain that I have all the dependent static libraries and no error or warning message is shown in the make process.

Can anyone please shed some light on what I'm doing wrong?

答:
The static lib is just an ar package.
You can use command of ar to make the pack and unpack it.</p>

Body:
I am trying to build libass into a shared library with static linking under MinGW-w64. When I configure with

./configure --disable-static --enable-shared

it generates the shared library (dynamically-linked) as expected. However, when I attempt to force static linking by setting

LDFLAGS=-static

instead of generating a statically-linked shared library (.dll with no dependency), it generates a static library (.a).

I am almost certain that I have all the dependent static libraries and no error or warning message is shown in the make process.

Can anyone please shed some light on what I'm doing wrong?


问:
rails_admin gem filter with has_many_through association
In my application

Product has many categories through category_has_products

Category has many products through category_has_products

Initially, I used

at product.rb

```<code>default_scope { includes(:brand, :categories) }
</code>```

and in rails_admin config set it as

```<code>field :categories, :string do
 searchable [{Category => :name}]
end
</code>```

This works like a charm. This got into performance issues due to has_many_through(other pages using product details got affected)

So I removed the default_scope from product.

After that, I am getting

```<code>PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "categories"
</code>```

any idea on how to preload categories?

Note: rails_admin gem version is 0.8.1 only. I am not able to update to latest version 1.X.X

答:
I found answer

in product.rb

```<code>scope :include_categories, -> {includes(:categories)}
class << self
  alias_method :all_products, :include_categories
end
</code>```

admin_product_config.rb

```<code>from
    scopes %i[all brandless unmatched matched ignored fresh diy_only]
to
    scopes %i[all_products brandless unmatched matched ignored fresh diy_only]
</code>```

To add filter option

```<code>  field :categories, :string do
    searchable [{Category => :name}]
  end
  configure :categories do
    hide
  end
</code>```

Thank you @jxpx777
https://github.com/sferik/rails_admin/issues/1348#issuecomment-39373394

Body:
In my application

Product has many categories through category_has_products

Category has many products through category_has_products

Initially, I used

at product.rb

default_scope { includes(:brand, :categories) }

and in rails_admin config set it as

field :categories, :string do
 searchable [{Category => :name}]
end

This works like a charm. This got into performance issues due to has_many_through(other pages using product details got affected)

So I removed the default_scope from product.

After that, I am getting

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "categories"

any idea on how to preload categories?

Note: rails_admin gem version is 0.8.1 only. I am not able to update to latest version 1.X.X

Body:
I found answer

in product.rb

scope :include_categories, -> {includes(:categories)}
class << self
  alias_method :all_products, :include_categories
end

admin_product_config.rb

from
    scopes %i[all brandless unmatched matched ignored fresh diy_only]
to
    scopes %i[all_products brandless unmatched matched ignored fresh diy_only]

To add filter option

  field :categories, :string do
    searchable [{Category => :name}]
  end
  configure :categories do
    hide
  end

Thank you @jxpx777
https://github.com/sferik/rails_admin/issues/1348#issuecomment-39373394


问:
How to make list-menu display when it have class active?

jQuery(document).ready(function() {
  $(".list-menu").hide();
  $(".head-list a").click(function() {
    $(".list-menu:visible").slideUp('slow');
    $(".head-list").removeClass('active-menu');
    $(this).parent().addClass('active-menu').next().slideDown('slow');
    return false;
  });
  if ($(".list-menu ul li").hasClass('active')) {
    $(".list-menu").show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="head-list">Puchase</div>
<div class="list-menu">
  <ul>
    <li class="<?php if($page == 'home'){ echo 'active';} ?>">Purchase</li>
    <li>Purchase List</li>
    <li>Purchase3</li>
    <li>Purchase4</li>
    <li>Purchase5</li>
  </ul>
</div></code>```

I Wanna it to display the .list-menu that have ul li class active only.

Thank You for your answers.

答:
For convenience I would first hide .list-menu using:

```<code>$(".list-menu").css('display', 'none');
</code>```

Then instead of this:

```<code>if ($(".list-menu ul li").hasClass('active')) {
        $(".list-menu").show();
}
</code>```

I would run the selector in a loop to check for the class named 'active' as so:

```<code> $(".list-menu ul").each(function(e){
    if( $(this).hasClass('active')) {
         $(".list-menu").css('display', 'block');
         $(this).show();
      }else{
         $(this).hide();
      }
});
</code>```

Body:
jQuery(document).ready(function() {
  $(".list-menu").hide();
  $(".head-list a").click(function() {
    $(".list-menu:visible").slideUp('slow');
    $(".head-list").removeClass('active-menu');
    $(this).parent().addClass('active-menu').next().slideDown('slow');
    return false;
  });
  if ($(".list-menu ul li").hasClass('active')) {
    $(".list-menu").show();
  }
});

Puchase

    <li class="<?php if($page == 'home'){ echo 'active';} ?>">Purchase

Purchase List

Purchase3

Purchase4

Purchase5

I Wanna it to display the .list-menu that have ul li class active only.

Thank You for your answers.

Body:
For convenience I would first hide .list-menu using:

$(".list-menu").css('display', 'none');

Then instead of this:

if ($(".list-menu ul li").hasClass('active')) {
        $(".list-menu").show();
}

I would run the selector in a loop to check for the class named 'active' as so:

 $(".list-menu ul").each(function(e){
    if( $(this).hasClass('active')) {
         $(".list-menu").css('display', 'block');
         $(this).show();
      }else{
         $(this).hide();
      }
});


问:
Spark Application keeps on RUNNING and seems HANGING - org.apache.spark.sql.hive.thriftserver.HiveThriftServer2
I’m using HDFS 2.7.3 and Spark2 2.0.0 in Hadoop cluster. When I start Spark2 Thrift Server it successfully starts but automatically from Hive user a job starts to run and it seems to hang forever.  If I manually kill the job, again it starts a new job with a new applicationId.

But if I stop the Spark2 Thrift Server the it kills the job. Can you please help me to understand this issue?

Thanks in advance.

答: i have met the same issue like you, spark 2.0 is not stable of thriftserver module, it is better to upgrade to spark 2.1</p>


问:
Use virtualenv with Python with Visual Studio Code
I have a Python project and navigation/autocomplete work perfectly within files in the project. I want to specify a virtualenv so that navigation/autocomplete work with packages inside that virtualenv.

I tried this in settings.py, but navigation/autocomplete does not work. Also by setting "python.pythonPath":"~/dev/venvs/proj/bin/python killed the original navigation/autocomplete.

```<code>{
    "python.autoComplete.extraPaths": [
        "~/dev/venvs/proj",
        "~/dev/venvs/proj/lib"
     ]
}
</code>```

答:
Quite simple with the latest version of Visual Studio Code, if you have installed the official Python extension for Visual Studio Code:

Shift + Command + P

Type: Python: Select Interpreter

Choose your virtual environment.

Official site

Body:
I have a Python project and navigation/autocomplete work perfectly within files in the project. I want to specify a virtualenv so that navigation/autocomplete work with packages inside that virtualenv.

I tried this in settings.py, but navigation/autocomplete does not work. Also by setting "python.pythonPath":"~/dev/venvs/proj/bin/python killed the original navigation/autocomplete.

{
    "python.autoComplete.extraPaths": [
        "~/dev/venvs/proj",
        "~/dev/venvs/proj/lib"
     ]
}


问:
Silk Test - Record open dialog in Chrome
I'm using silk test 17.5 in order to record a .net script on a web application, in Chrome 51. I have to upload a file by a open dialog box.
What is the bets way to achieve it?

Thank you.

答:
Unfortunately it’s not possible to use action recording for uploading the file, but there are ways to achieve this via scripting.

If your file upload looks like the one on this sample page: http://the-internet.herokuapp.com/upload you can either type the name of the file to be uploaded directly into the upload control:

```<code>With _desktop.BrowserApplication()
  With .BrowserWindow()
    .DomTextField("//INPUT[@id='file-upload']").TypeKeys("c:\temp\test.txt")
    .DomButton("//INPUT[@id='file-submit']").Click()
    Workbench.Verify("test.txt", .DomElement("//DIV[@id='uploaded-files']").Text)
  End With
End With
</code>```

Or you can click on the upload control to bring up the "File Open" dialog and then automate that via the Win32 API:

```<code>With _desktop.BrowserApplication()
  With .BrowserWindow()
    .DomTextField("//INPUT[@id='file-upload']").Click()
  End With
End With

With _desktop.Dialog("@caption='Open'")
  .TextField("@caption='File name:'").SetText("c:\temp\test.txt")
  .PushButton("@caption='Open'").Select()
End With

With _desktop.BrowserApplication()
  With .BrowserWindow()
    .DomButton("//INPUT[@id='file-submit']").Click()
    Workbench.Verify("test.txt", .DomElement("//DIV[@id='uploaded-files']").Text)
  End With
End With
</code>```

Body:
Unfortunately it’s not possible to use action recording for uploading the file, but there are ways to achieve this via scripting.

If your file upload looks like the one on this sample page: http://the-internet.herokuapp.com/upload you can either type the name of the file to be uploaded directly into the upload control:

With _desktop.BrowserApplication()
  With .BrowserWindow()
    .DomTextField("//INPUT[@id='file-upload']").TypeKeys("c:\temp\test.txt")
    .DomButton("//INPUT[@id='file-submit']").Click()
    Workbench.Verify("test.txt", .DomElement("//DIV[@id='uploaded-files']").Text)
  End With
End With

Or you can click on the upload control to bring up the "File Open" dialog and then automate that via the Win32 API:

With _desktop.BrowserApplication()
  With .BrowserWindow()
    .DomTextField("//INPUT[@id='file-upload']").Click()
  End With
End With

With _desktop.Dialog("@caption='Open'")
  .TextField("@caption='File name:'").SetText("c:\temp\test.txt")
  .PushButton("@caption='Open'").Select()
End With

With _desktop.BrowserApplication()
  With .BrowserWindow()
    .DomButton("//INPUT[@id='file-submit']").Click()
    Workbench.Verify("test.txt", .DomElement("//DIV[@id='uploaded-files']").Text)
  End With
End With


问:
How to get data to Dropdownlist from database in html view
I am creating an web page in which have a Dropdownlist. I have to retrieve data for the drop_down_list from the database. Is there any way to get data from the database to the html view my html code:

<select name="drop down"><option value="1">@test.list[i]</option></select>

I got the database value to the list variable but I don't know how to pass the data to the html view. Please help me in this issue.Thanks

答:
You need to create Select List of Items :

Your Action with List of Items in View Bag :

```<code>public ActionResult ActionName()
{
 List<SelectListItem> Items = new List<SelectListItem>();
        CustReportName.Add(new SelectListItem() { Text = "List1", Value = "1", Selected = false });
        CustReportName.Add(new SelectListItem() { Text = "List2", Value = "2", Selected = true });
        ViewBag.ListItems = Items;
return View("ViewName");
}
</code>```

For Multiple values from database table:

```<code>public ActionResult ActionName()
{
IEnumerable<SelectListItem> ItemsList = from item in YourTableObject
select new SelectListItem
{
Value = Convert.ToString(item.Id),
Text = item.ItemName
};
ViewBag.ListItems = new SelectList(ItemsList, "Value", "Text");
return View("ViewName");
}
</code>```

Your DropdownList On view :

```<code>@Html.DropDownListFor(model => model.ItemId, new SelectList(ViewBag.ItemList, "Value", "Text", 0), "-Select Item-", new { @class = "form-control", @id = "ItemId" })
</code>```

Cheers !!

Body:
You need to create Select List of Items :

Your Action with List of Items in View Bag :

public ActionResult ActionName()
{
 List<SelectListItem> Items = new List<SelectListItem>();
        CustReportName.Add(new SelectListItem() { Text = "List1", Value = "1", Selected = false });
        CustReportName.Add(new SelectListItem() { Text = "List2", Value = "2", Selected = true });
        ViewBag.ListItems = Items;
return View("ViewName");
}

For Multiple values from database table:

public ActionResult ActionName()
{
IEnumerable<SelectListItem> ItemsList = from item in YourTableObject
select new SelectListItem
{
Value = Convert.ToString(item.Id),
Text = item.ItemName
};
ViewBag.ListItems = new SelectList(ItemsList, "Value", "Text");
return View("ViewName");
}

Your DropdownList On view :

@Html.DropDownListFor(model => model.ItemId, new SelectList(ViewBag.ItemList, "Value", "Text", 0), "-Select Item-", new { @class = "form-control", @id = "ItemId" })

Cheers !!