Could not receive message back from WS service using Apache CXF Client: Read time out

Question: I am trying to call Web Service that is based on IIS WPF and its WSDL has following policy:
<wsp:Policy wsu:Id="custom_policy">
  <wsp:ExactlyOne>
    <wsp:All>
      <sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:TransportToken>
            <wsp:Policy>
              <sp:HttpsToken RequireClientCertificate="false"/>
            </wsp:Policy>
          </sp:TransportToken>
          <sp:AlgorithmSuite>
            <wsp:Policy>
              <sp:Basic256/>
            </wsp:Policy>
          </sp:AlgorithmSuite>
          <sp:Layout>
            <wsp:Policy>
              <sp:Strict/>
            </wsp:Policy>
          </sp:Layout>
          <sp:IncludeTimestamp/>
        </wsp:Policy>
      </sp:TransportBinding>
      <sp:SignedSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:UsernameToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
            <wsp:Policy>
              <sp:WssUsernameToken10/>
            </wsp:Policy>
          </sp:UsernameToken>
        </wsp:Policy>
      </sp:SignedSupportingTokens>
      <sp:Wss11 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy/>
      </sp:Wss11>
      <sp:Trust10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:MustSupportIssuedTokens/>
          <sp:RequireClientEntropy/>
          <sp:RequireServerEntropy/>
        </wsp:Policy>
      </sp:Trust10>
      <wsaw:UsingAddressing/>
    </wsp:All>
  </wsp:ExactlyOne>
</wsp:Policy>

with Apache CXF client and following code:
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(ITerytWs1.class);
factory.setAddress("https://uslugaterytws1test.stat.gov.pl/terytws1.svc");
ITerytWs1 info = (ITerytWs1) factory.create();
Map ctx = ((BindingProvider)info).getRequestContext();
ctx.put("ws-security.username", "TestPubliczny");
ctx.put("ws-security.password", "1234abcd");
ctx.put("ws-security.callback-handler", ClientPasswordCallback.class.getName());
var zal = info.isLoggedIn();

Dependencies are:
compile group: 'org.apache.cxf', name: 'cxf-rt-frontend-jaxws', version: '3.3.7'
compile group: 'org.apache.cxf', name: 'cxf-rt-transports-http', version: '3.3.7'
compile group: 'com.sun.activation', name: 'javax.activation', version: '1.2.0'
compile group: 'org.apache.cxf', name: 'cxf-rt-ws-security', version: '3.3.7'
compile group: 'com.sun.xml.messaging.saaj', name: 'saaj-impl', version: '1.5.2'

I receive only Read time out:
lip 16, 2020 1:58:31 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://tempuri.org/}ITerytWs1Service#{http://tempuri.org/}CiekawostkiSIMC has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Could not receive Message.
    at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:65)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
    at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:530)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:441)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:356)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:314)
    at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
  [...]
Caused by: java.net.SocketTimeoutException: SocketTimeoutException invoking https://uslugaterytws1test.stat.gov.pl/terytws1.svc: Read timed out
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    [..]
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.base/java.net.SocketInputStream.socketRead0(Native Method)
    [...]
Could not receive Message.
javax.xml.ws.WebServiceException: Could not receive Message.
    at org.apache.cxf.jaxws.JaxWsClientProxy.mapException(JaxWsClientProxy.java:183)

[...]
Caused by: java.net.SocketTimeoutException: SocketTimeoutException invoking https://uslugaterytws1test.stat.gov.pl/terytws1.svc: Read timed out
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[...]
How to configure this WS policy right and is it the problem of client or something else?
Comment: Maybe the service is not accessible or up. Have you tried running a test with SOAP UI?
Answer: I had to use SoapUI to check what kind of envelope is sent to the service to get the right answer, then I had to do the same with the code. Problem before was that wrong request was sent to the server and server got internal exception (probably) and has not returned answer of bad request.
This is what I have done with the class:
import lombok.Getter;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.ws.addressing.WSAddressingFeature;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.handler.WSHandlerConstants;
import org.tempuri.ITerytWs1;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

public class WebServiceClient {

@Getter
private ITerytWs1 service;
private final ApiClientConfiguration apiClientConfiguration;
private final ClientPasswordCallback clientPasswordCallback;

@Inject
public WebServiceClient(ApiClientConfiguration apiClientConfiguration) {
    this.apiClientConfiguration = apiClientConfiguration;
    this.clientPasswordCallback = new ClientPasswordCallback(apiClientConfiguration);
    initializeService();
    configureService();
}

private void configureService() {
    var client = ClientProxy.getClient(service);
    var endpoint = client.getEndpoint();
    Map<String, Object> outInterceptorProperties = createOutInterceptorProperties();
    var wssOutInterceptor = new WSS4JOutInterceptor(outInterceptorProperties);
    endpoint.getOutInterceptors().add(wssOutInterceptor);
}

private void initializeService() {
    var factory = new JaxWsProxyFactoryBean();
    var wsAddressingFeature = new WSAddressingFeature();
    factory.getFeatures().add(wsAddressingFeature);
    factory.setServiceClass(ITerytWs1.class);
    factory.setAddress(apiClientConfiguration.getAddress());
    service = (ITerytWs1) factory.create();
}

private Map<String, Object> createOutInterceptorProperties() {
    Map<String,Object> outInterceptorProperties = new HashMap<>();
    outInterceptorProperties.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
    outInterceptorProperties.put(WSHandlerConstants.USER, apiClientConfiguration.getUsername());
    outInterceptorProperties.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
    outInterceptorProperties.put(WSHandlerConstants.ADD_USERNAMETOKEN_NONCE, "true");
    outInterceptorProperties.put(WSHandlerConstants.ADD_USERNAMETOKEN_CREATED, "true");
    outInterceptorProperties.put(WSHandlerConstants.MUST_UNDERSTAND, "false");
    // Callback used to retrieve password for given user.
    outInterceptorProperties.put(WSHandlerConstants.PW_CALLBACK_REF, clientPasswordCallback);
    return outInterceptorProperties;
}
}


Overwrite an item if it already exists in Azure Cosmos DB while bulk importing from Java

Question: I'm using Java DocumentDb bulk-executor to bulk import an array of json to Azure Cosmos DB.
Sample JSON :
[
  {
    "SId": "101",
    "SName": "ABC"
  },
  {
    "SId": "102",
    "SName": "XYZ"
  }
]

Sample Code :
(PARTTION_KEY = "\SId")
DocumentCollection collection = Utilities.createEmptyCollectionIfNotExists(client, DATABASE, CONTAINER, PARTITION_KEY, THROUGHPUT);
            ArrayList<String> list = new ArrayList<String>();
            JSONParser jsonParser = new JSONParser();
            FileReader reader = new FileReader("C:\\samplejson.json");

                Object obj = jsonParser.parse(reader);

                JSONArray jsonArray  = (JSONArray) obj;

                if (jsonArray  != null) {
                    int len = jsonArray.size();
                    for (int i=0;i<len;i++){
                        list.add(jsonArray.get(i).toString());
                    }
                }

                client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(30);
                client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(9);

                DocumentBulkExecutor.Builder bulkExecutorBuilder = DocumentBulkExecutor.builder().from(client, DATABASE, CONTAINER,
                collection.getPartitionKey(), 20000);

                DocumentBulkExecutor bulkExecutor = bulkExecutorBuilder.build();

                client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(0);
                client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(0);
                BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, false, false, null);
                System.out.println(bulkImportResponse.getNumberOfDocumentsImported());

Now if I have this another JSON :
[
  {
    "SId": "101,         // Item with this SID has already been inserted
    "SName": "ABCDEF"
  },
  {
    "SId": "103",
    "SName": "PQR"
  }
]

I want to insert this JSON to the same container. But it's just stored as a new entry and with a different "id", automatically created by Cosmos DB.
How can I bulk import and overwrite if item on the basis of"SId", if it already exists, at the same time?
Please help!
Answer: You need to change the isUpsert flag in your call to importAll to be true.  This will enable the Upsert operation which means it will either add a new document if the id doesn't already exist, or it will update an existing document if the id is already there.
Change line:
BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, false, false, null);

To
BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, true, false, null);

https://learn.microsoft.com/en-us/azure/cosmos-db/bulk-executor-java#bulk-import-data-to-azure-cosmos-db
Comment: The ID needs to be unique within each partition, so if the ID and Sid both match an existing document then it should update.  If the ID matches but the Sid doesn't match then it's going to insert a new document.  I generally use Guids for ID to ensure uniqueness across partitions to avoid confusion.
Comment: I think you may be confusing ID and Partition Key.  The ID is a unique identifier for each document within a partition. This is what cosmos uses to determine if a document already exists.  The partition key is an element in your document used to group documents into different logical partitions.  Many documents can have the same partition key value, and it just means they are all stored in the same logical partition. [take a look here](https://learn.microsoft.com/en-us/azure/cosmos-db/partitioning-overview)
Comment: No, it is still just making new entries. I tried the same.
Comment: It is only updating on "id". Although I've chosen "SId" as my partition key. Is it possible to do so on "SId"?
Comment: Thank you, this was really a very helpful solution and explanation @Paul.
Comment: Also, I have a doubt that does Azure cosmos, do the import in random order?


error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

Question: I have read a lot of solutions to my problem but none helped. I tried clean, rebuild. Reinstalled visual 2010 and change from professional to ultimate. But still I dont know why I have this error.
My project look like this:
1 Exe Solution to test my static library.
1 Dll Solution static library.
Code which is converted to dll is using function from 1 lib called ClassificationFramework. I provided this lib as headers and cpp so basically source code. In Exe solution I linked my generated library + some other libs to run it + ClassificationFramework.dll. Everything works fine when I use Release but when I change to Debug (because I want to debug some stuff, I am tired of skipping debugger in release mode) I get this:
    2>Link:
    2>  ClassificationFramework.lib(SampleClass.obj) : MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
    2>ClassificationFramework.lib(SampleClass.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj
    2>ClassificationFramework.lib(SampleNamesSet.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj
    2>ClassificationFramework.lib(SampleSet.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj
    2>ClassificationFramework.lib(DirectoryReader.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj
    2>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
    2>C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Transformer\Debug\Tester.exe : fatal error LNK1319: 4 mismatches detected

When I build in Release I also got these warnings:
    1>Link:
    1>  Generating code
    1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(101): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because ptimizations are disabled in function
    1>c:\users\kasia\documents\visual studio 2010\projects\classificationframework\classificationframework\directoryreader.cpp(30): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
    1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xstring(1589): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
    1>c:\users\kasia\documents\visual studio 2010\projects\classificationframework\classificationframework\samplenamesset.cpp(226): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
    1>c:\users\kasia\documents\visual studio 2010\projects\classificationframework\classificationframework\directoryreader.cpp(60): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
    1>c:\users\kasia\documents\visual studio 2010\projects\classificationframework\classificationframework\samplenamesset.cpp(199): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
    1>c:\users\kasia\documents\visual studio 2010\projects\classificationframework\classificationframework\sampleset.cpp(27): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
    1>c:\users\kasia\documents\visual studio 2010\projects\classificationframework\classificationframework\samplenamesset.cpp(59): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
    1>  Finished generating code
    1>ClassificationFramework.lib(SampleSet.obj) : warning LNK4099: PDB 'vc100.pdb' was not found with 'ClassificationFramework.lib(SampleSet.obj)' or at 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Transformer\Release\vc100.pdb'; linking object as if no debug info
    1>ClassificationFramework.lib(SampleNamesSet.obj) : warning LNK4099: PDB 'vc100.pdb' was not found with 'ClassificationFramework.lib(SampleNamesSet.obj)' or at 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Transformer\Release\vc100.pdb'; linking object as if no debug info
    1>ClassificationFramework.lib(SampleClass.obj) : warning LNK4099: PDB 'vc100.pdb' was not found with 'ClassificationFramework.lib(SampleClass.obj)' or at 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Transformer\Release\vc100.pdb'; linking object as if no debug info
    1>ClassificationFramework.lib(DirectoryReader.obj) : warning LNK4099: PDB 'vc100.pdb' was not found with 'ClassificationFramework.lib(DirectoryReader.obj)' or at 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Transformer\Release\vc100.pdb'; linking object as if no debug info
    1>  Tester.vcxproj -> C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Transformer\Release\Tester.exe

I found that Debugger skips because of wrong path to pdb files.
'Tester.exe': Loaded 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Work\Release\Tester.exe', Symbols loaded.
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\kernel32.dll', Cannot find or open the PDB file
'Tester.exe': Unloaded 'C:\WINDOWS\SysWOW64\kernel32.dll'
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\ntdll.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\kernel32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\OpenCV2.2\bin\opencv_core220.dll', Binary was not built with debug information.
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\msvcp100.dll', Symbols loaded.
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\msvcr100.dll', Symbols loaded.
'Tester.exe': Loaded 'C:\OpenCV2.2\bin\opencv_highgui220.dll', Binary was not built with debug information.
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\user32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\gdi32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\advapi32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\rpcrt4.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\secur32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\ole32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\msvcrt.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_5.82.3790.4770_x-ww_A689AB02\comctl32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\avifil32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\winmm.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\msacm32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\msvfw32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\shell32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\shlwapi.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\avicap32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\version.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\OpenCV2.2\bin\opencv_imgproc220.dll', Binary was not built with debug information.
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\imm32.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\lpk.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\SysWOW64\usp10.dll', Cannot find or open the PDB file
'Tester.exe': Loaded 'C:\WINDOWS\WinSxS\wow64_Microsoft.Windows.Common-        Controls_6595b64144ccf1df_6.0.3790.4770_x-ww_8D2E3180\comctl32.dll', Cannot find or open the PDB file
The program '[4984] Tester.exe: Native' has exited with code 0 (0x0).

When i go to Debug->Windows->Modules i see that he cannot find those pdb files or something. How i can say him that those files are here here and here? I tried to run MSvisual as administrator but that too didnt help. I used microsoft server to load pdb files but also didnt help.
Answer: In VS2010 iterator debug level defaults to 2 in debug and is disabled in release. One of the dlls you are using probably has iterator debugging turned off in debug either because it was built in an older version of visual studio or they explicitly added the defines to the project.
Search for _ITERATOR_DEBUG_LEVEL and _SECURE_SCL remove them or set them appropriately in all projects and sources and rebuild everything.
_ITERATOR_DEBUG_LEVEL = 0 // disabled (for release builds)
_ITERATOR_DEBUG_LEVEL = 1 // enabled (if _SECURE_SCL is defined)
_ITERATOR_DEBUG_LEVEL = 2 // enabled (for debug builds)

In short you are probably mixing release and debug dlls. Don't linked release dlls in debug or vice versa!
Comment: "In short you are probably mixing release and debug dlls" helped me. Thanks!
Comment: Waiwaiwait ! You mean to tell me that when I'm using MSVC, to get a Debug build I must recompile ALL the dependencies ? Even those I don't care to debug ? What the shit man ! I can't believe this !
Comment: I dont see in any .h or .cpp file any of _ITERATOR_DEBUG_LEVEL or _SECURE_SCL They exist only in obj files as:
/FAILIFMISMATCH:"_ITERATOR_DEBUG_LEVEL=0"
What about
Comment: debugging in release is always sketchy because release builds usually don't have debug symbols. You may have incorrect stacks and missed breakpoints. Due to optimization the code may not be the same as what you are looking at. `_ITERATOR_DEBUG_LEVEL` would probably be defined in the vcproj files if not then make sure you use debug dlls with debug exe and release dlls with release exe.
Comment: "In short you are probably mixing release and debug dlls" -> In my case the RuntimeLibrary was MultiThreadedDebugDLL in the Release build when it should have been MultiThreadedDLL.
Comment: What about skipping breakpoints by debugger in release? Some breakpoints are not filled and says debugger avoid them because of optimalization or linking something like this
Comment: +1 I was using release libs in a debug build as well, thanks !
Comment: @user626921 You have to compile all YOUR dependencies, since CRT libs are maintained by Microsoft if you're using Visual Studio then you simply link to the existing redistributable that got installed on your machine same as any other 3rd party library. The only tricky business is ensuring all your projects are linking to the right CRT libs for the target build you want as mismatches between release and debug libraries or other options can cause problems.
Comment: Why not allow release libs in debug mode with the corresponding graceful degradation in functionality (i.e. the code in the libs can't be properly debugged)? The more I look at C++, the more I like Java and C#. I mean, surely we could get the performance of C++ without having to work full time to manage administrative details if only the tool designers cared.
Comment: @MihaiDanila Just the opposite actually the performance of C++ is largely due to native compiled optimizations allowed by the standard which does not leave room for debugging info and wasteful overhead. Yes, you are required to know what you are doing but that is not a bad thing. Languages like C# that use managed intermediate layers or worse languages like Java that do that in addition to running within a virtual abstraction of the OS are always going to be slower because of this. That said use the right tool for the job at hand. I personally use all 3 of those languages regularly ;-)
Comment: Perhaps these conundrums go away as one becomes more acquainted to the language and its idiosyncrasies. But on the surface it seems overkill to enforce exact matching of debug levels across the components of a project in the name of performance, since we know full well that reduced performance is generally accepted and expected by the developer while the software is being developed on. Even so, can the error be more descriptive at least? Capture some common sense error level quality expectations in the standard or something. :)
Comment: The _ITERATOR_DEBUG_LEVEL is probably set in the "Projects Property Page->Configuration Propertys->C/C++ ->Preprocessor->Preprocessor Definitions" of the Debug Configuration
Comment: For me MSBuild made a bad assumption when I hadn't been explicit in my solution about related libraries.  Searching the build log "Project reference .* has not been resolved" showed me the libraries I should have added.
Answer: I make a little update on this issue, as I just had the same error today on an application which is linking against a static lib, after I migrated the old Visual 6 project to Visual Studio 2012.
In my case the error was that I mistakenly compiled the Release version of the static lib with /MDd instead of /MD, whereas the application is /MD in release. Setting the correct /MD in the static lib project solved the issue.
This is done in Project properties

Select Configuration Properties / C C++ / Code Generation in the tree
and the option Runtime Library set to the same on all your dependencies projects and application.
Comment: This one solved for me. THumbs up for you.
Comment: It's good to see that solutions on Microsoft C++ compiler from 1998 reissued in 2012 are still up to date in 2021 :-) The debug vs release build issues are still something to know deep by 2021.
Comment: TBH I'm compiling Assimp Codec and some other stuff for Ogre, I guess some of them can be quite obsolete.
Answer: If you would like to purposely link your project A in Release against another project B in Debug, say to keep the overall performance benefits of your application while debugging, then you will likely hit this error. You can fix this by temporarily modifying the preprocessor flags of project B to disable iterator debugging (and make it match project A):
In Project B's "Debug" properties, Configuration Properties -> C/C++ -> Preprocessor, add the following to Preprocessor Definitions:
_HAS_ITERATOR_DEBUGGING=0;_ITERATOR_DEBUG_LEVEL=0;

Rebuild project B in Debug, then build project A in Release and it should link correctly.
Comment: In my case I wanted to keep both in debug mode. One of them was a new static library. I defined _ITERATOR_DEBUG_LEVEL=2 in the new library and it stopped the link error in the module that was linking to the new library.
Answer: The error can be caused by mixing together debug builds and release builds in same executable or dll.

in the vs configuration manager, are some of your projects in debug mode and some in release mode?
is one of your release projects has the preprocessor symbol DEBUG or _DEBUG defined?
is one of your debug projects has the preprocessor symbol NDEBUG defined?
Answer: I had a mismatch between projects: one with multi-byte character set, the other with Unicode.  Correcting these to agree on Unicode corrected the problem.
Comment: It turns out that the project I was trying to build had this issue as well as an unexpected missing preprocessor in debug: _DEBUG.
See http://forums.codeguru.com/showthread.php?519376-mismatch-detected-for-_ITERATOR_DEBUG_LEVEL-value-0-doesn-t-match-value-2&p=2050461#post2050461
Comment: I had a similar problem mexing in Matlab, but the other way round: I needed to change the VS2013 build to multi-byte to get the agreement. This also resolved a mismatch for RuntimeLIbrary.
Answer: Last chance (if other ways don't work):
define _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH macro in all projects. It will disable "#pragma detect_mismatch" feature which is used in CRT headers.
Comment: I tried pretty much everything on this page, and this was the only thing that worked. Add `_ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH` under `C/C++ >> Preprocessor >> PreprocessorDefinitions`.
Answer: I had this problem as well.
My problem was that I had copy/pasted the library include directories from my debug configurations.
So project "Indep" was including static library "Dep.lib" from "../Debug", even in release.  The fix was to change the library directory to "../Release" so I caught the release-built library rather than the previously-built debug library.
Comment: Had a similar problem, where my static lib landed in the same place regardless whether release or debug. In that case one should name them differently by appending 'd' or such. Otherwise you would also be forced to rebuild the lib everytime you switch between debug/release.
Answer: I had the same issue between debug and release libraries.
The mistake was in the solution properties / Configurations properties / Configurations.
The projects configurations did not match the main configuration / platform.
Answer: Try change _DEBUG to NDEBUG macro definition in C++ project properties (for Release configuration)
Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions
Answer: opencv_core245.lib(dxt.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in test.obj   I got error like this.
I have opencv_core245.lib and opencv_core245d.lib in Linker->Input->Additional dependenc. Since this two were confilicting I removed first one opencv_core245.lib. Error gone.
Answer: Try this:
Goto project property -> C/C++ -> Code generation -> Runtime Library
Select from combobox value : Multi-threaded DLL (/MD)
It work for me :)
Answer: In my case, for both Debug and Release, the solution was to clean then rebuild entire solution.
Edit: true in my case also (VS2017)
step1: clean the project.
step2: change configuration mode(from debug to release or vice versa).
step3: clean the project.
step4: build in the required configuration mode.
PS: to change config mode, find config settings under build menu
Answer: Small addition to the help above:
I got the mismatch error after adding a static libto an older VST solution using VST 2017 .
VST now generates "stdfax.h" for precompiled headers containing these 2 lines:
// Turn off iterator debugging as it makes the compiler very slow on large methods in debug builds
#define _HAS_ITERATOR_DEBUGGING 0

Answer: I had the same problem today (VS2010), I built Release | Win32, then tried to build Debug | Win32, and got this message.
I tried cleaning Debug | Win32 but the error still persisted.
I then cleaned Release | Win32, then cleaned Debug | Win32, and then it built fine.
Answer: I managed to get rid of this error (in my case using Ogre3D + Bullet) by changing the dependency libraries to the debug versions in Project Properties -> Linker -> Input -> Additional Dependencies (VC10).
I changed BulletCollision.lib to BulletCollision_debug.lib (for debug configuration) and it compiled.
Answer: I resolved my trouble in correcting the "Additional Library Directory", this one was wrong in indicating "$(SolutionDir)\Release", I changed it in "$(SolutionDir)\$(IntDir)"
To correct it, open your project properties -> Configuration Properties -> Linker -> General -> Additional Library Directory
I hope this will help some poeples with the same trouble ;)
Comment: so for me Debug works fine but when building in release I get the above error.... I opened Additional Library Directory I found: C:/Program Files/PCL 1.8.1/lib/$(Configuration)  what should I add now here?
Answer: I also had this issue and it arose because I re-made the project and then forgot to re-link it by reference in a dependent project.
Thus it was linking by reference to the old project instead of the new one.
It is important to know that there is a bug in re-adding a previously linked project by reference. You've got to manually delete the reference in the vcxproj and only then can you re-add it.  This is a known issue in Visual studio according to msdn.
Answer: I had similar problem, but the wrong setting was in the extern .lib file from which I did not have sources. If you do not have the source files, the simplest workaround is to just change the content of the .lib file.
Open the .lib file in an editor (I used PSPad, bud Windows notepad is also possible) and replace all occurences of _ITERATOR_DEBUG_LEVEL=2 to _ITERATOR_DEBUG_LEVEL=0
Answer: In my case the NDEBUG macro definition in the "Preprocessor Definitions" needed to be changed to _DEBUG.  I am building a static library for use in a .exe which was complaining about the very same error listed in the question.  Go to Configuration Properties ("Project" menu, "Properties" menu item) and then click the C/C++, section, then the Preprocessor section under that, and then edit your Preprocessor Definitions so that NDEBUG is changed to _DEBUG (to match the setting in the exe).
Answer: Like all the other answers, I checked my Configuration Properties -> C/C++ -> Preprocessor directives.
In my case I had the NDEBUG correctly defined in Release, but I also had: _SECURE_SCL=1.
Removing that one fixed the issue.
Answer: For me it's just a properties problem, change C/C++ /code generation/MDd to MD solved it
Answer: Ditto. I was linking a Release-level library to a Debug EXE.
Cause of problem: I had included the .LIB by right-clicking on the Project in Solution Explorer, choosing "Add ➔ Existing Item" and browsing to the .LIB file.
Fix: Go to Project Properties instead. Include a different .LIB in each of the Debug and Release by adding them to the list. Go to Linker ➔ Input, and add the version of the .LIB appropriate for the Configuration.
Answer: one of the projects is set to debug and others are set to release in configuration manager..  was lost in all other settings.
Answer: I encountered this issue when Qt's plugin converted a qmake project to a Visual Studio C++ project. The error was being reported in a dependency managed by vcpkg (gRPC). The reported conflict was between gpr.lib (dependency of gRPC) and an OBJ file from a CUDA kernel compilation. Not sure if that is significant.
I turned on verbose linker logging and saw that it was searching debug versions of gRPC, and then also searched release versions as well.
Project properties \ Linker \ General \ Show Progress \ Display all progress messages (/VERBOSE)
Then I stumbled across the vcpkg settings and saw there was a "Vcpkg Configuration" option that was set to "Release" for both my Debug and Release configurations. Setting that to "Debug" for the "Debug" configuration resolved the issue for me.


How do you access the menus given a QMenuBar?

Question: In Qt how do you recover the menus given a populated QMenuBar?
They do not seem to be the menu bar's children. For example, after the following (where the menu creation functions succeed and do what you expect)
menuBar()->addMenu(create_file_menu(this));
menuBar()->addMenu(create_view_menu(this));
auto children = menuBar()->children();
auto first_child = children[0];

children ends up with a size of 1 and that one child, first_child, is some object of type QMenuBarExtension. I was expecting to get two children with the first being the file menu.
I'm using Qt6 if that matters.
Answer: A QMenu is added to a QMenuBar internaly via QWidget::addAction(menu->menuAction()) (see <QtInstallPath/src\widgets\widgets\qmenubar.cpp>.
From QWidget you can retrieve the added QActions via QWidget::actions() - method which returns a list of associated QActions. In your specific example menuBar()->actions() should retrieve at least two actions for your menus.
However, there seems to be no way to get from a QMenu::menuAction() - created QAction back to the associated menu. Therefore you may need to store a pointer to your created QMenu - objects on your own.
Comment: ah, yeah, i didnt realize toplevel menus have actions associated with them. Don't really need the QMenu since I can enable/disable the action.


Not sure what drill bit to use for 6mm masonry anchor into brick

Question: Similar to this question diy.stackexchange.com#q136613 but not sure exactly and I still don't know what I should do, so I'm opening a new one.
I have a masonry anchor that is 6x30 and want to drill into brick wall. To make a hole I only have {5/32, 3/16, 1/4} in (IINM, these are 3.97mm, 4.76mm, and 6.35mm respectively) drill bits (Ryobi (homedepot.com). I looked around for awhile at a local Home Depot, browsing as many sections in and outside of Ryobi but couldn't find exact 6mm diameter bit. I also went into rental dept. at Home Depot but they didn't have an exact size of bit either.
I started drilling with 3/16 bit then the anchor doesn't even "sink". Then switched to 1/4 in. bit then the masonry anchor doesn't seem to stick at all as the hole may be too wide.
What should I do? I think of the following but

Find exact 6mm bit? I found this (amazon.com) but different brand than my drill (Ryobi), which seems to like hex.
Find a drill bit as close as possible to 6mm? Then how big the difference can be?

The thread I referred to above seems to handle smaller size diff, so that makes sense for that case. But in my case like I wrote above, 2 bits with I have don't work well.

Else

I have a floodlight that I bought from ring.com and AFACT its instruction (booklet, nor online (support.ring.com)) doesn't include any info about the recommended size of equipment to be used.
Masonry anchor that came with the floodlight

UPDATE: Thanks for the comments. I was going to try some/all of suggestions, but then I happened to find after a while that in another device I bought from the same manufacturer (floodlight from ring.com) comes with a masonry anchor plug with a very similar size, AND the masonry drill bit 6 mm. So I just used that drill bit and 6x30 anchor indeed fit well. Problem solved for me.

Just to make doubly-certain? when you say at 1/4" the anchor doesn't hold? you did test this with the appropriate screw in place? It won't tighten in until the screw forces it wider.

Good point. I hadn't back then.
The hole I made with 6 mm drill bit is very tight for the anchor, I agree 1/4 inch drill bit might work with the anchor plug tightens once it's screwed.
Comment: The drill bits you linked to at HD have hex-shanks. Does your drill have only a quick-change hex-shank? If so, then yes, you'll have to stick with hex-shank bits. If it has a "traditional" style 3-jaw chuck, then it can accept _any_ bit at all. Also, whatever type of chuck it has, just because it's a Ryobi drill does _not_ mean you have to have Ryobi brand drill bits, no matter _what_ the marketing seems to suggest.
Comment: Just to make doubly-certain… when you say at 1/4" the anchor doesn't hold… you *did* test this with the appropriate screw in place? It won't tighten in until the screw forces it wider.
Comment: A 1/4" hole really should work fine for a 6mm anchor. That extra 0.35mm should make no noticeable difference.
Comment: You already got it resolved, which is good. My usual method in a similar situation is to go with a smaller bit and after drilling the hole normally, widen it a bit using the same bit and moving it around. Not the best technique (especially to have the bits last a long time...) but in a pinch does the job.
Comment: I'm glad you got this figured out, but really, you want those plastic anchors to be a _snug_ fit, so you want the hole for them to be a bit smaller than the diameter of the plug, then you _hammer_ them in to ensure it doesn't go anywhere. Especially true for masonry, needs to be done gently if you're going into drywall (or you risk breaking the sheet of drywall).
Comment: Probably want a 7/32 bit.  Would see about prices for drill bit sets rather than buying single drill bits.  Could also get a different anchor type.
Comment: @FreeMan +1. I found with 6mm drill bit the hole was very tight and the anchor didn't make it to the end so I ended up hammering it down.
Answer: From an edit the OP made to his question:
I was going to try some/all of suggestions, but then I happened to find after a while that in another device I bought from the same manufacturer (floodlight from ring.com) comes with a masonry anchor plug with a very similar size, AND the masonry drill bit 6 mm. So I just used that drill bit and 6x30 anchor indeed fit well.
Problem solved for me.


Go WorkGroup doesn't synchronize functions

Question: This is just an abstract example. test will work as long as it receives messages from test2. Then when they are all done wg.Done() will be called, and application will close after wg.Wait().
package main

import (
    "fmt"
    "sync"
)

var a = make(chan bool)
var wg sync.WaitGroup

func main() {
    go test()
    wg.Add(1)
    for i := 0; i < 5; i++ {
        go test2()
        wg.Add(1)
    }
    wg.Wait()
}

func test() {
    defer wg.Done()
    for {
        val := <-a
        fmt.Println(val)
    }
}

func test2() {
    defer wg.Done()
    for i := 0; i < 3; i++ {
        a <- true
    }
}

At least this is theory, but it doesn't translate well to practice. It correctly displays true 15 times, but then application crashes with a deadlock, because wg.Done() is never called. I'm quite stumped, because this is how it's done in tutorials.
Answer: The goroutine created in test will never terminate, because of that, the wait group count will never reach zero and it will wait indefinitely.
Terminate the endless for-loop after 3 writes and the program should work, because you are reading 3 times from the channel.
Also, you have to call wg.Add before creating the goroutine, not after. wg.Done may be called before you can add to it, causing a panic.
Comment: No. The way you are doing is wrong. Of course it can be done with golang.
Comment: You seem to lack the basic understanding of how channels work. Work through the tour of go, and there you can see how it is done.
Comment: What should I do if we assume that I don't know how many messages I will receive?
Comment: Usually, the sending end closes the channel when done, so the receiver end can range on the channel. range will receive from the channel until it closes.
Comment: I can't close the channel in test2 because I can't be sure that it was closed in the last step.
Comment: You should close it in `test`, not `test2`
Comment: So the answer is that this type of application cannot be done with golang.


Can you sync PSVita trophies from a NTSC Game with a PAL Account

Question: I know that a PSN Account is tied to the memory card which means if you wanted a NTSC (US) and PAL (UK, Aus) PSN Account you would need 2 memory cards.
With that said, in terms of trophies, can you sync trophies that were obtained from an NTSC game with a PAL PSN Account? Here's an example:
I have Atelier Totori Plus on my Australian PSN Account (PAL). If I were to get a NTSC copy of Ragnarok Oddysey and got its trophies, could I sync them to the same account as my PAL PSN Account or can I only sync it with the NTSC Account that I would use to get its DLC?
EDIT: I should note that in my example Ragnarok Oddysey is preferably a physical copy, not downloaded.
Comment: Have you already earned the trophies on the NTSC account or are you looking to start the game on one account or the other?
Comment: @Colin i'm looking to start a new game of Ragnarok Oddysey (NTSC) and have it's trophies synced to my PAL PSN Account to add to the rest of my games, i have to have the memory card bound to my NTSC PSN Account for the Ragnarok Oddysey DLC in when i play the game and i'm not too sure how trophies are stored on the PSVita so i can't do what i do with the PS3 and download the DLC from one user then switch back to my main user
Comment: Trophies are tied to your PSN Account. If you can play your US game while being signed into your Australian account, the trophies should go to your Australian account. This is possible on PS3 but I'm not sure about Vita. It sounds like you'd have to somehow copy the game to your Aus account memory card. Can the PC content manager software do this?
Comment: @YellowMegaMan No this will not work as digital purchase of the game is not tied to the australian account. If the DLC is not available in the region specific store of the account you want the trophies on I don't this it will be possible.
Answer: Yes, you can. I have a US copy of Mortal Kombat for the PSVita and its trophies sync with my PAL account just fine.
That said, it depends if you can play the game while signed in to your account, so with an NTSC Vita game played off a game card - it's possible, but since games downloaded are locked to a single account on the Vita, you won't be able to download an NTSC copy and play it while signed in to your PAL account.
Regarding the DLC you've mentioned - it's a different problem. You cant download DLC for NTSC games with a PAL account, nor you can play Vita DLC with an account other than the one owning it. So in your case, getting a US copy of Ragnarok Odyssey will lock you from playing and earning trophies for its DLC on your PAL account.


Can 12 AWG THHN/THWN wire be placed in a buried conduit?

Question: My understanding is all buried wire in conduit must be THWN-2.
Per Southwire's spec sheet here the end of the first paragraph reads:

All Sizes Rated Both THHN and either THWN (sizes 14, 12, and 10 AWG)
or THWN-2 (sizes 8 AWG and larger).

It is baffling me that there doesn't seem to be THWN-2 in 12 AWG.
What do folks do for 20A circuits buried in conduit?
Background, I'm doing all this in conjunction with running 4-8's for a separate 35A 240V circuit to a mini-split. And figured I should fix the previous homeowners error of running 12/2 romex in that buried 3/4" PVC conduit.
Upsizing a 20A circuit to 8 THHN just to get a THWN-2 rating doesn't make sense to me, and I'd run into fill issues.  I would then need to upsize the conduit (not out of the question, but seems an extreme path to take).
Running 12 AWG UF-B in the conduit seems to be the other code compliant. While permitted that seems extreme as well and I'm not sure how to calculate fill using 12 UF-B + 4 8 THHN. Again, likely having to upsize the conduit.
I assumed I could just run 2-12 THHN/THWN (20A circuit A) and add the 4-8 THHN/THWN-2 (35A circuit B), and using one of the 8s as a common ground on both circuits. 6 wires total, fill would be 33%.
I'm wondering if there is some footnote in the NEC that says wire under 8 AWG actually only need to be rated THWN in buried conduits. Or if someone actually makes 12 AWG THWN-2, just not SouthWire?
Comment: @NoSparksPlease Because UF is very, very flat and wide instead of round like it could be.  Making it a worst case scenario.   A 6/3UF requires a 2" conduit.  (You can easily use the Harper shortcut: 1 wire in conduit needs conduit ID to be 138% of wire OD).
Comment: Circuits up to 60A only require a #10 ground. Do not run UF in conduit, besides being a
 hard pull and hard to legally support when entering a cabinet, the code requires calculating conduit fill of a cable assembly as a single round conductor based on the largest dimension of the cable. Normally that requires bigger conduit than would seem obvious.
Comment: @Harper-ReinstateMonica And directly to this question 53% fill of 3/4" sch 40 PVC is only 0.269 in². Encore 12-2 uf has a large dimension of  0.415" making it's area 0.54 in², 53% fill requiring 1.25" pvc.
Comment: @NoSparksPlease I think you made a math error there.  I try to simplify it by using "circular inches" (millions of circular mil if you prefer), so 0.415" diameter squared becomes 0.172 circular inches, or 172 kcmil.    Handle conduit diameters the same way, and it takes pi out of the equation.
Answer: Not sure where you got the idea that you need THWN-2, only.
All you need is the W.
TWN, THWN, RHW, XHW, XHHW, etc. are all perfectly fine, because they have the W that means they are waterproof, that means they can go in outdoor conduit. Most THHN is also THWN and MTW (multiply rated.)
If you are in a situation where the wire temperature may be extreme you might need to get picky for insulation temperature rating; but to be in exterior conduit (buried or not, they are all wet locations), all it needs is the W.
Answer: THWN is rated for wet locations
As Ecnerwal discusses.
The issue is thermal
The difference is at the top of Table 310.15(B)(16).

THWN is allowed 75 degree C running temperature.
THWN-2 is allowed 90 degrees C.
THHN also is allowed 90 C

Southwire is making a disclaimer: they are saying they don't guarantee #14-10 will be THWN-2. What's on their mind is a different table, NEC 240.4(D), which places artificial limits on #14, #12 and #10 wires, to limit them to 15A, 20A and 30A regardless of tables or thermal calcs.
Their logic is "heck, you can't run these wires at thermal limits anyway, so why do they need to be -2?"
However this still can bite you if you have multiple circuits in the pipe.  You must still do thermal derate calcs based on 310.15(B)(3)(a). Those derate calcs come off the highest temp allowed for the insulation. If the wire is THWN and not THWN-2, you're forced to calculate off the 75C number instead of the 90C number. That won't make a difference with up to 3 circuits in single/split-phase territory (2 in 3-phase territory) but it'll be problem getting to 4 circuits (or 3 in 3ph).
Cable in conduit is about swept area
Anytime you put a non-round cable in a conduit, you must treat it like helicopter blades: it occupies space like a round wire of the large dimension.  Because it twists.
This means an oval cable, especially a very wide oval cable like UF, sweeps an awful lot of area in the conduit - to the point that UF requires outlandishly large pipe. One 6/3 UF requires a 2" pipe, no kidding, do the calc yourself! Here's Harper's shortcut: A single cable needs 138% of its wide width as the interior dimension of the conduit, but this gets much worse if there are 2+ wires present.
NM or NM-B is already wrong in outdoor conduit because of the "wet rating" problem of course, but UF isn't an automatic upgrade because UF takes more space.
You do need to remove the NM-B, but not just over the wet rating; it's because the circular area of the NM-B, plus the #8 wires, has most likely overstuffed the conduit.
Comment: Thank you for the through and referenced answer.  I understood the rated temp difference, but I thought (not sure why now) _all_ outdoor buried in conduit wire had to be 90C, and hence THWN-2.
Comment: @jb510 Yup, that only applies if you're bundling enough wires that you need the 90C for derating purposes, i.e. using my "no more than four" rule of thumb.
Answer: For most applications you would use wire in household installations, you don't need the THWN-2. The 90C rating is pointless for anything other than when you need to de-rate wire for having a lot of conductors in a single conduit. Most residential products have terminals rated for 60 or 75C anyway, so you still end up sizing the wire for that anyway, meaning the "-2" is pointless.


Simple Divisor Sum Transformation by Changing the Order of Double Summation

Question:
Show that
$$\sum_{d|n} \frac{n}{d} \sigma(d) = \sum_{d|n} d \tau(d)$$
by changing the order of summations from each side to the other. $\sigma$ and $\tau$ are divisor sum functions.

Yes, I do can prove this by putting $\sum_{d|n} \frac{n}{d} \sigma(d)=F(n)$ and $\sum_{d|n} d \tau(d)=G(n)$ and using the property of multiplicative function. However, since professor mentioned that we have to be familiar with changing the order of summations, I tried to solve this just directly. But unlike other problems, some kind of mysterious cycle just looped again and again regardless of which side I choose to transform into the other.
Here is what I've been doing with the left side (but the miserable failure was just about the same as starting from the right side).
$$\sum_{d|n} \frac{n}{d} \sigma(d)=\sum_{d|n}\frac{n}{d} \sum_{c|d}c $$
Let ck=d where k is a positive integer. Then by changing the order of the summation,
$$\sum_{d|n}\frac{n}{d} \sum_{c|d}c
=\sum_{c|n}c\sum_{k|\frac{n}{c}}\frac{n}{ck}
=\sum_{c|n}n\sum_{k|\frac{n}{c}}\frac{1}{k}$$
Then one might notice that since $k$ is still remaining there, there is no possibility (at least for me...) to make $\tau$ to come out. Only $\sigma$ will just come out again to no avail and return to the very first state. I actually tried
$$\sum_{d|n} \frac{n}{d} \sigma(d)=\sum_{d|n} d \sigma(\frac{n}{d}) $$
but this one failed, too. So logically, my conclusion was that there is some kind of manipulating terms that can make me out of this infinite looping, but I haven't recognized the method yet. I think if I can tackle this problem from any side, then I could deal with the other side using a similar way.
Could anyone help me solving the secret of changing the order of summation? Thanks.
Answer: Start with $$\sum_{d|n} \frac{n}{d}\sigma(d)
= \sum_{d|n} d \; \sigma\left(\frac{n}{d}\right).$$
This is
$$\sum_{d|n} \sum_{e|n/d} de.$$
Now put $q=de$ to get
$$\sum_{d|n} \sum_{q/d|n/d} q
= \sum_{q|n} \sum_{d|q} q
= \sum_{q|n} q \sum_{d|q} 1
= \sum_{q|n} q \; \tau(q).$$
The first equality holds because $q/d|n/d$ means that for some $m$ we have $m q/d = n/d$ which means $mq =n,$ so $q$ is a divisor of $n$, and the number of times that it occurs is the number of $d$ such that $d|q$ or $\tau(q).$
Comment: So the idea was to make $de=q$ so that $\sigma$ will never arise again... Thanks. That was clever.


How to open Boostrap 3 modal box from Vanilla Javascript

Question: I have tried to open the Modal box like this.
window.getElementById("modal-box-click-counter").showModal();

and
var modal = document.getElementById("modal-box-click-counter");
      modal.modal("show");

This is the whole script I am trying to get to work:
function clickCounter() {
  var clicks;

  function loadClicks() {
    clicks = sessionStorage.getItem("clickcount");
  }

  function setClicks() {
    sessionStorage.setItem("clickcount", clicks);
  }

  function init() {
    loadClicks();

    if (clicks >= 4) {
      console.log("WORKING " + clicks);

      // I WANT THIS TO WORK.
      $("#modal-box-click-counter").modal("show");

    } else {
      clicks++;
      setClicks();
      console.log(clicks);
    }
  }

  if (typeof Storage !== "undefined") {
    window.addEventListener("click", init);
  } else {
    console.log("Sorry, your browser does not support web storage...");
  }
}

window.addEventListener("load", clickCounter);

But I can't get it to work. I have JQuery and Bootstrap loaded in the right order in functions.
Answer: If you have no egde cases you can simply work with the official bootstrap example: Modal Live Demo 3.4
Comment: Yes I am, but there is no Vanilla Javascript there on that link, only JQuery.
Comment: Ok, maybe this answer could help you: [How to open a Bootstrap modal without jQuery or bootstrap.js javascript](https://stackoverflow.com/questions/53594423/how-to-open-a-bootstrap-modal-without-jquery-or-bootstrap-js-javascript)


How to find the range of possible numbers of vertices and edges of a convex polyhedron, given the number of faces?

Question:
A polyhedron has $F$ faces. Find all possible amounts of its vertices and edges.

Of course, for small values of $F$, it's possible to just list the possibilities. But how to handle the general form of that task? Just plugging the faces into Euler's formula won't be enough.
Comment: Do you allow any [abstract polyhedron](https://en.wikipedia.org/wiki/Abstract_polytope) or are there geometric/topological restrictions?
Comment: You can assume that each vertex has degree $3$ or more. This leads to $3v\le 2e$, and then $e\le 3f-6$, so you have at least an upper bound on the number of possibilities. You similarly have a lower bound by assuming that the $f$ faces all have at least $3$ sides. I'm not sure whether the whole range is always achievable with flat faces.
Answer: In such a question, as the cited one, "polyhedron" usually is meant to be defined as convex, i.e. the set of points contained within the intersection of halfspaces. There Euler's formula does apply in its easiest form, i.e. according to $V-E+F=2$. $-$ Thence in the followings we assume this setting to be given.
First we consider the medium number $S$ of edges per vertex. That one then obeys the following equation: $VS=2E$. And furthermore, by geometric restriction, we can assume $S\ge 3$. In other words we get $3\le S=2E/V$.
Solving this relation for $V$ and inserting that into Euler's equation finally provides $E\le3F-6$. Solving it instead for $E$ and inserting that into Euler's equation instead would provide $V\le2F-4$.
Next we consider the medium number $N$ of edges per face. That one then obeys the following equation: $NF=2E$. And furthermore, by geometric restriction, we can assume $N\ge 3$. In other words we get $3\le N=2E/F$.
Solving this relation for $E$ directly provides $3F/2\le E$. Solving instead for $F$ and inserting that into Euler's equation finally provides $F/2+2\le V$.
Thus, combining these results, we get:
$$\begin{array}{rcccl}
F/2+2 & \le & V & \le & 2F-4\\
3F/2 & \le & E & \le & 3F-6
\end{array}$$
As already was mentioned within a comment, these ranges however do not tell whether any according value pair of $V$ and $E$ truely would be taken, i.e. that there would exist an according polyhedron with such indivdual values. It just tells the opposite: outside of these ranges there cannot be found any (convex) polyhedron with such values.
--- rk


datepicker plugin of jQuery does not send the value to backend in Struts 2

Question: I am using jQuery to show calendar, it perfectly work but when I submit the form backend does not receive the result >> result is null.
    <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

    <link rel="stylesheet" href="/resources/demos/style.css">


Subclass awakeFromNib to call a superclass custom init/setup method?

Question: I have a 3rd-party UIViewController that is designed to be initialized with -(id)initWithURL:(NSURL*)url only. There are no other init-family methods declared. I'd like to subclass this to be used with Storyboard so something like [super initWithURL:[NSURL URLWithString:@"about:blank"]] is called automatically. Design pattern aside, it's just the goal du jour.
I've tried this to no avail in the subclass:
- (void)awakeFromNib {
    [super awakeFromNib];

    if ([super respondsToSelector:@selector(initWithUrl:)]) {
        [super performSelector:@selector(initWithUrl:) withObject:[NSURL URLWithString:@"about:blank"]];
    }
}

The above gives a compiler error about the selector retaining an object. Now, the superclass initWithURL:is just this
- (id)initWithUrl:(NSURL *)url {
    // Set url and init views
    _url = url;
    [self setup];
    return self;
}

so I've tried to call [super performSelector:@selector(setup)] from awakeFromNib, but of course the private variable _url cannot be set from the subclass. How can I accomplish this for Storyboard use?
Answer: You will want to override the initWithCoder: init method in your UIViewController subclass. This way you can return a different instance when the UIViewController is being created.
- (instancetype)initWithCoder:(NSCoder *)decoder
{
    self = [super initWithURL:[NSURL URLWithString:@"about:blank"]];
    return self;
}

Some additional reading about how objects are initialized from the storyboard: Responding to Being Loaded from a Nib File
Comment: That's it. Very good write up. I've never used `initWithCoder`, nor storyboard that much. Thank you.


How do I improve my Land Price (LP) ranking?

Question: In Venture Towns for iOS, you need to improve your Land Price for your shops in order to get a high ranking at the end of the year.
I haven't even been able to make it into the top 100. What sorts of things can I do to make my rankings/my Land Prices better?
Answer: It seems like you can get a huge bonus for putting certain buildings together and creating a "Specialty District," although I've also seen this called a "Combo."
There's a pretty exhaustive list of parts of the game in this Google Doc spreadsheet, which might be enlightening reading, although it's a bit dense.
I found a list of combos in this message board post.  I don't believe it's 100% complete, but it might be enough to help you figure out what the pattern is:

Pleasure - Casino, Arcade, Bowling Alley
Health - Hospital, Sports Gym, Spa/Jpn Rest
Shopping - Supermarket, Boutique, Jeweler
H. Springs - Jpn Rest, Woods, Lake
Culture - Jeweler, Art Museum, Movie Thtr
Gourmet - Sushi Bar, Chinese Rest, Bar
Student - Trade School, Steakhouse, Diner
Fashion - Boutique, Art Museum, Drugstore
Business - Office, Office, City Hotel
Intellect - Bookstore, Trade School, Art Museum
Geek - Elec Shp, Anime Shp, Game Shp
Kids - Toy Str, Park, Game Shp
Tourist - Woods, Mountains, City Hotel/Jpn Rest
Local - Cake Shp, Greengrocer, Florist/Fish Monger
Industry - Scooter Shp, Car Dealer, College
Date - Theme Park, Zoo, Movie Thtr/Arcade
Sports - Stadium, Bsbll Field, Sports Gym
Nature - Pasture, Park, Woods/Lake
Lunch - Cafe, Deli, Bakery
Silicon - PC Shp, Mobile Shp, Game Co.
Ancient - Monument, Pagoda, Jpn Garden
Animal - Zoo, Pet Shp, Pasture
Media - Antenna, Concert Hall, TV Station
Fishy - Fishing Pond, Aquarium, Fish Monger
Hacker - Pizza Parlor, Fast Food, Security Co.
Rock - Record Str, Video Rental, Concert Hall
Ghost - Skyscraper, Skyscraper, Skyscraper/Antenna
Hollywood - Movie Thtr, Theme Park, Jeweler/Boutique
Special - Airport, TV Station, Office (M)

There's also this page which purports to have some help information on it, but it looks like it just might be a transcription of the help files in the game, so I don't know how much value that will add to you.
I also found this thread, which covers (I'm guessing) the Japanese version, but I bet the core gameplay is the same.
In one place I found a reference to something called a "house combo" but the tip was unsourced and I couldn't find any other reference to such a thing.  If you're still stuck after mastering Specialty Districts, you might try to figure out if this is possible and how.
Comment: Holy cow. Awesome information overload! Hurray!
Comment: @AshleyNunn, I am like a *ravenous attack dog* frothing at the mouth with *pure, unadulterated data.*
Comment: that would explain a lot. ;)
Answer: There are several ways to increase land prices.

Adjacent buildings - simply building two businesses adjacent to each other increases their land value.
Adjacent plants - Many plants increase the land value of businesses they're next to.
Adjacent roads - Roads are one of the most effective land price boosters. They're also the only thing that can be built on an incline tile. (They're especially useful on the Caldera City map, where all those hills would otherwise be wasted space.)
Land Price Seed item - Using this item on a building instantly and permanently increases its land price. You can use up to 10 of them on a building before they're no longer effective.
Combos - Placing buildings in a combo configuration increases the land price of all buildings in the combo, and sometimes buildings adjacent to the combo (the amount of increase depends on the combo type). This page is an excellent resource with a complete combo list.

Layering combos, or placing multiple combos adjacent to one another is the most effective way to increase land price, and probably the only way to get to #1. For example, you can build Culture, Fashion and Intellect combos together by sharing an Art Museum between all three. Use a few Land Price Seeds on that Art Museum, and you'll hit #1 land price in no time.
Answer: Nature Combo
Your first source of high land prices would be the ones that rely on nature: H. Springs Combo (Jpn Rest.) and Tourist Combo (Jpn Rest./Hotel). These work best on most of the maps where you have a lot of 'dead' land area and can be very cheaply implemented provided that you get a Japanese Restaurant early. Set it something like the following
 MMM
 WWW
 HJH
RRRRR

Where M can be mountains or a lake/river, W is woods either naturally or deliberately placed, H are your houses, and J is your Japanese Restaurant/Hotel. You can always reduce the layer of wood if you don't have the space, but this is great for filling small areas. Using a City Hotel instead of a Jpn. Rest. also lets you stack a Business Combo on top of it, for a massive 55% boost to land.
Business Combo
The Business Combo gives a whopping +35% land, easily the best. The only problem is that you'll end up with a redundant Office, but it's almost always worth it. I have about 4 of these in my most successful towns so far. The +30% product price makes them sandwich well with Jewelers, Car Dealers, and the Pleasure Combo.
Art Museum
Art Museums combo with a lot of cheap structures. Use the Art Museum combined with all of its combos to create a "downtown" rich man zone. Plop a Business Combo next to one and you'll easily get your Museum up into the $60k+ range. Combined with Land Price seeds, I got my Museum up to $100k+ LP, easily winning the #1 for land.


Get android Ethernet MAC Address (not wifi interface)

Question: I'm using Android with Api level 8 and I want to get the Address of my Ethernet interface (eth0).
On API level 8, the NetworkInterface class don't have the function getHardwareAddress().
The WifiManager also does not work since this is not an Wireless interface.
Thanks in advance!
Answer: This is my solution based on the Joel F answer. Hope it helps someone!
/*
 * Load file content to String
 */
public static String loadFileAsString(String filePath) throws java.io.IOException{
    StringBuffer fileData = new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    char[] buf = new char[1024];
    int numRead=0;
    while((numRead=reader.read(buf)) != -1){
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
    }
    reader.close();
    return fileData.toString();
}

/*
 * Get the STB MacAddress
 */
public String getMacAddress(){
    try {
        return loadFileAsString("/sys/class/net/eth0/address")
            .toUpperCase().substring(0, 17);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Answer: Assuming your ethernet interface is eth0, try opening and reading the file /sys/class/net/eth0/address.
Comment: excelent!it worked. Do you think it work in any android device with eth0?
Comment: It ought to, that's a standard Linux kernel path that I doubt they would change anytime soon.  Glad it helped.
Answer: public static String getEthernetMacAddress() {
    String macAddress = "Not able to read";
    try {
        List<NetworkInterface> allNetworkInterfaces = Collections.list(NetworkInterface
                .getNetworkInterfaces());
        for (NetworkInterface nif : allNetworkInterfaces) {
            if (!nif.getName().equalsIgnoreCase("eth0"))
                continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return macAddress;
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                res1.append(String.format("%02X:", b));
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            macAddress = res1.toString();
        }
    } catch (Exception ex) {
        log(LogLevel.ERROR, "getEthernetMacAddress e :" + ex.getMessage());
        ex.printStackTrace();
    }
    return macAddress;
}

Comment: This solution works and doesn't need any read permissions. Thanks!
Answer: this way to use java fix it; maybe can help you
NetworkInterface netf = NetworkInterface.getByName("eth0");
byte[] array = netf.getHardwareAddress();
StringBuilder stringBuilder = new StringBuilder("");
String str = "";
for (int i = 0; i < array.length; i++) {
    int v = array[i] & 0xFF;
    String hv = Integer.toHexString(v).toUpperCase();
    if (hv.length() < 2) {
        stringBuilder.append(0);
    }
    stringBuilder.append(hv).append("-");
}
str = stringBuilder.substring(0, stringBuilder.length()- 1);

Answer: Check also /sys/class/efuse/mac at least on Amlogic platforms.
Answer: Maybe my answer will be helpful to a few of you out there, and at least funny for the rest of you.
I was trying to get the ethernet MAC address for an Android TV device, to try to find the actual manufacturer the MAC address is registered to. I connected to the device with adb and used Joel F's great answer above and it worked great.
Then I flipped the box over and there it is on a sticker on the bottom of the device.
So if you don't need it programatically, try flipping the device over first.
P.S. I contacted the manufacturer the address is registered to, and they said they don't make this model and that other manufacturers copy their MAC addresses.
Answer: Right now (March 2014) Google doesn't privides an API about Ethernet
This is the rason because we don't have a way to get the ethernet mac like in wifi case.
private String getWifiMACAddress(Context ctx) {
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
   return info.getMacAddress();
}

One alternative is reading the eth0 file. Please let me know if anyone knows otherwise!
Answer: Many implementations of AndroidTV may have it populated in property, you could check with getprop command to find the correct property name ad then read it using  SystemProperties.get()
for reading the MAC in the program in java you could use something like following
SystemProperties.get("ro.boot.ethernet-mac");

Answer: Kotlin version of 'a.prateek' solution:
fun getEthernetMacAddress(): String? {
    try {
        val allNetworkInterfaces: List<NetworkInterface> = Collections.list(NetworkInterface.getNetworkInterfaces())
        for (networkInterface in allNetworkInterfaces) {
            if (!networkInterface.name.contains("eth0", ignoreCase = true)) continue
            val macBytes = networkInterface.hardwareAddress ?: continue
            val macStringBuilder = StringBuilder()
            for (byte in macBytes) {
                macStringBuilder.append(String.format("%02X:", byte))
            }
            if (macStringBuilder.isNotEmpty()) {
                macStringBuilder.deleteCharAt(macStringBuilder.length - 1)
            }
            return macStringBuilder.toString()
        }
    } catch (e: Exception) {
        Timber.e(e)
    }
    return null
}


Inno Setup: How to change background color

Question: Is there a way to change the background color of the Inno Setup bottom panel to white color?
Thanks for your help!
Answer: That bottom panel that you described is actually the area of the Wizard form, and so you can just set the Color property of the WizardForm object itself:
[Code]
procedure InitializeWizard;
begin
  WizardForm.Color := clWhite;
end;

There's yet one more thing worth mentioning; though the above code shows how to set that area color to a constant white as you asked, what you can see on your screenshot as white is actually a color given by the Windows theme, so that color must not always be white. So if your aim was to have the same color as the page you're currently on, then you should rather inherit the color from the parent pages:
[Code]
procedure CurPageChanged(CurPageID: Integer);
begin
  case CurPageID of
    wpWelcome: WizardForm.Color := WizardForm.WelcomePage.Color;
    wpFinished: WizardForm.Color := WizardForm.FinishedPage.Color;
  else
    WizardForm.Color := WizardForm.InnerPage.Color;
  end;
end;

Comment: See also follow up question, [Changing background color of task list box and other controls in Inno Setup](https://stackoverflow.com/q/52441557/850848).
Comment: You're welcome! I've added some talk about the white color :)
Comment: Another related question: [How to change background color of SelectDirBitmapImage and SelectGroupBitmapImage in Inno Setup](https://stackoverflow.com/q/61083816/850848).


No Cookie / No IP Tracking a Visitor

Question: Problem Statement:  Track an anonymous user to persist state (or lock out of a feature after a timer) on a device that has visited a website.  This would need to work with cookies disabled, across browsers, including visits in incognito mode.  This also would need to be device specific, 2 computers within a home network would have 2 independent timers.
I have seen this applied in a few scenarios with the most recent being the NBC Olympics with the stream timer.  This has so many uses for "free no sign-up trials" while not giving away everything or limiting features in "try before you buy".  Any ideas would be appreciated!
Comment: "not prevent two different devices sharing an IP from locking each other out." The double negative is confusing and it contradicts the "No IP" part of the question's title. Effectively, you're saying, "Once the timer elapses, the mechanism should prevent all devices sharing the same IP address from using a feature." However, you're also saying the mechanism cannot use end-user IP addresses? Did I understand that correctly?
Comment: Updated phrasing to clarify.  Thanks.
Answer: For this you would need to employ a cross-browser fingerprinting (or device fingerprinting) technique.
Related research
I recommend you read the paper (Cross-)Browser Fingerprinting via OS and Hardware Level Features by Yinzhi Cao, Song Li, and Erik Wijmans, which has an associated demo implementation of 2 of the techniques described therein.
Another good paper I found on web fingerprinting techniques which you should read if you're interested is Web-based Fingerprinting Techniques by Vítor Bernardo and Dulce Domingos.
The (in)security of device fingerprinting
The basis for device fingerprinting is collecting a variety of features from the client device which are indicative of the device/OS of the device, and are stable across browsers. Collect enough and the combination of these features of one user will very likely be unique among all users.
Most features useful for device fingerprinting can only be measured on the client (with JavaScript), and then need to be communicated back to the server, either raw or as a hash. Due to this, device fingerprinting as a security measure relies also on your ability to obfuscate the JS doing the fingerprinting and the corresponding network traffic communicating the fingerprint. If a user can figure out how the fingerprint is being collected and/or sent back to the server then they can spoof it to circumvent any protections you've put in place based on it.
Features that can be fingerprinted
Useful features to measure include (but are not limited to)

GPU rendering artefacts

anti-aliasing method
OpenGL driver varying interpolation
texture sampling

Installed fonts and writing systems
Text rendering minutiae

anti-aliasing
subpixel rendering
kerning, tracking and leading of particular fonts can indicate subtle variations due to different installed versions

In terms of low hanging fruit, there are Web APIs such as Navigator.hardwareConcurrency which expose details about the underlying hardware directly, however many browsers now disable or spoof this feature in order to avoid its use for fingerprinting.
The more features you collect the more solid your fingerprint, as long as they don't vary across browsers on the same device.
Conclusion
Ultimately, there is no be-all and end-all to device fingerprinting since it's a very complex topic with many potential approaches and a constant arms race with browser vendors trying to prevent fingerprinting techniques and developers trying to find new ones.
If you're looking for an out-of-box solution, there are currently a small handlful of open source and commercial browser and user fingerprinting services out there such as FingerprintJS (which is both). Though it does seem that many device fingerprinting solutions are not sold as standalone functionality but instead as a part of a fraud prevention system (such as SEON) or similar.
(The following is just opinion)
Overall it's my view that device fingerprinting is an iffy solution to locking out features, and a better solution is to make the signup process for an account as quick and easy as possible (though perhaps the free account could be used in combination with device or browser fingerprinting to temper abuse of the free trial system)

No Cookie / No IP Tracking a Visitor


Python loop programming , loop not running

Question: I'm new to Python and although I'm typing word for word from the tutorial I'm not getting the result I should be. Basically I'm expecting multiple answers from the range, but I only get one result.
>>> sum = 0
>>> for i in range (10): sum = sum + i
>>> print (sum)
45

Where am I going wrong?
Comment: I'm voting to close this question because it's so basic. If you want to learn Python, you would be better off reading a book. Now, if the tutorial you were following doesn't make sense, you should find another one and keep reading until you grasp the basic principles of Python. That way, once you get *really* stuck, you can come to us and we'll be happy to help you. :)
Comment: What exactly do you mean by `I'm expecting multiple answers from the range`. Are you trying to print all the number b/w `0-10` than you should do `for i in xrange(10): print i`
Comment: Why would you get more than one result? The question is?
Comment: You're going wrong by going against the grain of every tutorial I have ever seen and trying to invent your own coding style before you even know the basics.
Comment: The Alison tutorial I was following was here: http://alison.com/topic/learn/2971/36732/module-1-introduction-to-programming-with-python/for-loops-in-python
Answer: Note that using sum is a bad idea since sum() is already a Python built-in function. I use total here instead:
total = 0
for i in range(10):
    total = total + i  # same as total += i
    print(total)

gives:
0
1
3
6
10
15
21
28
36
45

Is this the output you expected/wanted?
In Python whitespace/indentation is crucial, so if you want a statement to be part of a function/loop/etc you need to indent it to the same level as the other statements in the block.
In contrast, your original code looks like this formatted more conventionally:
total = 0
for i in range(10):
    total = total + i  # same as total += i
print(total)

So you can see that print was only called once after the loop had finished executing. Indentation makes all the difference between the two versions.
Finally,  PEP8 - The Python Style Guide mentions that there ought to be no space between the function name and its arguments, so range(10) is preferred to range (10), print() to print (), etc
PEP 8 is good reading for any Python programmer.
Comment: Much appreciated, but even copying your code line for line its printing one single answer, 45 and not the rest of the range. The tutorial I was following was from Alison (http://alison.com/topic/learn/2971/36732/module-1-introduction-to-programming-with-python/for-loops-in-python) and they use "SUM" rather than total, and I still only get 45 and none of the other results. Very frustrating.
Comment: @endarandom ok, my first segment *will* work (I tested it and the output you see is what it generated). I wonder if when you copy/paste it you get some mix of tabs and blanks which is hard to spot. Since the code is very short, I would suggest you just type in those few lines. If you are executing them line by line, be sure you indent. Are you working under Windows? Are you using IDLE?
Comment: @endarandom Let me know how you make out -- this is fairly straight forward so we ought to get this working. I wonder about the tutorial though ... here's the official [Python Tutorial](http://docs.python.org/tutorial/) in case you want to check that out.
Answer: That is in fact the correct answer you should be expecting. Here's proof (hope you don't mind a little JS to prove my point)
Now, if you want the sum variable to be printed every iteration of the loop, you should modify your code to look like this:
sum = 0
for i in range (10):
    sum = sum + i
    print (sum)

Spacing is important in Python. Very important.
Answer: There's nothing wrong here. In each step you're adding the next number to sum, so in each step it's 0, 1, 3, 6, ...., 45. And then you print that answer out.
If you want every step printed out, you need to make sure print is inside the for block:
for i in range (10):
    sum = sum + i
    print (sum)

(watch out for indentation)
PS. Don't use sum as a variable name. It's already a global function, so by assigning sum=0 you're removing the old meaning - check sum(range(10)) in a new python shell


derivative of volterra operator with respect to f?

Question: What is the derivative of volterra operator with respect to $f$?(Also Higher Order Derivatives)
$(V f)(x)=\int_0^x f(t)dt.$
Answer: I'm going to assume that your function space is the space of continuous functions as is often the case with the Volterra operator. (If $L^2([0,1])$ is meant, just apply Cauchy-Schwarz to $f$ and $g$ where $g(x) = 1$ and you get that it is again bounded.) The Volterra operator is bounded on $C([0,1])$ since:
$$|Vf(x)| \le \int_0^x|f(t)|\,dt \le \left(\sup_{y\in[0,1]}|f(y)|\right)\int_0^x\,dt \le \|f\|\int_0^x\,dt \le \|f\|. $$
The last equality holds because $x \le 1$. For an operator $F$, the Frechet derivative exists if and only if there exists a bounded operator $A$ such that
$$F(x+h) = Fx + Ah + o(\|h\|).$$
Moreover, $A$ is said to be the Frechet derivative of $F$. If $F$ is itself bounded and linear, then we have that
$$F(x+h) = Fx + Fh.$$
In your case, the Volterra operator is bounded and linear. What then would you say about $V$ and its relationship to $A$?
Answer: For sufficiently well behaved functions(smooth and sufficiently differentiable for the expressions to make sense), the derivative is
$$f(x)-f(0)$$ and the higher derivatives
$$
\frac{d^n}{dx^n}(Vf(x) = \frac{d^{n-1}f}{dx^{n-1}}
$$
Comment: This isn't what is being asked. It's a variational-type question, not a standard calculus question.


Android : How to pass Integer Array between activities?

Question: I have two activities (Main & Sub) both contain list view to display images. I want to reuse the sub activity for displaying the images according to the cell click in the main activity (some thing like Restaurant Menu). So I have declared an array of integer arrays (Images in drawable folder) that I want to pass to sub activity and the subadapter
I tried below code, but I ended with the Int and Integer conflict.
main activity
public class AppsMenu extends AppCompatActivity {

    ListView appsmainlist;
    Integer[] images={R.drawable.res,R.drawable.clo,R.drawable.beu,R.drawable.col,R.drawable.tor,R.drawable.hot};
    Integer[][] subarray = {{R.drawable.res1,R.drawable.res2,R.drawable.res3,R.drawable.res4},{R.drawable.clo1,R.drawable.clo2,R.drawable.clo3,R.drawable.clo4}};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apps_menu);
        appsmainlist = (ListView) findViewById(R.id.appsmainlist);
        appsmenuadapter appsmenuadapter = new appsmenuadapter(this,images);
        appsmainlist.setAdapter(appsmenuadapter);
        appsmainlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    Intent intent = new Intent(AppsMenu.this,appsview.class);
                    intent.putExtra("subarray",subarray[i]);
                    startActivity(intent);

            }
        });
    }
}

sub Activity
ListView appsviewlist;
Integer [] appsviewarray;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_appsview);
    appsviewlist = (ListView) findViewById(R.id.appsviewlist);

// Error goes here
        appsviewarray = getIntent().getIntArrayExtra("subarray");
        appsviewadapter appsviewadapter = new appsviewadapter(this,appsviewarray);
    }

Adapter :
public class subadapter extends ArrayAdapter<Integer> {
...
}

Any help will be much appreciated.
Comment: change to primitive int instead of Integer
Comment: if i did so ,  the adapter will not except it !! adapter
Comment: create another array and then simply pass values if so, however you can also use adapter constructor for this instead of using generics
Comment: If this is the only functionality of your app, you can have the applications class hold the data, and have the activity retrieve it from the Application class. Another quick and dirty way is to use a static variable in the parent activity, and depending on the design of your app, it may be a safe choice.
Answer: Do Arrays keep resource id?
Did you think about to use Resource Array?
Something like this:
<integer-array name="resoruces">
        <item>@drawable/amex</item>
        <item>@drawable/mastercard</item>
        <item>@drawable/mastercard_white</item>
        <item>@drawable/visa</item>
    </integer-array>
In this way you can get them using context.
Comment: plz could u direct me to some example ?
Comment: you have subarray to keep array of resources id. So you can use a simple variable `int subarray = 2`, so you can pass it to other activity and you can get correct array.

`..`
`..`
`..`
 end you can make choice
`if(subarray==1) context.getIntegerArray(R.array.resource1) ...`

please check correct method name!
Comment: thanks man, works like charm
Comment: Ok! I'm happy to be useful. :)
Answer: Create Bundle and save is as parcelable array


Dimension of the secant variety $\sigma_2 (\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)$

Question: I am trying to compute the dimension of the secant variety $\sigma_2 (\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)$, for this I want to use the Terracini Lemma, that says that $$
T_p\sigma_2 (\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)= \langle T_x(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1),T_y(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)~\rangle.
$$
The expected dimension is $9$.
What I tried to do was to utilize the Segre embedding $$\sigma:\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1\rightarrow \mathbb P(\mathbb C^2\otimes \mathbb C^2\otimes \mathbb C^2\otimes \mathbb C^2),
$$
and now this space corresponds to the projetivization of rank 1 tensors in $\mathbb C^2\otimes \mathbb C^2\otimes \mathbb C^2\otimes \mathbb C^2$.
So a curve on this space is given by $\gamma:(a,b)\rightarrow \mathbb C^2\otimes \mathbb C^2\otimes \mathbb C^2\otimes \mathbb C^2$, $\gamma(t)=a(t)\otimes b(t)\otimes c(t)\otimes d(t)$. Computing the tangent space to $x=\gamma(0)=a\otimes b\otimes c\otimes d$, we have that $$
T_x(C(\sigma(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)))=\mathbb C^2\otimes b\otimes c\otimes d+\dots +a\otimes b \otimes c \otimes \mathbb C^2,
$$
So via Terracini I would have that $$T_p\sigma_2(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)=\langle T_x\sigma(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1), T_y\sigma(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)~\rangle
$$
I cannot see what I am missing. Any suggestion or tips?
Thanks in advance!
Answer: The four 2-dimensional summands of $T_x$ in your formula all contain the 1-dimensional space $a \otimes b \otimes c \otimes d$. Consequently, their sum is 5-dimensional.
Comment: But how do I guarantee that these two spaces $T_{x}\sigma(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)$ and $T_{y}\sigma(\mathbb P^1\times\mathbb P^1\times\mathbb P^1\times\mathbb P^1)$ are independent, i.e. that their dimension sum is 9?
Comment: For instance, compute in a basis.
Comment: Assume that $x=a\otimes b\otimes c\otimes d$ and $y=e\otimes f\otimes g\otimes h$, we can choose basis for each of the $\mathbb C^2$ st $a=b=c=d=e_1$ and because $p$ has rank $2$, $e=f=e_2$ without lost of generality. Then I can show that it has dimension 10 given that $g\neq \lambda e_1$ and $h\neq \mu e_1$. This means in a set of dimension one in the cone, i.e. the points $ p=e_1\otimes e_1 \otimes e_1\otimes e_1+\lambda e_2\otimes e_2\otimes e_1\otimes e_1$, it does not have the expected dimension, does this means that the dimension of the space is $9$ since at a general point it is $9$?


Pressure tank losing pressure

Question: My pressure tank is losing pressure. It cycles about once every hour if no water is used. It turns on at 30# and goes off at 50#.
The tank is less than a year old and looks in good condition. I just started to notice a few weeks ago, but recently more often. Not sure if it's getting worse or I'm just noticing it more since I'm now aware of it.
Here is what I've done so far:
First, I checked for leaks and cannot find any. There is some discolored dirt under the house that looks like it could be wet, but according to a plumber I spoke to, if I was losing 20# of pressure an hour, it would be around 5 gallons of water and easy to spot. I'm not sure if that calculation is correct, but I definitely would spot a leak if that much water was leaking out, even if I couldn't see exactly where a leak would be.
Next I closed the shutoff valve just after the tank/pressure valve/pressure switch and the pressure didn't drop at all. The plumber told me that since the pressure did not drop, the leak was not from the tank the the well and that it had to be someplace in the house. Again, I could not find any leaks.
Next I checked the air pressure in the tank, which should have been 28#, but it was at 36#. I adjusted the pressure accordingly and will see what happens from here. I was thinking that maybe with too much pressure it could cause water to leak slowly out of joints, which may be the discoloration I seen at certain spots under the house, although there is quite a bit of condensation.
Anyone know what else I can check? I have to be losing water someplace, unless there is a problem elsewhere, such as with the tank, etc., but I would think that with the shutoff valve off, if I had a tank problem, I still would have lost pressure.
Thanks ahead for any suggestions ...
Comment: I would double check for leaks again. Make sure you actually cover everything. Toilets, sinks, water softener, maybe a sump pump, etc.
Comment: Did you check the pressure in the tank while the system was pressurized?  Pressure must be taken off the system before checking tank pressure.  Nevertheless I do believe the leak is past the tank, by your description.
Comment: Yes, I first shut off the electric to the pump then drained the water from inside the house until it stopped and the pressure gauge dropped to zero. That is when I checked the pressure in the tank and it was too high. I then corrected the pressure to 2# below cut in pressure (28# / 30#).
Answer: Your tank is not loosing pressure you have a leak, a toilet, or faucet somewhere in the house is the most likely cause. I have seen copper pipe riddled with tiny pin holes That were so small it raised the humidity several months later ew found the first ones. In that home we had to replace most of the copper it may have been due to cheap pipe or high mineral content not sure as the house was all copper (no galvanized pipe issues) or dielectric unions needed.
Answer: This certainly sounds like a leak, particularly the "shut valve and problem stops" part.
If you don't have a puddle, it's probably leaking into a drain.
Toilets and water softeners top my list for common "leak to drain unnoticed" items. If your valving permits, start isolating parts of the system or individual fixtures. One (or more, but probably one) of them is leaking.
Correcting the air pressure in the tank is good, but has nothing to do with your leaky problem. I trust you did that with the water side drained/at 0 PSI?
Comment: Yes, the water side was drained to 0 PSI.

Pressure tank losing pressure


PHP MySQLI DateTime TimeStamps not pulling correctly

Question: OK! So, I have a page where I'm trying to pull a list of records from the database with dates < 30 days from expiration.
Now, the tricky part is - that the date format is in "yyyy-mm-dd hh:mm:ss"
Here's my code:
$Today = date("Y-m-d h:i:s");
if ($result = $mysqli->query("SELECT * FROM table WHERE DATEDIFF(ExpireDate, '$Today') < 30 ORDER BY `StartDate` ASC"))
{
    while($row = mysqli_fetch_array($result))
    {
        //show records
        //this type of query usually works when I'm NOT doing stuff with dates
    }
    mysqli_close($mysqli);
}

When I try to pull just records without any date/time conditions, it gives me the entire list of records, but when I want to see the those conditions, it doesn't display anything.
How do I show the records that are 30 days from expiration?
I SHOULD NOTE - that this is for internal use, only, and that there is no access from the outside world.
(I just wanted something simple for internal records keeping)
I've even tried this:
select * from table where some_date < curdate() - interval 30 day

and failed miserably... thoughts?
Comment: exactly 30 days? or anything under 30 days? for instance 16 days and 29 days in the same resultset?
Comment: Is the `expireDate` column a datetime column?
Comment: @iam-decoder "< = 30"
Answer: Just let the > & < operators take care of it
$Today = date("Y-m-d h:i:s");
$ExpiresFromToday= date("Y-m-d h:i:s", strtotime("+30 days"));
if ($result = $mysqli->query("SELECT * FROM `table` WHERE (`ExpireDate` < '$ExpiresFromToday' AND `ExpireDate` > '$Today') ORDER BY `StartDate` ASC")){
    while($row = mysqli_fetch_array($result)){
        //show records
    }
    mysqli_close($mysqli);
}

EDIT
to work with DATEDIFF tell mysql to treat the datetime string as a date:
$Today = date("Y-m-d h:i:s");
if ($result = $mysqli->query("SELECT * FROM `table` WHERE (DATEDIFF(DATE(`ExpireDate`), DATE('$Today')) < 30 AND `ExpireDate` >= '$Today') ORDER BY `StartDate` ASC")){
    while($row = mysqli_fetch_array($result)){
        //show records
    }
    mysqli_close($mysqli);
}

Comment: @iam-decoder BOTH of those suggestions worked out nicely!  Thanks!


LISTAGG 4000 Character Limit - Result of string concatenation is too long

Question:  select t.name, listagg(t.text)
   from user_source t
  group by t.name;

I am trying to execute the code above but since varchar2 is limited by 4000 chars it throws error. I tried to convert listagg to xml but I could not solve the

ORA-64451: Conversion of special character to escaped character failed.

error. I also tried the answers from other posts from various websites including stackoverflow.
I do not want to truncate the string, also I can't change MAX_STRING_SIZE parameter.
This example below throws ORA-64451 as well. I tried but could not solve the problem.
select rtrim(
             xmlagg(
                    xmlelement(e, to_clob(t.TEXT), '; ').extract('//text()')
                   ).GetClobVal(),
             ',')
  from user_source t;

Comment: You may also create your own aggregate function to operate on clobs
Comment: what is the data type of t.text?, size, also.
Comment: https://paulzipblog.wordpress.com/2019/04/23/a-solution-to-listaggs-4000-byte-limit/
Comment: @OldProgrammer unfortunately I couldn't solve the ORA-64451 error in your answer. but creating the my own aggregate function is worked like a charm!
Answer: The best solution I know is posted somewhere in the Internet... You could probably just google for it. It basically consist of few steps:

Creating a collection type to store each text value to concatenate

create or replace type string_array_t as table of VARCHAR2(4000);

Creating a PL/SQL function which takes string_array_t as parameter and returns concatenated text as CLOB:

create or replace function
  string_array2clob(
    p_string_array string_array_t
    ,p_delimiter varchar2 default ','
) RETURN CLOB IS
  v_string CLOB;
BEGIN
  -- inside is a loop over p_string_array to concatenate all elements
  --
  -- below is just a draft because in real you should use a while loop
  -- to handle sparse collection and you should put some checks to handle not initialized collection
  -- and other important cases
  -- furthermore it's better to create additional varchar2 variable as a buffer
  -- and convert that buffer to clob when it's full for a better performance
  for indx in p_string_array.first..p_string_array.last loop
    v_string := v_string || to_clob(p_string_array(indx) || p_delimiter);
  end loop;

  RETURN substr(v_string, 1, nvl(length(v_string),0) - nvl(length(p_delimiter),0));
END string_array2clob;
/

Aggregate query as usual but using cast and collect instead of listagg and at the end convert it to clob with function from step above:

select t.name, string_array2clob(cast(collect(t.text order by t.line) as string_array_t ), p_delimiter => chr(10)) as text
   from user_source t
  group by t.name;

If your query is not just an example of concept and really you're trying to get a source of some object in database, then you should read about dbms_metadata.get_ddl function. It's made for it.
Comment: @mertcan This is inefficient as it is going to store the data in memory twice. Once in the collection and then a second time when you concatenate the string in the function. It would be better to use a user-defined aggregation function which will only store the data once.
Comment: @mertcan - you need `SELECT_CATALOG_ROLE` or to be the owner of the object to see its definition. So log in as the owner or ask for a `SELECT_CATALOG_ROLE` privilege (it might not be accepted by DBA because it gives access in sensitive area).
Comment: The solution that you suggested is perfectly solved the problem. But I can't use the dbms_metadata.get_ddl function because I am not privileged user. It throws ORA-31603 error which I am not able to get rid of.
Comment: @MT0 thanks for the info. I will take a look at your "custom aggregation function" solution from [here.](https://stackoverflow.com/questions/42999390/limit-characters-returned-in-oracle-sql-query/43000237#43000237)
Comment: @MT0 does solution from [here](https://stackoverflow.com/questions/42999390/limit-characters-returned-in-oracle-sql-query/43000237#43000237) is what you have in mind? If yes, then I will take a look into it and benchmark it, because last time I used custom aggregate function it was soooo slow, I had to find another solution. I admit my query will use double size of memory but probably only for the limited number of rows (fetch size). I have never had problems with it and query time is usually more important for me.


Enable Wireless on Ubuntu on a mac pro 1.1

Question: How Do i get my wireless working, I just installed Ubuntu on my 2006 Mac Pro 1.1
Comment: In order to get help more information is needed.  Do you get an error or does the wireless card not actually show up?
Please help provide us more information around this so we can help you out more
Answer: I have spent a couple of weeks benchmarking some linux distros like:

Mint with Cinnamon desktop environnment
Ubuntu
The new Debian 7.4
Fedora
CentOS
EliveCD

And I have EliveCD installed because of the full support of the mac hardware (i.e. the WiFi chipset) and Elive works pretty fluently.