问:
D3D, Vertex From Mesh
By Using D3DXLoadMeshFromX, I could load a mesh's subsets, materials, textures,... So I succeed Draw Mesh.

What I want to know is that Mesh's Vertex Infomation(for picking).

My Code is..

```<code>    m_pMesh->PDIRECT3DVERTEXBUFFER9     pVB;
    m_pMesh->GetVertexBuffer(&pVB);

    void* Vtx = nullptr;
    pVB->Lock(0, 0, (void**)&Vtx, 0);
</code>```

Then I want to know Vtx's information like Vertex, but Vtx is void pointer...
If I know struct of that mesh I might know vertex info, but I don't

I'm sorry if I answer too vaguely.

答:
This is covered in the legacy DirectX SDK's sample in Samples\C++\Direct3D\Pick.

You have to use CloneMeshFVF to reformat the vertex data layout and you need to make sure you specify D3DXMESH_VB_MANAGED or D3DXMESH_VB_SYSTEMMEM so that you can actually lock the resulting VB.

```<code>   LPD3DXMESH pMesh;

    g_Mesh.GetMesh()->CloneMeshFVF( D3DXMESH_MANAGED,
                                    g_Mesh.GetMesh()->GetFVF(), pD3Device, &pMesh );

    LPDIRECT3DVERTEXBUFFER9 pVB;
    LPDIRECT3DINDEXBUFFER9 pIB;

    pMesh->GetVertexBuffer( &pVB );
    pMesh->GetIndexBuffer( &pIB );

    WORD* pIndices;
    D3DVERTEX* pVertices;

    pIB->Lock( 0, 0, ( void** )&pIndices, 0 );
    pVB->Lock( 0, 0, ( void** )&pVertices, 0 );
</code>```

Keep in mind that picking uses a CPU memory copy of the vertex data, while rendering uses a video memory copy. In real-time applications, you typically do not use the full complexity of the rendering model for collision, but a simplified collision model that you never need to render and only keep in memory.

Title: D3D, Vertex From Mesh

Body:
By Using D3DXLoadMeshFromX, I could load a mesh's subsets, materials, textures,... So I succeed Draw Mesh.

What I want to know is that Mesh's Vertex Infomation(for picking).

My Code is..

    m_pMesh->PDIRECT3DVERTEXBUFFER9     pVB;
    m_pMesh->GetVertexBuffer(&pVB);

    void* Vtx = nullptr;
    pVB->Lock(0, 0, (void**)&Vtx, 0);

Then I want to know Vtx's information like Vertex, but Vtx is void pointer...
If I know struct of that mesh I might know vertex info, but I don't

I'm sorry if I answer too vaguely.

Body:
This is covered in the legacy DirectX SDK's sample in Samples\C++\Direct3D\Pick.

You have to use CloneMeshFVF to reformat the vertex data layout and you need to make sure you specify D3DXMESH_VB_MANAGED or D3DXMESH_VB_SYSTEMMEM so that you can actually lock the resulting VB.

   LPD3DXMESH pMesh;

    g_Mesh.GetMesh()->CloneMeshFVF( D3DXMESH_MANAGED,
                                    g_Mesh.GetMesh()->GetFVF(), pD3Device, &pMesh );

    LPDIRECT3DVERTEXBUFFER9 pVB;
    LPDIRECT3DINDEXBUFFER9 pIB;

    pMesh->GetVertexBuffer( &pVB );
    pMesh->GetIndexBuffer( &pIB );

    WORD* pIndices;
    D3DVERTEX* pVertices;

    pIB->Lock( 0, 0, ( void** )&pIndices, 0 );
    pVB->Lock( 0, 0, ( void** )&pVertices, 0 );

Keep in mind that picking uses a CPU memory copy of the vertex data, while rendering uses a video memory copy. In real-time applications, you typically do not use the full complexity of the rendering model for collision, but a simplified collision model that you never need to render and only keep in memory.


来源: stackexchange

问:
How to share global variables between tests?
I have a global variable in conftest.py and use it in tests. For example:

conftest.py

```<code>api_version = 'v25'
api_url = 'http://www.foobar.com/' + api_version
</code>```

test_foo.py

```<code>from conftest import api_url
import requests

@pytest.fixture
def data():
    return requests.request("GET", api_url)

test_bar(data):
    assert data is not None
</code>```

Now I want to be able to change api_version from cmd for testing other api version. So I modified conftest.py in the following way:

conftest.py

```<code>api_url = None

def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")

@pytest.fixture(autouse=True, scope='session')
def cmd_param(pytestconfig):
    api_version = pytestconfig.getoption("--mobile_api_ver").lower()
    global api_url
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        api_url = 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)
</code>```

But this doesn't work as I expected because all imports execute before fixtures and test_foo import api_url = None before cmd_param fixture redefines this.
Then i write get_api_url method and call it from test module:

conftest.py

```<code>api_url = None

def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")

@pytest.fixture(autouse=True, scope='session')
def cmd_param(pytestconfig):
    api_version = pytestconfig.getoption("--mobile_api_ver").lower()
    global api_url
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        api_url = 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)

def get_api_url():
    return api_url
</code>```

But now I was forced to change test_foo.py too:

test_foo.py

```<code>from conftest import get_api_url
import requests

@pytest.fixture
def data():

    return requests.request("GET", get_api_url())

test_bar(data):
    assert data is not None
</code>```

It works, but solution looks awkward. Is there a more elegant way to use custom cmd options without changing test files?

答:
I just try to get it work without complete changing your code. I hope it could give you some idea.

in conftest.py

```<code>api_url_by_option = None

def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")

@pytest.fixture(autouse=True, scope='session')
def cmd_param(pytestconfig):
    api_version = pytestconfig.getoption("--mobile_api_ver").lower()
    global api_url_by_option
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        api_url_by_option = 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)

@pytest.fixture:
def api_url():
    return api_url_by_option
</code>```

in test_foo.py you don't need to import api_url. Please notice that the api_url fixture from conftest.py is used in fixture data

```<code>import requests

@pytest.fixture
def data(api_url):
    return requests.request("GET", api_url)

test_bar(data):
    assert data is not None
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a global variable in conftest.py and use it in tests. For example:

conftest.py

api_version = 'v25'
api_url = 'http://www.foobar.com/' + api_version

test_foo.py

from conftest import api_url
import requests

@pytest.fixture
def data():
    return requests.request("GET", api_url)

test_bar(data):
    assert data is not None

Now I want to be able to change api_version from cmd for testing other api version. So I modified conftest.py in the following way:

conftest.py

api_url = None

def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")

@pytest.fixture(autouse=True, scope='session')
def cmd_param(pytestconfig):
    api_version = pytestconfig.getoption("--mobile_api_ver").lower()
    global api_url
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        api_url = 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)

But this doesn't work as I expected because all imports execute before fixtures and test_foo import api_url = None before cmd_param fixture redefines this.
Then i write get_api_url method and call it from test module:

conftest.py

api_url = None

def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")

@pytest.fixture(autouse=True, scope='session')
def cmd_param(pytestconfig):
    api_version = pytestconfig.getoption("--mobile_api_ver").lower()
    global api_url
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        api_url = 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)

def get_api_url():
    return api_url

But now I was forced to change test_foo.py too:

test_foo.py

from conftest import get_api_url
import requests

@pytest.fixture
def data():

    return requests.request("GET", get_api_url())

test_bar(data):
    assert data is not None

It works, but solution looks awkward. Is there a more elegant way to use custom cmd options without changing test files?

Body:
I just try to get it work without complete changing your code. I hope it could give you some idea.

in conftest.py

api_url_by_option = None

def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")

@pytest.fixture(autouse=True, scope='session')
def cmd_param(pytestconfig):
    api_version = pytestconfig.getoption("--mobile_api_ver").lower()
    global api_url_by_option
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        api_url_by_option = 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)

@pytest.fixture:
def api_url():
    return api_url_by_option

in test_foo.py you don't need to import api_url. Please notice that the api_url fixture from conftest.py is used in fixture data

import requests

@pytest.fixture
def data(api_url):
    return requests.request("GET", api_url)

test_bar(data):
    assert data is not None


问:
c# hosted rest service return 404
I've implemented my controller in c#

```<code>[ServiceContract(Name = "UserController")]
public interface ApiController
{
    Task<HttpResponseMessage> SignUp(LoginModel model);

    Task<HttpResponseMessage> Login(LoginModel model);

}

namespace Nerder_Backend.Controllers
{
    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
        private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
        private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];

        [Route("signup")]
        [HttpPost]
        public async Task<HttpResponseMessage> SignUp(LoginModel model)
        {
            if (model == null || !model.IsValid())
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Invalid email and/or password")
                };
                return response;
            }
</code>```

and then I'm trying to host it to be possible to call it via AJAX on jquery, because my app will be mobile cross plaform and I have to separate client side to server side, anyway, that's the hosting main method:

```<code>static void Main(string[] args)
        {

            var baseAddress = "http://localhost:8080";
            var config = new HttpSelfHostConfiguration(baseAddress);
            CouchbaseConfig.Register();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            config.MapHttpAttributeRoutes();//map attribute routes
                                            // Create the server
            using (var server = new HttpSelfHostServer(config))
            {
            server.OpenAsync().Wait();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
    }
</code>```

The host start and it's listening but when I call the URL via javascript i get a 404 error message.

HTTP status code 404.

This is the javascript code:

```<code> $.ajax({
            type: 'post',
            url: 'http://localhost:8080/api/user/signup',
</code>```

I used also CORS enabler for chrome, how can i check if in any way my path is valid? Should I change the way I host my sevice?

This is my app.config if it can help:

```<code> <system.webServer>
    <!-- ENABLE REST SERVICES -->
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <!--END -->
  </system.webServer>

  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Couchbase.NetClient" publicKeyToken="05e9c6b5a9ec94c2" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.4.5.0" newVersion="2.4.5.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.Core" publicKeyToken="407dd0808d44fbdc" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>
</code>```

答:
How are you hosting your service?

How are you ensuring the port is actually 8080 when the service is running?
- it could be giving 404 error because it is the wrong port

If, for example, your service only exists in Visual Studio and you hit F5 to start debugging and it auto opens a new window for you in your browser, and you see the the "IIS Express" icon in the bottom right taskbar area: the port can vary.

ContentLicense: CC BY-SA 3.0

Title: c# hosted rest service return 404

Body:
I've implemented my controller in c#

[ServiceContract(Name = "UserController")]
public interface ApiController
{
    Task<HttpResponseMessage> SignUp(LoginModel model);

    Task<HttpResponseMessage> Login(LoginModel model);

}

namespace Nerder_Backend.Controllers
{
    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
        private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
        private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];

        [Route("signup")]
        [HttpPost]
        public async Task<HttpResponseMessage> SignUp(LoginModel model)
        {
            if (model == null || !model.IsValid())
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Invalid email and/or password")
                };
                return response;
            }

and then I'm trying to host it to be possible to call it via AJAX on jquery, because my app will be mobile cross plaform and I have to separate client side to server side, anyway, that's the hosting main method:

static void Main(string[] args)
        {

            var baseAddress = "http://localhost:8080";
            var config = new HttpSelfHostConfiguration(baseAddress);
            CouchbaseConfig.Register();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            config.MapHttpAttributeRoutes();//map attribute routes
                                            // Create the server
            using (var server = new HttpSelfHostServer(config))
            {
            server.OpenAsync().Wait();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
    }

The host start and it's listening but when I call the URL via javascript i get a 404 error message.

HTTP status code 404.

This is the javascript code:

 $.ajax({
            type: 'post',
            url: 'http://localhost:8080/api/user/signup',

I used also CORS enabler for chrome, how can i check if in any way my path is valid? Should I change the way I host my sevice?

This is my app.config if it can help:

 <system.webServer>

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>

  </system.webServer>

  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Couchbase.NetClient" publicKeyToken="05e9c6b5a9ec94c2" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.4.5.0" newVersion="2.4.5.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.Core" publicKeyToken="407dd0808d44fbdc" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>


问:
Devise - How to trigger a sign_in on page user already has access to
I am using Devise 3.5.2.  I have an Item model with a show action that anyone can access( before_filter :authenticate_user!, except: :show). On the show page I have a button that triggers a file upload dialog using jquery.

I only want this upload dialog to work for logged in users. If a user is logged out and they click the button I want it to bring them to my login page. When they login I want it to take them back to the show page.

How can I make it so clicking this link brings them to the login page and then after logging in they are redirected to the page they were just on and already had access to?

```<code><% unless current_user %>
  <%= link_to "Upload image", item_path @item, class: "btn btn-lg btn-success" %>
<% end %>
</code>```

This won't work because they already have access to this page.

EDIT: I tried following this link here https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in but it doesn't seem to be working.

My sessions controller looks like this. Maybe my create method is causing a conflict?

```<code>class SessionsController < Devise::SessionsController

   def new
     self.resource = resource_class.new(sign_in_params)
     store_location_for(resource, params[:redirect_to])
     super
   end

  def create
    self.resource = warden.authenticate!(auth_options)
    if resource.deactivated?
      set_flash_message(:notice, :reactivated) if is_flashing_format?
      resource.reactivate
    end
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end
end
</code>```

答:
Since you are already using before_action :authenticate_user! in your controller for validating logged_in users..you just need to override that method to redirect to whatever page you like e.g.

In your application_controller.rb,

```<code>def authenticate_user!
  if user_signed_in?
    super
  else
    redirect_to whatever_path
  end
end
</code>```

Body:
I am using Devise 3.5.2.  I have an Item model with a show action that anyone can access( before_filter :authenticate_user!, except: :show). On the show page I have a button that triggers a file upload dialog using jquery.

I only want this upload dialog to work for logged in users. If a user is logged out and they click the button I want it to bring them to my login page. When they login I want it to take them back to the show page.

How can I make it so clicking this link brings them to the login page and then after logging in they are redirected to the page they were just on and already had access to?

<% unless current_user %>
  <%= link_to "Upload image", item_path @item, class: "btn btn-lg btn-success" %>
<% end %>

This won't work because they already have access to this page.

EDIT: I tried following this link here https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in but it doesn't seem to be working.

My sessions controller looks like this. Maybe my create method is causing a conflict?

class SessionsController < Devise::SessionsController

   def new
     self.resource = resource_class.new(sign_in_params)
     store_location_for(resource, params[:redirect_to])
     super
   end

  def create
    self.resource = warden.authenticate!(auth_options)
    if resource.deactivated?
      set_flash_message(:notice, :reactivated) if is_flashing_format?
      resource.reactivate
    end
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end
end

Body:
Since you are already using before_action :authenticate_user! in your controller for validating logged_in users..you just need to override that method to redirect to whatever page you like e.g.

In your application_controller.rb,

def authenticate_user!
  if user_signed_in?
    super
  else
    redirect_to whatever_path
  end
end


问:
Active Directory/C#: Get users in single domain with multiple OUs?
I am currently trying to pull all of the users in my organization from a security group called Y under a security group called X. I have tried multiple different approaches to this and am starting to reach my wits end with it. I am currently back to the DirectoryEntry method of trying to retrieve my users, but was previously trying the PrincipalContext method. The PrincipalContext method works very well for retrieving my servers, but they are members of singular top-level groups. Group Y is nested under group X which is grouped like so: A -> B -> C -> D -> X -> Y. Another possible problem I see is the distinguishedName property has the OUs in what appears to be an unorganized manner so I'm sensing the order doesn't matter when it comes to AD? But I would assume when querying with wild cards the order somewhat matters?

The distinguishedName property is structured like so (pseudo to save typing): CN=User Name, OUs=Y, D, X, C, B, A, DCs=a, b, c, net

Below is my current code to pull users:

```<code>        private static void GetUsers() {
        int x = 0;

        DirectoryEntry dm = new DirectoryEntry("LDAP://a.b.c.net");
        DirectorySearcher searcher = new DirectorySearcher(dm);

        searcher.Filter = "(&(objectClass=user)(distinguishedName=*OU=Y*OU=X*))";
        searcher.PropertiesToLoad.AddRange(new string[4] {"name", "samAccountName", "userPrincipalName", "mail"});

        foreach (SearchResult result in searcher.FindAll()) {
            Console.WriteLine(string.Format("Name: {0}\nSAM: {1}\nPrincipal: {2}\nMail: {3}",
                                            result.Properties["name"],
                                            result.Properties["samAccountName"],
                                            result.Properties["userPrincipalName"],
                                            result.Properties["mail"]));
            x++;
        }

        Console.WriteLine("User Count: " + x);
    }
</code>```

I am assuming this is an issue with my filter since the code executes completely and prints a user count of zero. I am finding it hard to understand how the wild card works and have found very little information on how to pull users from sub-groups and to narrow things down. I work for a very, very, large organization so just pulling all users in the domain would not only take a lot of time, but would also return tens of thousands of records.

Please help?!?!?!?!?
-Thanks,
Jamie

答:
So after hours of research and no luck here on Stack Overflow, I figured out that it was a combination of my domain and filter. I had to add the OU list to the end of the DNS in the supplied domain. Also, the filter needed to be narrowed down and I had to removed the distinguishedName property and just filter the name and sn properties.</p>

```<code>using (DirectoryEntry entry = new DirectoryEntry("LDAP://a.b.c.net/OU=Y,OU=D,OU=X,OU=C,OU=B,OU=A,DC=a,DC=b,DC=c,DC=net"))
mySearcher.Filter = ("(&(objectClass=user)(&(|(name=*1*)(name=*2*))(!(sn=*.*))))");
</code>```

Body:
I am currently trying to pull all of the users in my organization from a security group called Y under a security group called X. I have tried multiple different approaches to this and am starting to reach my wits end with it. I am currently back to the DirectoryEntry method of trying to retrieve my users, but was previously trying the PrincipalContext method. The PrincipalContext method works very well for retrieving my servers, but they are members of singular top-level groups. Group Y is nested under group X which is grouped like so: A -> B -> C -> D -> X -> Y. Another possible problem I see is the distinguishedName property has the OUs in what appears to be an unorganized manner so I'm sensing the order doesn't matter when it comes to AD? But I would assume when querying with wild cards the order somewhat matters?

The distinguishedName property is structured like so (pseudo to save typing): CN=User Name, OUs=Y, D, X, C, B, A, DCs=a, b, c, net

Below is my current code to pull users:

        private static void GetUsers() {
        int x = 0;

        DirectoryEntry dm = new DirectoryEntry("LDAP://a.b.c.net");
        DirectorySearcher searcher = new DirectorySearcher(dm);

        searcher.Filter = "(&(objectClass=user)(distinguishedName=*OU=Y*OU=X*))";
        searcher.PropertiesToLoad.AddRange(new string[4] {"name", "samAccountName", "userPrincipalName", "mail"});

        foreach (SearchResult result in searcher.FindAll()) {
            Console.WriteLine(string.Format("Name: {0}\nSAM: {1}\nPrincipal: {2}\nMail: {3}",
                                            result.Properties["name"],
                                            result.Properties["samAccountName"],
                                            result.Properties["userPrincipalName"],
                                            result.Properties["mail"]));
            x++;
        }

        Console.WriteLine("User Count: " + x);
    }

I am assuming this is an issue with my filter since the code executes completely and prints a user count of zero. I am finding it hard to understand how the wild card works and have found very little information on how to pull users from sub-groups and to narrow things down. I work for a very, very, large organization so just pulling all users in the domain would not only take a lot of time, but would also return tens of thousands of records.

Please help?!?!?!?!?
-Thanks,
Jamie

Body:
So after hours of research and no luck here on Stack Overflow, I figured out that it was a combination of my domain and filter. I had to add the OU list to the end of the DNS in the supplied domain. Also, the filter needed to be narrowed down and I had to removed the distinguishedName property and just filter the name and sn properties.

using (DirectoryEntry entry = new DirectoryEntry("LDAP://a.b.c.net/OU=Y,OU=D,OU=X,OU=C,OU=B,OU=A,DC=a,DC=b,DC=c,DC=net"))
mySearcher.Filter = ("(&(objectClass=user)(&(|(name=*1*)(name=*2*))(!(sn=*.*))))");


问:
Very high performance .Net-based engine for handling web requests
I have a need for a simple, lightweight .Net-based web server engine that will comfortably serve hundreds (or even thousands) of simultaneous requests without breaking a sweat.

I love the idea of node.js but it's only got one .Net port and it seems to have some significant limitations in the forming of blocking writes and hasn't been developed any further since the author quickly whipped it together. Has anyone used it for high performance stuff?

What alternatives are there? Do we really need to be developing something custom?

答:
I'll assume from the fact that you're asking this that IIS won't work for you (because if there was any chance that IIS would work, I would suggest using it instead).

You could check out Manos (an entire framework with its own Web Server).

You could also try the re-distributable version of Cassini.

ContentLicense: CC BY-SA 2.5


问:
Bootstrap Navigation Toggle Not Working
I am having trouble getting my navigation toggle to work on mobile. The toggle button appears, and when I click it, my "Social" dropdown menu appears to the left of the toggle button. It doesn't show my other navigation links either.

You can find my code on codepen: https://codepen.io/jeremycollins/pen/VWvWme

Here is the code. I am using Bootstrap 3.3.7:

body {
 background-color: #222222;
 color: #fff;
 font-family: 'Overclock' arial;
 }

#bio {
 color: #fff;
 margin-top: 50px;
 font-weight: 400;
 padding-left: 30px;
 }

#jeremy {
 margin-left: 100px;
 font-weight: 900;
 }

.jumbotron {background-color: #222222;}

.profile {
 border-radius: 50%;
 float: right;
 }

.navbar-brand {font-weight: 900;
}

#tagline {font-weight: 700;}

.thumbnails {

}
span {
 display: inline-block;
 vertical-align: middle;
 }

.outer-line {
 width: 20%;
 border-bottom: 3px solid white;
 margin-top: 16px;
 }

.spacer {margin-top: 100px;}

button {color: #fff;}

.btn {background-color: #222222;}

.btn:hover {color: grey;}

#footercopy {margin-top: 16px;}

.icon-bar {
  color: white;
}

.navbar {
  height:50px;
}

.nav.navbar-left{
  bottom: 0;
  left: 0;
  position:absolute;
}

.nav.navbar-right{
  bottom: 0;
  right: 100px;
  position:absolute;
}

.dropdown-menu {
  background-color: #222222;
}

.dropdown-menu>li>a {
  color:#fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      Jeremy Collins
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <li>Home</li>
        <li>Portfolio</li>
        <li>Contact</li>
        <li class="dropdown">
          Social Links <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Facebook</li>
            <li>Twitter</li>
            <li>LinkedIn</li>
            <li role="separator" class="divider"></li>
            <li>GitHub</li>
            <li>freeCodeCamp</li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

<div class="container">
  <div class="spacer"></div>
    <div class="jumbotron">
        <div class="col-md-8">

            <h1>Hello, </h1>
            <h1 id="jeremy">I'm Jeremy!</h1>
            <p id="bio">Full Stack Developer, System Administrator, & Entrepreneur</p>
        </div>
        <div class="col-md-4">
            <img class="img-responsive profile" src="https://avatars1.githubusercontent.com/u/20449608?v=3&u=3028ad3dd7f5185b62b69ba4ad957e5ae7cacacf&s=400" alt="Jeremy Collins">
        </div>
    </div>
    <div class="container">
        <div class="col-md-12">
            <div class="text-center">
                <div class="spacer"></div>
                <span class="outer-line"></span>
                <span aria-hidden="true" style="margin:10px 0">
                    <h1>{ Portfolio }</h1>

                </span>
                <span class="outer-line"></span>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="col-md-6">
            <div class="text-center">
                <p><img class="center-block img-responsive" src="http://placehold.it/400x150/000000/FFFFFF&text=Project+1!"></img></p>
                <p><img class="center-block img-responsive" src="http://placehold.it/400x150/000000/FFFFFF&text=Project+3!"></img></p>
                <p><img class="center-block img-responsive" src="http://placehold.it/400x150/000000/FFFFFF&text=Project+5!"></img></p>
            </div>
        </div>
        <div class="col-md-6">
            <div class="text-center">
                <p><img class="center-block img-responsive" src="http://placehold.it/400x150/000000/FFFFFF&text=Project+2!"></img></p>
                <p><img class="center-block img-responsive" src="http://placehold.it/400x150/000000/FFFFFF&text=Project+4!"></img></p>
                <p><img class="center-block img-responsive" src="http://placehold.it/400x150/000000/FFFFFF&text=Project+6!"></img></p>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="col-md-12">
            <div class="text-center">
                <div class="spacer"></div>
                <span class="outer-line"></span>
                <span aria-hidden="true" style="margin:10px 0">
                    <h1>{ Contact }</h1>

                </span>
                <span class="outer-line"></span>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="col-md-12">
            <form>
                <div class="form-group">
                    <label>Email address</label>
                    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
                    <small id="emailHelp" class="form-text text-muted">I'll never share your email with anyone else.</small>
                </div>
                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" class="form-control" placeholder="Name">
                </div>
                <div class="form-group">
                    <label>Message</label>
                    <textarea class="form-control" placeholder="Enter your message..."></textarea>
                    <button type="submit" class="btn btn-inverse btn-block"><i class="fa fa-envelope"></i> Submit</button>
            </form>
            </div>
        </div>
    </div>
</div>
<div class="fluid-width">
<nav class="navbar navbar-inverse">
    <div class="container-fluid">
        <h4 class="text-center" id="footercopy">&copy 2017 Jeremy Collins</h4>
    </div>
</nav>
</div>

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script></code>```

答:
Do you have the right bootstrap  links in
check if you have this link:
which is the JS

```<code> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

Title: Bootstrap Navigation Toggle Not Working

Body:
I am having trouble getting my navigation toggle to work on mobile. The toggle button appears, and when I click it, my "Social" dropdown menu appears to the left of the toggle button. It doesn't show my other navigation links either.

You can find my code on codepen: https://codepen.io/jeremycollins/pen/VWvWme

Here is the code. I am using Bootstrap 3.3.7:

body {
 background-color: #222222;
 color: #fff;
 font-family: 'Overclock' arial;
 }

#bio {
 color: #fff;
 margin-top: 50px;
 font-weight: 400;
 padding-left: 30px;
 }

#jeremy {
 margin-left: 100px;
 font-weight: 900;
 }

.jumbotron {background-color: #222222;}

.profile {
 border-radius: 50%;
 float: right;
 }

.navbar-brand {font-weight: 900;
}

#tagline {font-weight: 700;}

.thumbnails {

}
span {
 display: inline-block;
 vertical-align: middle;
 }

.outer-line {
 width: 20%;
 border-bottom: 3px solid white;
 margin-top: 16px;
 }

.spacer {margin-top: 100px;}

button {color: #fff;}

.btn {background-color: #222222;}

.btn:hover {color: grey;}

#footercopy {margin-top: 16px;}

.icon-bar {
  color: white;
}

.navbar {
  height:50px;
}

.nav.navbar-left{
  bottom: 0;
  left: 0;
  position:absolute;
}

.nav.navbar-right{
  bottom: 0;
  right: 100px;
  position:absolute;
}

.dropdown-menu {
  background-color: #222222;
}

.dropdown-menu>li>a {
  color:#fff;
}

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Jeremy Collins

Home

Portfolio

Contact

          Social Links

Facebook

Twitter

LinkedIn

GitHub

freeCodeCamp

Hello,

I'm Jeremy!

Full Stack Developer, System Administrator, & Entrepreneur

{ Portfolio }

{ Contact }

            <form>

                    Email address
                    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
                    I'll never share your email with anyone else.

                    Full Name
                    <input type="text" class="form-control" placeholder="Name">

                    Message
                    <textarea class="form-control" placeholder="Enter your message..."></textarea>
                    <button type="submit" class="btn btn-inverse btn-block"> Submit</button>
            </form>

&copy 2017 Jeremy Collins

Body:
Do you have the right bootstrap  links in <head>
check if you have this link:
which is the JS

 <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


问:
Rethinkdb string match two arrays
I have two arrays containing only strings that I would like to match.

I cannot use contains or setIntersection because I want case insensitive match to work as well.

I have tried many different ways but I have not found a working solution. I think this is the best I have came up with so far, but it does not work:

```<code>r.db( 'my_db' ).table( 'Table' ).hasFields( 'tags' ).filter( function( row ) {
  return row( 'tags' ).filter( function( t ) {
    return r.expr( [ 'Foo', 'Bar', 'FooBar' ] ).filter( function( m ) {
      return t.match( '(?i)^' + m + '$' );
    } ).count().gt( 0 );
  } ).count().gt( 0 );
} );
</code>```

the tags column is an arrays of strings. But I think the problem is that m is not a string so I cannot use it with match. But how can I convert it to a string? I have tried coerceTo but that does not work.

Any ides on how to make this work?

答:
You should be able to get your query to work by using .add() instead of +, for example:

```<code>r.expr('(?i)^').add(m).add('$')
</code>```

You could also try something like this instead:

```<code>r.db('my_db').table('Table').hasFields('tags').filter(row =>
  row('tags').map(x => x.upcase()).setIntersect(['FOO', 'BAR', 'FOOBAR']).isEmpty().not())
</code>```

Title: Rethinkdb string match two arrays

Body:
I have two arrays containing only strings that I would like to match.

I cannot use contains or setIntersection because I want case insensitive match to work as well.

I have tried many different ways but I have not found a working solution. I think this is the best I have came up with so far, but it does not work:

r.db( 'my_db' ).table( 'Table' ).hasFields( 'tags' ).filter( function( row ) {
  return row( 'tags' ).filter( function( t ) {
    return r.expr( [ 'Foo', 'Bar', 'FooBar' ] ).filter( function( m ) {
      return t.match( '(?i)^' + m + '$' );
    } ).count().gt( 0 );
  } ).count().gt( 0 );
} );

the tags column is an arrays of strings. But I think the problem is that m is not a string so I cannot use it with match. But how can I convert it to a string? I have tried coerceTo but that does not work.

Any ides on how to make this work?

Body:
You should be able to get your query to work by using .add() instead of +, for example:

r.expr('(?i)^').add(m).add('$')

You could also try something like this instead:

r.db('my_db').table('Table').hasFields('tags').filter(row =>
  row('tags').map(x => x.upcase()).setIntersect(['FOO', 'BAR', 'FOOBAR']).isEmpty().not())


问:
BigQuery php client library queryresult shows isComplete false. But I can confirm the query is successful
```<code>$queryResults = $this->bigQuery->runQuery($query, ['parameters' => ['id' => $id]]);

    $info = $queryResults->info();

    var_dump($info);

    // var_dump($queryResults);

    $isComplete = $queryResults->isComplete();

    if ($isComplete) {
        exit("Insert. Done!");
    }
</code>```

The query is a "insert select" statement. which I had run successful on bigquery cloud console directly.

When I use php client library here, the query finished successful too and I can confirm that it is the same as I run query directly on google cloud console.

But the info of the query shows isComplete false.

```<code>array(3) {
["kind"]=>
string(22) "bigquery#queryResponse"
["jobReference"]=>
array(2) {
["projectId"]=>
string(26) "myprojectid"
["jobId"]=>
string(31) "job_OHcckVSSwAI7pHXijmmUqK5H4XE"
}
["jobComplete"]=>
bool(false)
}
</code>```

There are no errors report form the $queryResults->info();. How could I find out why it shows me isComplete false?

答:
Probably you still need to run $queryResults -> reload() to update the job status. As in the docs:

```<code>$isComplete = $queryResults->isComplete();

while (!$isComplete) {
    sleep(1); // small delay between requests
    $queryResults->reload();
    $isComplete = $queryResults->isComplete();
}
</code>```

Body:
$queryResults = $this->bigQuery->runQuery($query, ['parameters' => ['id' => $id]]);

    $info = $queryResults->info();

    var_dump($info);

    // var_dump($queryResults);

    $isComplete = $queryResults->isComplete();

    if ($isComplete) {
        exit("Insert. Done!");
    }

The query is a "insert select" statement. which I had run successful on bigquery cloud console directly.

When I use php client library here, the query finished successful too and I can confirm that it is the same as I run query directly on google cloud console.

But the info of the query shows isComplete false.

array(3) {
["kind"]=>
string(22) "bigquery#queryResponse"
["jobReference"]=>
array(2) {
["projectId"]=>
string(26) "myprojectid"
["jobId"]=>
string(31) "job_OHcckVSSwAI7pHXijmmUqK5H4XE"
}
["jobComplete"]=>
bool(false)
}

There are no errors report form the $queryResults->info();. How could I find out why it shows me isComplete false?

Body:
Probably you still need to run $queryResults -> reload() to update the job status. As in the docs:

$isComplete = $queryResults->isComplete();

while (!$isComplete) {
    sleep(1); // small delay between requests
    $queryResults->reload();
    $isComplete = $queryResults->isComplete();
}


问:
OpenCV VideoCapture says video has 0 frames (C++ and Python)
I'm using OpenCV 2.4.9 and trying to open a video. isOpened() successfully runs, but when I try to look at the number of frames the video has, it returns 0, and I can't access the frames of the video. This happens with every video I have. I can use the same videos on a different machine (the issue happens in my CentOS 7 VM, the videos are in a shared folder and the host OS can access them fine in OpenCV). Ffmpeg is installed and I can ffplay the videos and ffmpeg -i tells me the videos have a nonzero number of frames. My OpenCV was compiled with ffmpeg successfully:

```<code>"  Video I/O:\n"
"    DC1394 1.x:                  NO\n"
"    DC1394 2.x:                  YES (ver 2.2.2)\n"
"    FFMPEG:                      YES\n"
"      codec:                     YES (ver 56.26.100)\n"
"      format:                    YES (ver 56.25.101)\n"
"      util:                      YES (ver 54.20.100)\n"
"      swscale:                   YES (ver 3.1.101)\n"
"      gentoo-style:              YES\n"
"    GStreamer:                   \n"
"      base:                      YES (ver 0.10.36)\n"
"      app:                       YES (ver 0.10.36)\n"
"      video:                     YES (ver 0.10.36)\n"
"    OpenNI:                      NO\n"
"    OpenNI PrimeSensor Modules:  NO\n"
"    PvAPI:                       NO\n"
"    GigEVisionSDK:               NO\n"
"    UniCap:                      NO\n"
"    UniCap ucil:                 NO\n"
"    V4L/V4L2:                    Using libv4l (ver 0.9.5)\n"
"    XIMEA:                       NO\n"
"    Xine:                        NO\n"
"\n"
</code>```

My code correctly compiles and I can read images with OpenCV.

The code is incredibly basic. For Python:

```<code>import cv2
cap = cv2.VideoCapture('test.mp4')
print cap.isOpened()
print cap.get(cv2.cv.CV_CAP_PROP_FPS)
print cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)
>> True
>> 0.0
>> 0
</code>```

And for C++:

```<code>#include "opencv2/opencv.hpp"
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
    cv::VideoCapture cap;
    cap.open("test.mp4");
    if(cap.isOpened())
    {
        cout >> cap.get(CV_CAP_PROP_FPS) >> endl;
        cout >> cap.get(CV_CAP_PROP_FRAME_COUNT) >> endl;
    }
    return(0);
}
</code>```

Which prints 0 as well.

答:
This looks similar to the codec issues I had, and described in this stack overflow post. In short: I used ffmpeg to convert the video:

ffmpeg -i input.avi -c:v libx264 -vf format=yuv420p output.mp4

Body:
I'm using OpenCV 2.4.9 and trying to open a video. isOpened() successfully runs, but when I try to look at the number of frames the video has, it returns 0, and I can't access the frames of the video. This happens with every video I have. I can use the same videos on a different machine (the issue happens in my CentOS 7 VM, the videos are in a shared folder and the host OS can access them fine in OpenCV). Ffmpeg is installed and I can ffplay the videos and ffmpeg -i tells me the videos have a nonzero number of frames. My OpenCV was compiled with ffmpeg successfully:

"  Video I/O:\n"
"    DC1394 1.x:                  NO\n"
"    DC1394 2.x:                  YES (ver 2.2.2)\n"
"    FFMPEG:                      YES\n"
"      codec:                     YES (ver 56.26.100)\n"
"      format:                    YES (ver 56.25.101)\n"
"      util:                      YES (ver 54.20.100)\n"
"      swscale:                   YES (ver 3.1.101)\n"
"      gentoo-style:              YES\n"
"    GStreamer:                   \n"
"      base:                      YES (ver 0.10.36)\n"
"      app:                       YES (ver 0.10.36)\n"
"      video:                     YES (ver 0.10.36)\n"
"    OpenNI:                      NO\n"
"    OpenNI PrimeSensor Modules:  NO\n"
"    PvAPI:                       NO\n"
"    GigEVisionSDK:               NO\n"
"    UniCap:                      NO\n"
"    UniCap ucil:                 NO\n"
"    V4L/V4L2:                    Using libv4l (ver 0.9.5)\n"
"    XIMEA:                       NO\n"
"    Xine:                        NO\n"
"\n"

My code correctly compiles and I can read images with OpenCV.

The code is incredibly basic. For Python:

import cv2
cap = cv2.VideoCapture('test.mp4')
print cap.isOpened()
print cap.get(cv2.cv.CV_CAP_PROP_FPS)
print cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)
>> True
>> 0.0
>> 0

And for C++:

#include "opencv2/opencv.hpp"
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
    cv::VideoCapture cap;
    cap.open("test.mp4");
    if(cap.isOpened())
    {
        cout >> cap.get(CV_CAP_PROP_FPS) >> endl;
        cout >> cap.get(CV_CAP_PROP_FRAME_COUNT) >> endl;
    }
    return(0);
}

Which prints 0 as well.


问:
How to find non-retweets in a MongoDB collection of tweets?
I have a collection of about 1.4 million tweets in a MongoDB collection. I want to find all that are NOT retweets, and am using Python. The structure of a document is as follows:

```<code>{
  '_id': ObjectId('59388c046b0c1901172555b9'),
  'coordinates': None,
  'created_at': datetime.datetime(2016, 8, 18, 17, 17, 12),
  'geo': None,
  'is_quote': False,
  'lang': 'en',
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s',
  'tw_id': 766323071976247296,
  'user_id': 2231233110,
  'user_lang': 'en',
  'user_loc': 'main; @Kan1shk3',
  'user_name': 'sheezy0',
  'user_timezone': 'Chennai'
}
</code>```

I can write a query that works to find the particular tweet from above:

```<code>twitter_mongo_collection.find_one({
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s'
})
</code>```

But when I try to find retweets, my code doesn't work, for example I try to find any tweets that start like this:

```<code>'text': b'RT some tweet'
</code>```

Using this query:

```<code>find_one( {'text': {'$regex': "/^RT/" } }  )
</code>```

It doesn't return an error, but it doesn't find anything. I suspect it has something to do with that 'b' at the beginning before the text starts. I know I also need to put '$not:' in there somewhere but am not sure where.

Thanks!

答:
I had to decode the 'text' field that was encoded as binary. Then I was able to use

twitter_mongo_collection.find_one( { {'text': { '$not': re.compile("^RT.*") } } )

to find all the documents that did not start with "RT".

Body:
I have a collection of about 1.4 million tweets in a MongoDB collection. I want to find all that are NOT retweets, and am using Python. The structure of a document is as follows:

{
  '_id': ObjectId('59388c046b0c1901172555b9'),
  'coordinates': None,
  'created_at': datetime.datetime(2016, 8, 18, 17, 17, 12),
  'geo': None,
  'is_quote': False,
  'lang': 'en',
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s',
  'tw_id': 766323071976247296,
  'user_id': 2231233110,
  'user_lang': 'en',
  'user_loc': 'main; @Kan1shk3',
  'user_name': 'sheezy0',
  'user_timezone': 'Chennai'
}

I can write a query that works to find the particular tweet from above:

twitter_mongo_collection.find_one({
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s'
})

But when I try to find retweets, my code doesn't work, for example I try to find any tweets that start like this:

'text': b'RT some tweet'

Using this query:

find_one( {'text': {'$regex': "/^RT/" } }  )

It doesn't return an error, but it doesn't find anything. I suspect it has something to do with that 'b' at the beginning before the text starts. I know I also need to put '$not:' in there somewhere but am not sure where.

Thanks!


问:
Capybara error: Selenium::WebDriver::Error::ElementNotVisibleError: element not visible
I am using the Trix WYSIWYG editor in my app.  For my capybara test: I want to fill in the editor.

I found the article: How to test basecamp's trip editor... which seemed promising.  Unfortunately it keeps giving me this error:

Selenium::WebDriver::Error::ElementNotVisibleError: element not visible

So it appears that Capybara is finding the element ok, but it is just not interacting with it because Capybara must have some default setting to not interact with hidden/invisible elements.

After looking around I came upon this Stackoverflow question: Is it possible to interact with hidden elements with capybara.

From that post: I have already tried this:

```<code>def fill_in_trix_editor(id, value)
  Capybara.ignore_hidden_elements = false
  find(:xpath, "//*[@id='#{id}']").set(value)
  Capybara.ignore_hidden_elements = true
end
</code>```

As well as this:

```<code>def fill_in_trix_editor(id, value)
  find(:xpath, "//*[@id='#{id}']", visible: false).set(value)
end
</code>```

Any idea as to how I can get Capybara to fill in the editor?  For what it is worth: I am using rails 5.1.1 and chromedriver=2.29.461585

答:
Short answer: You can't using selenium

Longer answer: That error is selenium preventing you from interacting with a non-visible element because there would be no way for a user to click or send keys to a non-visible element.

If you really want to change the value of a hidden element, the only way would be using JS via execute_script but that most likely won't generate the events trix is expecting/using.  A much better solution would to be figure out what visible elements a user would interact with and interact with them directly. Capybara with selenium does support calling set on visible contenteditable elements which is what trix appears to be using (along with custom elements) so something like

```<code>find(:css, 'trix-editor').set("New text")
</code>```

will probably work for you

Body:
I am using the Trix WYSIWYG editor in my app.  For my capybara test: I want to fill in the editor.

I found the article: How to test basecamp's trip editor... which seemed promising.  Unfortunately it keeps giving me this error:

Selenium::WebDriver::Error::ElementNotVisibleError: element not visible

So it appears that Capybara is finding the element ok, but it is just not interacting with it because Capybara must have some default setting to not interact with hidden/invisible elements.

After looking around I came upon this Stackoverflow question: Is it possible to interact with hidden elements with capybara.

From that post: I have already tried this:

def fill_in_trix_editor(id, value)
  Capybara.ignore_hidden_elements = false
  find(:xpath, "//*[@id='#{id}']").set(value)
  Capybara.ignore_hidden_elements = true
end

As well as this:

def fill_in_trix_editor(id, value)
  find(:xpath, "//*[@id='#{id}']", visible: false).set(value)
end

Any idea as to how I can get Capybara to fill in the editor?  For what it is worth: I am using rails 5.1.1 and chromedriver=2.29.461585

Body:
Short answer: You can't using selenium

Longer answer: That error is selenium preventing you from interacting with a non-visible element because there would be no way for a user to click or send keys to a non-visible element.

If you really want to change the value of a hidden element, the only way would be using JS via execute_script but that most likely won't generate the events trix is expecting/using.  A much better solution would to be figure out what visible elements a user would interact with and interact with them directly. Capybara with selenium does support calling set on visible contenteditable elements which is what trix appears to be using (along with custom elements) so something like

find(:css, 'trix-editor').set("New text")

will probably work for you


问:
Sync a git repository with three different origins on Github/Bitbucket
Imagine I have 4 repositories: [A, B, C, D]
I would like to use a simple git command to update them all at the same time.

I expect to use something like:

```<code>git push all
</code>```

Any ideas?

答:
Just add all repos as remotes and make an alias that pushes to all of them like

```<code>git config alias.push-all '!git push remote-a && git push remote-b && git push remote-c'
</code>```

Then you can use git push-all to push to all remotes. If one fails because of non-fast-forward or whatever, solve the issue and just do it again, or manually push to the remotes individually.

Body:
Imagine I have 4 repositories: [A, B, C, D]
I would like to use a simple git command to update them all at the same time.

I expect to use something like:

git push all

Any ideas?

Body:
Just add all repos as remotes and make an alias that pushes to all of them like

git config alias.push-all '!git push remote-a && git push remote-b && git push remote-c'

Then you can use git push-all to push to all remotes. If one fails because of non-fast-forward or whatever, solve the issue and just do it again, or manually push to the remotes individually.


问:
Sqlite convert string to date
I have date stored as string in an sqlite database like "28/11/2010".
I want to convert the string to date.

Specifically I have to convert lots of string dates between two dates.

In postgresql, I use to_date('30/11/2010','dd/MM/yyyy'), how can I do the same thing with sqlite?

Something like this:

```<code>SELECT * FROM table
    WHERE   to_date(column,'dd/MM/yyyy')
    BETWEEN to_date('01/11/2010','dd/MM/yyyy')
    AND     to_date('30/11/2010','dd/MM/yyyy')
</code>```

答:
If Source Date format isn't consistent there is some problem
with substr function, e.g.:

1/1/2017 or 1/11/2017  or  11/11/2017  or  1/1/17
etc.

So I followed a different apporach using a temporary table. This snippet outputs 'YYYY-MM-DD' + time if exists.

Note that this version accepts Day/Month/Year format. If you want Month/Day/Year
swap the first two variables DayPart and MonthPart. Also, two year dates '44-'99 assumes 1944-1999 whereas '00-'43 assumes 2000-2043.

```<code> BEGIN;

    CREATE TEMP TABLE [DateconvertionTable] (Id TEXT PRIMARY KEY, OriginalDate  TEXT  , SepA  INTEGER,  DayPart TEXT,Rest1 TEXT, SepB  INTEGER,  MonthPart TEXT, Rest2 TEXT, SepC  INTEGER,  YearPart TEXT, Rest3 TEXT, NewDate TEXT);
    INSERT INTO [DateconvertionTable] (Id,OriginalDate)  SELECT SourceIdColumn, SourceDateColumn From  [SourceTable];

    --day Part (If day is first)

    UPDATE [DateconvertionTable] SET SepA=instr(OriginalDate ,'/');
    UPDATE [DateconvertionTable] SET DayPart=substr(OriginalDate,1,SepA-1) ;
    UPDATE [DateconvertionTable] SET Rest1=substr(OriginalDate,SepA+1);

    --Month Part (If Month is second)

    UPDATE [DateconvertionTable] SET SepB=instr(Rest1,'/');
    UPDATE [DateconvertionTable]  SET MonthPart=substr(Rest1, 1,SepB-1);
    UPDATE [DateconvertionTable] SET Rest2=substr(Rest1,SepB+1);

    --Year Part (3d)

    UPDATE [DateconvertionTable] SET SepC=instr(Rest2,' ');

           --Use Cases In case of time string included
    UPDATE [DateconvertionTable]  SET YearPart= CASE WHEN SepC=0 THEN Rest2 ELSE substr(Rest2,1,SepC-1)  END;

           --The Rest considered time
    UPDATE [DateconvertionTable]  SET Rest3= CASE WHEN SepC=0 THEN  '' ELSE substr(Rest2,SepC+1) END;

           -- Convert 1 digit day and month to 2 digit
    UPDATE [DateconvertionTable] SET DayPart=0||DayPart WHERE CAST(DayPart AS INTEGER)<10;
    UPDATE [DateconvertionTable] SET MonthPart=0||MonthPart WHERE CAST(MonthPart AS INTEGER)<10;

           --If there is a need to convert 2 digit year to 4 digit year, make some assumptions...
    UPDATE [DateconvertionTable] SET YearPart=19||YearPart WHERE CAST(YearPart AS INTEGER)>=44 AND CAST(YearPart AS INTEGER)<100;
    UPDATE [DateconvertionTable] SET YearPart=20||YearPart WHERE CAST(YearPart AS INTEGER)<44 AND CAST(YearPart AS INTEGER)<100;

    UPDATE [DateconvertionTable] SET NewDate = YearPart  || '-' || MonthPart || '-' || DayPart || ' ' || Rest3;

    UPDATE [SourceTable] SET SourceDateColumn=(Select NewDate FROM DateconvertionTable WHERE [DateconvertionTable].id=SourceIdColumn);
    END;
</code>```

Title: Sqlite convert string to date

Body:
I have date stored as string in an sqlite database like "28/11/2010".
I want to convert the string to date.

Specifically I have to convert lots of string dates between two dates.

In postgresql, I use to_date('30/11/2010','dd/MM/yyyy'), how can I do the same thing with sqlite?

Something like this:

SELECT * FROM table
    WHERE   to_date(column,'dd/MM/yyyy')
    BETWEEN to_date('01/11/2010','dd/MM/yyyy')
    AND     to_date('30/11/2010','dd/MM/yyyy')

Body:
If Source Date format isn't consistent there is some problem
with substr function, e.g.:

1/1/2017 or 1/11/2017  or  11/11/2017  or  1/1/17
etc.

So I followed a different apporach using a temporary table. This snippet outputs 'YYYY-MM-DD' + time if exists.

Note that this version accepts Day/Month/Year format. If you want Month/Day/Year
swap the first two variables DayPart and MonthPart. Also, two year dates '44-'99 assumes 1944-1999 whereas '00-'43 assumes 2000-2043.

 BEGIN;

    CREATE TEMP TABLE [DateconvertionTable] (Id TEXT PRIMARY KEY, OriginalDate  TEXT  , SepA  INTEGER,  DayPart TEXT,Rest1 TEXT, SepB  INTEGER,  MonthPart TEXT, Rest2 TEXT, SepC  INTEGER,  YearPart TEXT, Rest3 TEXT, NewDate TEXT);
    INSERT INTO [DateconvertionTable] (Id,OriginalDate)  SELECT SourceIdColumn, SourceDateColumn From  [SourceTable];

    --day Part (If day is first)

    UPDATE [DateconvertionTable] SET SepA=instr(OriginalDate ,'/');
    UPDATE [DateconvertionTable] SET DayPart=substr(OriginalDate,1,SepA-1) ;
    UPDATE [DateconvertionTable] SET Rest1=substr(OriginalDate,SepA+1);

    --Month Part (If Month is second)

    UPDATE [DateconvertionTable] SET SepB=instr(Rest1,'/');
    UPDATE [DateconvertionTable]  SET MonthPart=substr(Rest1, 1,SepB-1);
    UPDATE [DateconvertionTable] SET Rest2=substr(Rest1,SepB+1);

    --Year Part (3d)

    UPDATE [DateconvertionTable] SET SepC=instr(Rest2,' ');

           --Use Cases In case of time string included
    UPDATE [DateconvertionTable]  SET YearPart= CASE WHEN SepC=0 THEN Rest2 ELSE substr(Rest2,1,SepC-1)  END;

           --The Rest considered time
    UPDATE [DateconvertionTable]  SET Rest3= CASE WHEN SepC=0 THEN  '' ELSE substr(Rest2,SepC+1) END;

           -- Convert 1 digit day and month to 2 digit
    UPDATE [DateconvertionTable] SET DayPart=0||DayPart WHERE CAST(DayPart AS INTEGER)<10;
    UPDATE [DateconvertionTable] SET MonthPart=0||MonthPart WHERE CAST(MonthPart AS INTEGER)<10;

           --If there is a need to convert 2 digit year to 4 digit year, make some assumptions...
    UPDATE [DateconvertionTable] SET YearPart=19||YearPart WHERE CAST(YearPart AS INTEGER)>=44 AND CAST(YearPart AS INTEGER)<100;
    UPDATE [DateconvertionTable] SET YearPart=20||YearPart WHERE CAST(YearPart AS INTEGER)<44 AND CAST(YearPart AS INTEGER)<100;

    UPDATE [DateconvertionTable] SET NewDate = YearPart  || '-' || MonthPart || '-' || DayPart || ' ' || Rest3;

    UPDATE [SourceTable] SET SourceDateColumn=(Select NewDate FROM DateconvertionTable WHERE [DateconvertionTable].id=SourceIdColumn);
    END;


问:
Checking multiple checkboxes at same time causes $apply already in progress error
When a user clicks on a button to select all checkboxes in a single table, I use this code.

```<code>$("#workOneTable .rsvLine input[type=checkbox]").each(function() {
    if (!$(this).prop("checked")) {
        this.click();
    }
});
</code>```

When the code runs I get the $apply already in progress error, and I am not calling $apply at all.
I have to perform the click on each checkbox in the table selected too add each row that the checkbox is in to a list array. If I wrap this code in a $timeout I do not get the errors but my checkboxes will not get checked either.

Any help is greatly appreciated.

EDIT

This is the working code.

```<code>if (!$(this).prop("checked")) {
 var a = $(this);
 setTimeout(function() {
     a.click();
 })
}
</code>```

答:
Your click event is running digest cycle which is conflicting with current digest cycle. you can use setTimeout()

can you change this

```<code>if ( !$( this ).prop( "checked" ) )
{
    this.click();
}
</code>```

into

```<code>if ( !$( this ).prop( "checked" ) )
{
    var a = $(this);
    setTimeout(function(){a.click();})
}
</code>```

Body:
When a user clicks on a button to select all checkboxes in a single table, I use this code.

$("#workOneTable .rsvLine input[type=checkbox]").each(function() {
    if (!$(this).prop("checked")) {
        this.click();
    }
});

When the code runs I get the $apply already in progress error, and I am not calling $apply at all.
I have to perform the click on each checkbox in the table selected too add each row that the checkbox is in to a list array. If I wrap this code in a $timeout I do not get the errors but my checkboxes will not get checked either.

Any help is greatly appreciated.

EDIT

This is the working code.

if (!$(this).prop("checked")) {
 var a = $(this);
 setTimeout(function() {
     a.click();
 })
}

Body:
Your click event is running digest cycle which is conflicting with current digest cycle. you can use setTimeout()

can you change this

if ( !$( this ).prop( "checked" ) )
{
    this.click();
}

into

if ( !$( this ).prop( "checked" ) )
{
    var a = $(this);
    setTimeout(function(){a.click();})
}


问:
Issue with IE conditional comments and Google Analytics
I have a web-page that starts like so:

```<code><!DOCTYPE html>

<html>
<head>
    <!--[if lt IE 10]>
    <script>
        location.href = "http://www.getfirefox.com";
    </script>
    <![endif]-->
</code>```

That page gets ~500 pageviews/month and for the last 6 months I had no IE visitors according to Google Analytics. However, a few days ago I got a report of an IE6 visit. How did that happen?

Did the redirection code in the conditional comment fire to late?

Did Google Analytics code mistakingly identified a non-IE browser as IE6?

答:
You register no IE visits because your script with location.href = ... runs before the Google Analytics code gets a chance to run.

You could have registered that IE6 visit if

IE 6 failed to do the location.href assignment (I've seen problems reported with this) but did run the analytics js code.

An IE 6 visitor had javascript turned off
(in this case they wouldn't run the analytics code either, so wouldn't register a visit)

Another browser is impersonating IE 6, e.g. in the User-Agent string, but doesn't process the conditional comments.

You can move your conditional comment and the script within it to the end of the page, after the analytics js code if you want Google to count it but still send them off to getfirefox.com

You can also just say

```<code><!--[if IE]
...
</code>```

don't test a specific version if you always want to send IE away.

Body:
I have a web-page that starts like so:

<!DOCTYPE html>

That page gets ~500 pageviews/month and for the last 6 months I had no IE visitors according to Google Analytics. However, a few days ago I got a report of an IE6 visit. How did that happen?

Did the redirection code in the conditional comment fire to late?

Did Google Analytics code mistakingly identified a non-IE browser as IE6?

Body:
You register no IE visits because your script with location.href = ... runs before the Google Analytics code gets a chance to run.

You could have registered that IE6 visit if

IE 6 failed to do the location.href assignment (I've seen problems reported with this) but did run the analytics js code.

An IE 6 visitor had javascript turned off
(in this case they wouldn't run the analytics code either, so wouldn't register a visit)

Another browser is impersonating IE 6, e.g. in the User-Agent string, but doesn't process the conditional comments.

You can move your conditional comment and the script within it to the end of the page, after the analytics js code if you want Google to count it but still send them off to getfirefox.com

You can also just say

<!--[if IE]
...

don't test a specific version if you always want to send IE away.


问:
Get context attribute value from console
I'm reading with dev. tools console with this code $('#basis > td')[1] this code line: € 11,85

With $('#basis > td')[1].textContent i read the content of 	, also € 11,85.

How can i read the value of context? - i want to get 11.84689, but i can't find anywhere, how to fetch context attribute value...

答:
I think you can use:

```<code>$(document).find('td')[0].getAttribute('context');
</code>```

or

```<code>$('#basis').find('td')[0].getAttribute('context');
</code>```

Body:
I think you can use:

$(document).find('td')[0].getAttribute('context');

or

$('#basis').find('td')[0].getAttribute('context');


问:
T-SQL: how do I query a table that results in a list of the fields that have NULLS
I'm looking to set up an array of data quality scripts on a new set of data that my group is getting. One of the issues I'd like to keep track of is maintaining a list of fields that contain nulls. Some fields that's ok, others it is not, although we don't want to block the bulk insert because we've not allowed certain fields to null.

Example:

```<code>SELECT [columns]
FROM [TABLE] T
WHERE [columns] CONTAINS NULLS
</code>```

答:
This is slow and ugly, but short of buying a tool from RedGate (et al.), you might be able to modify it with an ISNULL(@column,'PICK ME') to search for your nulls...</p>

```<code>DECLARE @Query NVARCHAR(MAX), @Column NVARCHAR(100), @Table NVARCHAR(100)
DECLARE @Search NVARCHAR(100)
SET @Search = 'PICK ME'

IF OBJECT_ID('tempdb.dbo.#Results2','U') IS NOT NULL
    DROP TABLE tempdb.dbo.#Results2

CREATE TABLE #Results2(Table_Name VARCHAR(100), Column_Name VARCHAR(100))

DECLARE Col CURSOR FOR
SELECT Table_Name, Column_Name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLLATION_NAME IS NOT NULL
ORDER BY TABLE_NAME, ORDINAL_POSITION

OPEN Col
FETCH NEXT FROM Col INTO @Table, @Column
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @Query = 'IF EXISTS (SELECT * FROM '+QUOTENAME(@Table)+' WHERE '+QUOTENAME(@Column)+'='''+@Search+''')
                    SELECT '''+@Table+''','''+@Column+''''

    INSERT INTO #Results2
    EXEC sp_executesql @Query
    FETCH NEXT FROM Col INTO @Table, @Column
END
CLOSE Col
DEALLOCATE Col

SELECT * FROM #Results2
</code>```

Body:
I'm looking to set up an array of data quality scripts on a new set of data that my group is getting. One of the issues I'd like to keep track of is maintaining a list of fields that contain nulls. Some fields that's ok, others it is not, although we don't want to block the bulk insert because we've not allowed certain fields to null.

Example:

SELECT [columns]
FROM [TABLE] T
WHERE [columns] CONTAINS NULLS

Body:
This is slow and ugly, but short of buying a tool from RedGate (et al.), you might be able to modify it with an ISNULL(@column,'PICK ME') to search for your nulls...

DECLARE @Query NVARCHAR(MAX), @Column NVARCHAR(100), @Table NVARCHAR(100)
DECLARE @Search NVARCHAR(100)
SET @Search = 'PICK ME'

IF OBJECT_ID('tempdb.dbo.#Results2','U') IS NOT NULL
    DROP TABLE tempdb.dbo.#Results2

CREATE TABLE #Results2(Table_Name VARCHAR(100), Column_Name VARCHAR(100))

DECLARE Col CURSOR FOR
SELECT Table_Name, Column_Name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLLATION_NAME IS NOT NULL
ORDER BY TABLE_NAME, ORDINAL_POSITION

OPEN Col
FETCH NEXT FROM Col INTO @Table, @Column
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @Query = 'IF EXISTS (SELECT * FROM '+QUOTENAME(@Table)+' WHERE '+QUOTENAME(@Column)+'='''+@Search+''')
                    SELECT '''+@Table+''','''+@Column+''''

    INSERT INTO #Results2
    EXEC sp_executesql @Query
    FETCH NEXT FROM Col INTO @Table, @Column
END
CLOSE Col
DEALLOCATE Col

SELECT * FROM #Results2


问:
ordered list allign like the rest in css and html
I need 1.5.2.1 in the list also alligned like the rest, what am I doing wrong? Please help me to adjust the css code to align the ordered list indent as seen at 1.5.2.1, I dont know what im doing wrong.

ol {
 counter-reset: item;
 padding: 0;
 margin: 0;
 margin-left: 20px !ie7;
}

ul {
 margin: 0;
 padding: 0;
 list-style: none;
}

li span, li {
    display: block;
    overflow: hidden;
}

li:before {
 display: block;
 position: relative;
 content: counters(item, ".") ".";
 float: left;
}
ol > li {
 counter-increment: item;

}
ol li:before {

 width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ol>
  <li><strong>Introduction</strong>
    <ol>
      <li><span>This document...</span></li>
      <li><span>In the event...</span></li>
      <li><span>We...</span>
        <ol>
          <li><span>"Acknowledgment...</span>

            <li><span>"Deliver"/ "Delivered"/...</span>

              <ol>
                <li>where...</li>
              </ol>

            </li>
        </ol>
        </li>
    </ol>
    </li>
    <li>TITLE TWO
      <ol>
        <li>text 2 one</li>
        <li>text 2 two</li>
        <li>text 2 three</li>
        <li>text 2 four</li>
      </ol>
    </li>
    <li>TITLE THREE
      <ol>
        <li>text 3 one</li>
        <li>text 3 two</li>
        <li>text 3 three</li>
        <li>text 3 four</li>
        <li>text 3 five</li>
        <li>text 3 six</li>
      </ol>
    </li>
</ol></code>```

答:
You did not have the  tag right around 1.5.2.1's text.

```<code><ol>
    <li>
        <span>
            where you are already in possession of the Vehicle, confirming our mutual intention (as evidenced by a written Delivery Note which we will                 issue to you and which must be signed and accepted by you) that you shall cease holding the Vehicle in your possession for and on our behalf and retain possession of the Vehicle with the intention of holding the Vehicle in your name on your behalf as owner of the Vehicle; or
        </span>
    </li>
</ol>
</code>```

Body:
I need 1.5.2.1 in the list also alligned like the rest, what am I doing wrong? Please help me to adjust the css code to align the ordered list indent as seen at 1.5.2.1, I dont know what im doing wrong.

ol {
 counter-reset: item;
 padding: 0;
 margin: 0;
 margin-left: 20px !ie7;
}

ul {
 margin: 0;
 padding: 0;
 list-style: none;
}

li span, li {
    display: block;
    overflow: hidden;
}

li:before {
 display: block;
 position: relative;
 content: counters(item, ".") ".";
 float: left;
}
ol > li {
 counter-increment: item;

}
ol li:before {

 width: 50px;
}

Introduction

This document...

In the event...

We...

"Acknowledgment...

"Deliver"/ "Delivered"/...

where...

TITLE TWO

text 2 one

text 2 two

text 2 three

text 2 four

TITLE THREE

text 3 one

text 3 two

text 3 three

text 3 four

text 3 five

text 3 six

Body:
You did not have the <span> tag right around 1.5.2.1's text.

<ol>
    <li>
        <span>
            where you are already in possession of the Vehicle, confirming our mutual intention (as evidenced by a written Delivery Note which we will                 issue to you and which must be signed and accepted by you) that you shall cease holding the Vehicle in your possession for and on our behalf and retain possession of the Vehicle with the intention of holding the Vehicle in your name on your behalf as owner of the Vehicle; or
        </span>
    </li>
</ol>


问:
How to target the 7th child only
Problem I have the following code that displays the navigation bar that is provided by Mura:

```<code>#$.dspPrimaryNav(
viewDepth=0
, id='navPrimary'
, class='nav navbar-nav nav-nowrap'
, displayHome='never'
, closeFolders=false
, showCurrentChildrenOnly=false
, liHasKidsClass='dropdown'
, liHasKidsAttributes=''
, liCurrentClass=''
, liCurrentAttributes=''
, liHasKidsNestedClass='dropdown-submenu'
, aHasKidsClass='dropdown-toggle'
, aHasKidsAttributes='role="button" data-toggle="dropdown" data-target="##"'
, aCurrentClass=''
, aCurrentAttributes=''
, ulNestedClass='dropdown-menu'
, ulNestedAttributes=''
, aNotCurrentClass=''
, siteid=$.event('siteid')
)#
</code>```

And the displays the following navigation bar:

As you can see above, the second row of the navigation bar is shifted to the right. I tried the following css to align the second row with the first row of the navigation bar:

```<code>#navPrimary ul:nth-child(3n+1){
    margin-left:-15px;
}
</code>```

However, it is not working. Any help would be appreciated.

答:
You can use the following css to target the 7th item of the list. I assume all of the links are part of the same list so I changed the ul to li. </p>

```<code>#navPrimary li:nth-child(7){
    margin-left:-15px;
}
</code>```

Title: How to target the 7th child only

Body:
Problem I have the following code that displays the navigation bar that is provided by Mura:

#$.dspPrimaryNav(
viewDepth=0
, id='navPrimary'
, class='nav navbar-nav nav-nowrap'
, displayHome='never'
, closeFolders=false
, showCurrentChildrenOnly=false
, liHasKidsClass='dropdown'
, liHasKidsAttributes=''
, liCurrentClass=''
, liCurrentAttributes=''
, liHasKidsNestedClass='dropdown-submenu'
, aHasKidsClass='dropdown-toggle'
, aHasKidsAttributes='role="button" data-toggle="dropdown" data-target="##"'
, aCurrentClass=''
, aCurrentAttributes=''
, ulNestedClass='dropdown-menu'
, ulNestedAttributes=''
, aNotCurrentClass=''
, siteid=$.event('siteid')
)#

And the displays the following navigation bar:

As you can see above, the second row of the navigation bar is shifted to the right. I tried the following css to align the second row with the first row of the navigation bar:

#navPrimary ul:nth-child(3n+1){
    margin-left:-15px;
}

However, it is not working. Any help would be appreciated.

Body:
You can use the following css to target the 7th item of the list. I assume all of the links are part of the same list so I changed the ul to li.

#navPrimary li:nth-child(7){
    margin-left:-15px;
}


问:
System.Threading.Timer trying to make timer for same time every day
I am using System.Threading.Timer in a console service app, and trying to make timer for same time every day.

Initially I am good if I start the app prior to the time.  Like if my time is 10:05 and I start the app at 10:00 we are good. But if I start at 10:06 I dont know how to tell the timespan to go 24 hours ahead.

Thanks for any help!

```<code>public void SetUpTimer(TimeSpan alertTime)
{
    DateTime current = DateTime.Now;
    TimeSpan timeToGo = alertTime - current.TimeOfDay;

    if (timeToGo < TimeSpan.Zero)
    {
        EventLog.WriteEntry("MyApp", "Timer Passed  " );

        return;//time already passed
    }

    timer = new System.Threading.Timer(x =>
    {
        EventLog.WriteEntry("MhyApp", "Timer Set  " + timeToGo);

        this.MethodRunsAt();
    },  null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}
</code>```

答:
I suggest you to use cron expressions to solve this task. For example you can use Quartz.Net library (it is available through nuget).

Your cron expression will look like this:

```<code>0 10 * * *    //“At 10:00”
</code>```

It tells that action will be performed exactly “At 10:00” every day. Or if you want you can even start it every monday and wednesday:

```<code>0 10 * * 1,3  //“At 10:00 on Monday and Wednesday.”
</code>```

Or if you want to make it periodic in some time scope:

```<code>0/2 10 * * 1,3  //“At every 2nd minute from 0 through 59 past hour 10 on Monday and Wednesday.”
</code>```

Body:
I am using System.Threading.Timer in a console service app, and trying to make timer for same time every day.

Initially I am good if I start the app prior to the time.  Like if my time is 10:05 and I start the app at 10:00 we are good. But if I start at 10:06 I dont know how to tell the timespan to go 24 hours ahead.

Thanks for any help!

public void SetUpTimer(TimeSpan alertTime)
{
    DateTime current = DateTime.Now;
    TimeSpan timeToGo = alertTime - current.TimeOfDay;

    if (timeToGo < TimeSpan.Zero)
    {
        EventLog.WriteEntry("MyApp", "Timer Passed  " );

        return;//time already passed
    }

    timer = new System.Threading.Timer(x =>
    {
        EventLog.WriteEntry("MhyApp", "Timer Set  " + timeToGo);

        this.MethodRunsAt();
    },  null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}

Body:
I suggest you to use cron expressions to solve this task. For example you can use Quartz.Net library (it is available through nuget).

Your cron expression will look like this:

0 10 * * *    //“At 10:00”

It tells that action will be performed exactly “At 10:00” every day. Or if you want you can even start it every monday and wednesday:

0 10 * * 1,3  //“At 10:00 on Monday and Wednesday.”

Or if you want to make it periodic in some time scope:

0/2 10 * * 1,3  //“At every 2nd minute from 0 through 59 past hour 10 on Monday and Wednesday.”


问:
How to append text to end of current line using Vim function?
I'd like to append text to the end of a current line in Vim. I'd like to do this within the context of a function.

How can this be done? Do I need to escape/sanitise the text?

答:
With :exe + :normal! you may need to sanatize the text as you feared -- it'll depend on the kind of quotes you use, and on whether you forget to bang :normal and you have insert mode mappings and abbreviations.

With setline('.', getline('.') . text), vim won't try to interpret the text you append. This seems convoluted, but this is the more robust way to proceed -- it can become way more convoluted if you start to escape things with A.


问:
ICal.net Calendar Comparison
I've been using a nuget package called ICal.net to load ics files to check for events that have recently been added.

I've noticed while using the IEnumerable Except method for this that some events are missed even though you can see that more events have been added.

I came across the Uid property in the Event, checked it out and noticed that its unique - https://github.com/rianjs/ical.net/blob/5176d27ac243eb98a01157f2ed7ff3e2852b98eb/v2/ical.NET/Interfaces/Components/IUniqueComponent.cs#L14

I wrote a IEqualityComparer<IEvent> for this using the Uid but now all events are being seen as new events.

Was just wondering if anyone had any suggestions on how I can take 2 calendars, compare the events and get the differences? Currently there is 2000+ events and increasing so trying to keep it performant.

答:
If I understand you correctly, you have two collections of calendars. One represents a VCALENDAR with multiple VEVENTs, and the second represents the same VCALENDAR + VEVENTs at a later point in time. Often the later VCALENDAR has more events than the earlier calendar, for obvious reasons. And you want to compare the two to see the difference, i.e., find the new events.

Using Uid might be sufficient, and it might not be; it depends on your calendaring system. While each UID should be unique, that's up to your application to guarantee. When ical.net creates an event, it does a Guid.NewGuid().ToString(), so if you're using ical.net to create events, they should be unique. Google Calendar and (I assume) other popular calendaring applications also provide deterministically unique Uids.

ical.net does not consider the Uid significant for the purposes of equality or hashing. Instead, it pays attention to the composition of the events themselves.

If you know that each event's UID is unique, and you have no interest in comparing two events with unmatched Uids, I would do something like this:

```<code>var eventIdSet = new HashSet<string>(StringComparison.OrdinalIgnoreCase);
var firstEventIds = firstCalendarCollection
    .SelectMany(cc => cc.Event)
    .Select(e => e.Uid);
eventIdSet.UnionWith(firstEventIds);

var secondEventIds = secondCalendarCollection
    .SelectMany(cc => cc.Event)
    .Select(e => e.Uid);

eventIdSet.ExceptWith(secondEventIds);
</code>```

That should give you the new calendar ids present in the first collection, but not the second.

If you want to compare event contents, I would do follow the same pattern, stopping at the Event object:

```<code>var firstSet = new HashSet<Event>();
var firstEvents = firstCalendarCollection.SelectMany(cc => cc.Event);
firstSet.UnionWith(firstEventIds);

var secondEvents = secondCalendarCollection.SelectMany(cc => cc.Event);
firstSet.ExceptWith(secondEvents);
</code>```

This will do the same thing, but as I said above, event ids are ignored by the internal GetHashCode and Equals implementations.

Comparing Uids alone will be faster than comparing the entire contents of each Event. That said, unless this is a busy server application that has to do this multiple times per second, it shouldn't matter. We are using ical.net, and doing set operations like this with 800-1000 calendar events, and it's milliseconds of compute time in a WPF application. You probably wouldn't notice the difference between the Uid comparisons and the whole Event content comparison except under extreme circumstances.

Edit: I've created a wiki page: https://github.com/rianjs/ical.net/wiki/Comparing-collections-of-calendar-events

Title: ICal.net Calendar Comparison

Body:
If I understand you correctly, you have two collections of calendars. One represents a VCALENDAR with multiple VEVENTs, and the second represents the same VCALENDAR + VEVENTs at a later point in time. Often the later VCALENDAR has more events than the earlier calendar, for obvious reasons. And you want to compare the two to see the difference, i.e., find the new events.

Using Uid might be sufficient, and it might not be; it depends on your calendaring system. While each UID should be unique, that's up to your application to guarantee. When ical.net creates an event, it does a Guid.NewGuid().ToString(), so if you're using ical.net to create events, they should be unique. Google Calendar and (I assume) other popular calendaring applications also provide deterministically unique Uids.

ical.net does not consider the Uid significant for the purposes of equality or hashing. Instead, it pays attention to the composition of the events themselves.

If you know that each event's UID is unique, and you have no interest in comparing two events with unmatched Uids, I would do something like this:

var eventIdSet = new HashSet<string>(StringComparison.OrdinalIgnoreCase);
var firstEventIds = firstCalendarCollection
    .SelectMany(cc => cc.Event)
    .Select(e => e.Uid);
eventIdSet.UnionWith(firstEventIds);

var secondEventIds = secondCalendarCollection
    .SelectMany(cc => cc.Event)
    .Select(e => e.Uid);

eventIdSet.ExceptWith(secondEventIds);

That should give you the new calendar ids present in the first collection, but not the second.

If you want to compare event contents, I would do follow the same pattern, stopping at the Event object:

var firstSet = new HashSet<Event>();
var firstEvents = firstCalendarCollection.SelectMany(cc => cc.Event);
firstSet.UnionWith(firstEventIds);

var secondEvents = secondCalendarCollection.SelectMany(cc => cc.Event);
firstSet.ExceptWith(secondEvents);

This will do the same thing, but as I said above, event ids are ignored by the internal GetHashCode and Equals implementations.

Comparing Uids alone will be faster than comparing the entire contents of each Event. That said, unless this is a busy server application that has to do this multiple times per second, it shouldn't matter. We are using ical.net, and doing set operations like this with 800-1000 calendar events, and it's milliseconds of compute time in a WPF application. You probably wouldn't notice the difference between the Uid comparisons and the whole Event content comparison except under extreme circumstances.

Edit: I've created a wiki page: https://github.com/rianjs/ical.net/wiki/Comparing-collections-of-calendar-events


问:
java networking, calls to write in average take 4x longer than calls to read, is it normal?
To be more specific, i have written a server with java NIO, and it works quiet well, after some testing i have found out that for some reason, in average a call to the SocketChannels write method takes 1ms, the read method on the other hand takes 0.22ms in average.

Now at first i was thinking that setting the sent/receive buffer values on Socket might help a bit, but after thinking about it, all the messages are very short(a few bytes) and i send a message about every 2 seconds on a single connection. Both sent and receive buffers are well over 1024 bytes in size so this can't really be the problem, i do have several thousand clients connected at once thou.

Now i am a bit out of ideas on this, is this normal and if it is, why ?

答: I would start by using Wireshark to eliminate variables.</p>


问:
Bash array not filling in loop reading from file
I'm trying to fill an array with the lines in a file in bash. I do not understand what is happening here:

```<code>balter@exahead1:~$ declare -a a
balter@exahead1:~$ cat t.txt
a b
c d
e f
g h
balter@exahead1:~$ cat t.txt | while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done
a b
0: a b
a b
c d
1: c d
a b c d
e f
2: e f
a b c d e f
g h
3: g h
a b c d e f g h
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$
</code>```

EDIT:
Apparently it "works" if I redirect the file in rather than pipe it:

```<code>balter@exahead1:~$ while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done < t.txt
a b
0: a b
a b
c d
1: c d
a b c d
e f
2: e f
a b c d e f
g h
3: g h
a b c d e f g h
balter@exahead1:~$ echo "${a[@]}"
a b c d e f g h
balter@exahead1:~$
</code>```

EDIT 2
@anubhava--what version of bash would I need? I tried your suggestion, and although we have mapfile it did not "work".

```<code>balter@exahead1:~$ bash --version
bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
balter@exahead1:~$ unset a
balter@exahead1:~$ a=()
balter@exahead1:~$ mapfile -t a < t.txt
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$
</code>```

Neither did the 2nd method:

```<code>balter@exahead1:~$ unset a
balter@exahead1:~$ a=()
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$
balter@exahead1:~$ while IFS= read -r line; do a+=("$line"); done < t.txt
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$
</code>```

EDIT 3

Both of the above methods "work" on my Mac running El Capitan.

答:
You can just use builtin mapfile for this:

```<code>mapfile -t arr < file
</code>```

If you are on older BASH version then you can use while loop like this:

```<code>arr=()

while IFS= read -r line; do
   arr+=("$line")
done < file
</code>```

Body:
I'm trying to fill an array with the lines in a file in bash. I do not understand what is happening here:

balter@exahead1:~$ declare -a a
balter@exahead1:~$ cat t.txt
a b
c d
e f
g h
balter@exahead1:~$ cat t.txt | while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done
a b
0: a b
a b
c d
1: c d
a b c d
e f
2: e f
a b c d e f
g h
3: g h
a b c d e f g h
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$

EDIT:
Apparently it "works" if I redirect the file in rather than pipe it:

balter@exahead1:~$ while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done < t.txt
a b
0: a b
a b
c d
1: c d
a b c d
e f
2: e f
a b c d e f
g h
3: g h
a b c d e f g h
balter@exahead1:~$ echo "${a[@]}"
a b c d e f g h
balter@exahead1:~$

EDIT 2
@anubhava--what version of bash would I need? I tried your suggestion, and although we have mapfile it did not "work".

balter@exahead1:~$ bash --version
bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
balter@exahead1:~$ unset a
balter@exahead1:~$ a=()
balter@exahead1:~$ mapfile -t a < t.txt
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$

Neither did the 2nd method:

balter@exahead1:~$ unset a
balter@exahead1:~$ a=()
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$
balter@exahead1:~$ while IFS= read -r line; do a+=("$line"); done < t.txt
balter@exahead1:~$ echo "${a[@]}"

balter@exahead1:~$

EDIT 3

Both of the above methods "work" on my Mac running El Capitan.

Body:
You can just use builtin mapfile for this:

mapfile -t arr < file

If you are on older BASH version then you can use while loop like this:

arr=()

while IFS= read -r line; do
   arr+=("$line")
done < file


问:
MS Access Sequential number Calculation and record generation
Ok, this one is new to me...  I have a table where the user enters the number of records to be entered (X).  I would like MS Access to calculate the number X down to and including 0, and enter those numbers as records in another table.

[User Entry Table].[Number] = 10

The following numbers are then added to table Y in Field Record Number

10
9
8
7
6
5
4
3
2
1
0

答:
```<code>Public Sub Insert(nBase As Integer)
    Dim nIndex As Integer
    Dim db As Database
    Set db = CurrentDb
    For nIndex = nBase To 0 Step -1
        db.Execute "INSERT INTO [User Entry Table] ([Number]) VALUES (" & nIndex & ")"
    Next
End Sub
</code>```


问:
Is this the right way to use generics in Java?
```<code>class Matrix<T>{
   private List<Attribute<T>> attributes;

   public Matrix(T type){
      attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));
   }
}
</code>```

I feel like in the constructor, these two lines should be use a specific type, not the generic T:

```<code>attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));
</code>```

But the compiler doesn't complain. So this is the right way to define this class?

答:
I feel like in the constructor, these two lines should be use a specific type, not the generic T

No, because your class Matrix is generic on the type parameter T. This means that it encapsulates a list of attributes of the type T, namely: List<Attribute<T>>.

If you use it with Integer:

```<code>Matrix<Integer> integerMatrix = new Matrix<>(1);
</code>```

Then 1 would be inside the first attribute of the list.

However, if you declare another matrix with String:

```<code>Matrix<String> stringMatrix = new Matrix<>("hello");
</code>```

Then your matrix will hold attributes that encapsulate String values.

Body:
class Matrix<T>{
   private List<Attribute<T>> attributes;

   public Matrix(T type){
      attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));
   }
}

I feel like in the constructor, these two lines should be use a specific type, not the generic T:

attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));

But the compiler doesn't complain. So this is the right way to define this class?

Body:
I feel like in the constructor, these two lines should be use a specific type, not the generic T

No, because your class Matrix is generic on the type parameter T. This means that it encapsulates a list of attributes of the type T, namely: List<Attribute<T>>.

If you use it with Integer:

Matrix<Integer> integerMatrix = new Matrix<>(1);

Then 1 would be inside the first attribute of the list.

However, if you declare another matrix with String:

Matrix<String> stringMatrix = new Matrix<>("hello");

Then your matrix will hold attributes that encapsulate String values.