text:
Q: How to resolve the dependency and compile the Junit test classes using Gradle Bulid Tool I'm new to Gradle, currently i added a small java projects and executed well.
Correct me if my understanding since java is available we are able to complie the java project and executed well.
To test i have wirtten a test class with help of junit, but I couldn't not compile and not able to pull the dependency from the maven there was an issue.
When I checked with stacktrace option I find that the issue is java.net.UnknownHostException: repo1.maven.org when i tried to access through google it says the Directory browsing is disabled, perhaps it may only for pulling dependency.
Below I have given the steps followed along with the error details.
Kindly help me how to resolve or please suggest how to proceed or correct me if my understanding is wrong.
Compilation of Java Class

Compilation of Junit without stacktrace

Compilation of Junit with Stack Trace
D:\Public\NetbeansApp\ShopCart>gradle -s build
:compileJava
:processResources UP-TO-DATE
:classes
:jar UP-TO-DATE
:assemble UP-TO-DATE
:compileTestJava

FAILURE: Build failed with an exception.

* What went wrong:
Could not resolve all dependencies for configuration ':testCompile'.
> Could not resolve junit:junit:4.12.
  Required by:
      :ShopCart:unspecified
   > Could not GET 'https://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.pom'.
      > repo1.maven.org

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.artifacts.ResolveException: Could not resolve all dependencies for configuration ':testCompile'.
        at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration.rethrowFailure(DefaultLenientConfiguration.java:52)
        at org.gradle.api.internal.artifacts.ivyservice.DefaultResolvedConfiguration.rethrowFailure(DefaultResolvedConfiguration.java:36)
        at org.gradle.api.internal.artifacts.ivyservice.SelfResolvingDependencyResolver$FilesAggregatingResolvedConfiguration.rethrowFailure(SelfResol
vingDependencyResolver.java:110)
        at org.gradle.api.internal.artifacts.ivyservice.ErrorHandlingArtifactDependencyResolver$ErrorHandlingResolvedConfiguration.rethrowFailure(Erro
rHandlingArtifactDependencyResolver.java:180)
        at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getFiles(DefaultConfiguration.java:444)
        at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.getFiles(DefaultConfiguration.java:205)
        at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration_Decorated.getFiles(Unknown Source)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext$FileTreeConverter.convertInto(DefaultFileCollectionResolveCont
ext.java:191)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:103)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileTrees(DefaultFileCollectionResolveContext.java:75
)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext$FileTreeConverter.convertInto(DefaultFileCollectionResolveCont
ext.java:182)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:98)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileTrees(DefaultFileCollectionResolveContext.java:75
)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext$FileTreeConverter.convertInto(DefaultFileCollectionResolveCont
ext.java:182)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:98)
        at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileTrees(DefaultFileCollectionResolveContext.java:75
)
        at org.gradle.api.internal.file.CompositeFileCollection$1.resolve(CompositeFileCollection.java:88)
        at org.gradle.api.internal.file.CompositeFileCollection.getSourceCollections(CompositeFileCollection.java:143)
        at org.gradle.api.internal.file.CompositeFileTree.getSourceCollections(CompositeFileTree.java:30)
        at org.gradle.api.internal.file.CompositeFileCollection.getFiles(CompositeFileCollection.java:38)
        at org.gradle.api.internal.changedetection.state.DefaultFileCollectionSnapshotter.snapshot(DefaultFileCollectionSnapshotter.java:47)
        at org.gradle.api.internal.changedetection.rules.TaskUpToDateState.<init>(TaskUpToDateState.java:55)
        at org.gradle.api.internal.changedetection.changes.DefaultTaskArtifactStateRepository$TaskArtifactStateImpl.getStates(DefaultTaskArtifactState
Repository.java:126)
        at org.gradle.api.internal.changedetection.changes.DefaultTaskArtifactStateRepository$TaskArtifactStateImpl.isUpToDate(DefaultTaskArtifactStat
eRepository.java:69)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:305)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
        at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
        at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve junit:junit:4.12.
Required by:
    :ShopCart:unspecified
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.resolve(RepositoryChainDependencyResolver.java:81
)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainAdapter.resolve(RepositoryChainAdapter.java:69)
        at org.gradle.api.internal.artifacts.ivyservice.clientmodule.ClientModuleResolver.resolve(ClientModuleResolver.java:44)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$ModuleVersionResolveState.resolve(DependencyGraphBu
ilder.java:577)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$ModuleVersionResolveState.getMetaData(DependencyGra
phBuilder.java:587)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$DependencyEdge.calculateTargetConfigurations(Depend
encyGraphBuilder.java:272)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$DependencyEdge.attachToTargetConfigurations(Depende
ncyGraphBuilder.java:246)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder.traverseGraph(DependencyGraphBuilder.java:156)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder.resolveDependencyGraph(DependencyGraphBuilder.java:
94)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder.resolve(DependencyGraphBuilder.java:84)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultDependencyResolver$1.execute(DefaultDependencyResolver.java:122)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultDependencyResolver$1.execute(DefaultDependencyResolver.java:88)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:136)
        at org.gradle.api.internal.artifacts.ivyservice.DefaultIvyContextManager.withIvy(DefaultIvyContextManager.java:61)
        at org.gradle.api.internal.artifacts.ivyservice.DefaultIvyContextManager.withIvy(DefaultIvyContextManager.java:39)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultDependencyResolver.resolve(DefaultDependencyResolver.java:88)
        at org.gradle.api.internal.artifacts.ivyservice.CacheLockingArtifactDependencyResolver$1.run(CacheLockingArtifactDependencyResolver.java:42)
        at org.gradle.internal.Factories$1.create(Factories.java:22)
        at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAccess.java:187)
        at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAccess.java:175)
        at org.gradle.cache.internal.DefaultPersistentDirectoryStore.useCache(DefaultPersistentDirectoryStore.java:106)
        at org.gradle.cache.internal.DefaultCacheFactory$ReferenceTrackingCache.useCache(DefaultCacheFactory.java:187)
        at org.gradle.api.internal.artifacts.ivyservice.DefaultCacheLockingManager.useCache(DefaultCacheLockingManager.java:64)
        at org.gradle.api.internal.artifacts.ivyservice.CacheLockingArtifactDependencyResolver.resolve(CacheLockingArtifactDependencyResolver.java:40)

        at org.gradle.api.internal.artifacts.ivyservice.SelfResolvingDependencyResolver.resolve(SelfResolvingDependencyResolver.java:45)
        at org.gradle.api.internal.artifacts.ivyservice.ShortcircuitEmptyConfigsArtifactDependencyResolver.resolve(ShortcircuitEmptyConfigsArtifactDep
endencyResolver.java:55)
        at org.gradle.api.internal.artifacts.ivyservice.ErrorHandlingArtifactDependencyResolver.resolve(ErrorHandlingArtifactDependencyResolver.java:4
7)
        at org.gradle.api.internal.artifacts.ivyservice.DefaultConfigurationResolver.resolve(DefaultConfigurationResolver.java:46)
        at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.resolveNow(DefaultConfiguration.java:250)
        at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.getResolvedConfiguration(DefaultConfiguration.java:240)
        at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration_Decorated.getResolvedConfiguration(Unknown Source)
        at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getFiles(DefaultConfiguration.java:442)
        ... 61 more
Caused by: org.gradle.internal.resource.transport.http.HttpRequestException: Could not GET 'https://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12
.pom'.
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:80)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performRawGet(HttpClientHelper.java:66)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performGet(HttpClientHelper.java:70)
        at org.gradle.internal.resource.transport.http.HttpResourceAccessor.getResource(HttpResourceAccessor.java:53)
        at org.gradle.internal.resource.transport.http.HttpResourceAccessor.getResource(HttpResourceAccessor.java:36)
        at org.gradle.internal.resource.transfer.ProgressLoggingExternalResourceAccessor.getResource(ProgressLoggingExternalResourceAccessor.java:39)
        at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.getResource(DefaultCacheAwareExternalResourceAccessor.java:
72)
        at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadStaticResource(DefaultExternalResou
rceArtifactResolver.java:91)
        at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.resolveMetaDataArtifact(DefaultExternalReso
urceArtifactResolver.java:57)
        at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.parseMetaDataFromArtifact(ExternalResourceResolver.java:16
2)
        at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.resolveStaticDependency(ExternalResourceResolver.java:141)

        at org.gradle.api.internal.artifacts.repositories.resolver.MavenResolver.doResolveComponentMetaData(MavenResolver.java:82)
        at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$RemoteRepositoryAccess.resolveComponentMetaData(ExternalRe
sourceResolver.java:391)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CacheLockReleasingModuleComponentsRepository$LockReleasingRepositoryAccess$2.run(Ca
cheLockReleasingModuleComponentsRepository.java:65)
        at org.gradle.internal.Factories$1.create(Factories.java:22)
        at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:237)
        at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:308)
        at org.gradle.cache.internal.DefaultPersistentDirectoryStore.longRunningOperation(DefaultPersistentDirectoryStore.java:114)
        at org.gradle.cache.internal.DefaultCacheFactory$ReferenceTrackingCache.longRunningOperation(DefaultCacheFactory.java:179)
        at org.gradle.api.internal.artifacts.ivyservice.DefaultCacheLockingManager.longRunningOperation(DefaultCacheLockingManager.java:56)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CacheLockReleasingModuleComponentsRepository$LockReleasingRepositoryAccess.resolveC
omponentMetaData(CacheLockReleasingModuleComponentsRepository.java:63)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$ResolveAndCacheRepositoryAccess.resolveComponentMe
taData(CachingModuleComponentRepository.java:284)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.BaseModuleComponentRepositoryAccess.resolveComponentMetaData(BaseModuleComponentRep
ositoryAccess.java:38)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.memcache.InMemoryCachedModuleComponentRepository$CachedAccess.resolveComponentMetaD
ata(InMemoryCachedModuleComponentRepository.java:70)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ComponentMetaDataResolveState.process(ComponentMetaDataResolveState.java:70)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ComponentMetaDataResolveState.resolve(ComponentMetaDataResolveState.java:62)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.findBestMatch(RepositoryChainDependencyResolver.j
ava:114)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.findBestMatch(RepositoryChainDependencyResolver.j
ava:97)
        at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.resolve(RepositoryChainDependencyResolver.java:70
)
        ... 92 more
Caused by: java.net.UnknownHostException: repo1.maven.org
        at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:278)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:162)
        at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
        at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:640)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
        at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:137)
        at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:118)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performHttpRequest(HttpClientHelper.java:111)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.executeGetOrHead(HttpClientHelper.java:87)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:78)
        ... 120 more

BUILD FAILED

Total time: 14.846 secs

D:\Public\NetbeansApp\ShopCart>

App project structure with Test Class

Build script
apply plugin: 'java'

sourceCompatibility = '1.7'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

// NetBeans will automatically add "run" and "debug" tasks relying on the
// "mainClass" property. You may however define the property prior executing
// tasks by passing a "-PmainClass=<QUALIFIED_CLASS_NAME>" argument.
//
// Note however, that you may define your own "run" and "debug" task if you
// prefer. In this case NetBeans will not add these tasks but you may rely on
// your own implementation.
if (!hasProperty('mainClass')) {
    ext.mainClass = ''
}

jar {
    manifest {
        attributes 'Main-Class': 'com.gradle.shopcart.ShopCartApp'
    }
}

repositories {
    mavenCentral()
    // You may define additional repositories, or even remove "mavenCentral()".
    // Read more about repositories here:
    //   http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:repositories
}

dependencies {
    // TODO: Add dependencies here ...
    // You can read more about how to add dependency here:
    //   http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:how_to_declare_your_dependencies
    testCompile group: 'junit', name: 'junit', version: '4.12'

}

Error of Directory

A: As you commented you are trying to make it work behind a corporate proxy. You need to setup your Gradle properly, so it can load the dependencies with the proxy in mind. To do so you should follow the Gradle User Guide section 20.2. Accessing the web via a proxy.
Often this doesn't work either because the corporate proxy is a special proxy which required a special authentication mechanism (NTLM). Therefore you should check out the Cntlm Authentication Proxy. Cntlm is a local HTTP Proxy which is able to authentication against your corporate proxy and forward the traffic from the local proxy to corporate proxy.
Another solutions would be a own Maven Repository Server/Proxy/Cache like Artifactory or Nexus.

A: It indeed looks like your machine fail to download junit from maven. This assumption is based on the error you provided above:
`> Could not GET 'https://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.pom'`.

I checked and this file does exists so you should check whether your machine has access to it. If it is indeed not accessible from yours then you can follow the steps in Gradle doc here to set up a proxy for accessing the web.


text:
Q: Нахождение производной функции на Python 3 Я считываю func как строку, затем же мне надо найти производную функции, записанной в переменной func. Например: пусть func = "3*x**2 - 5*x", тогда итогом должна быть строка "6*x-5". Помогите пожалуйста с реализацией этого. Заранее спасибо.

A: Проще всего воспользоваться библиотекой sympy
import sympy

func = '3*x**2 - 5*x'
print(sympy.diff(func)) # 6*x - 5

Но она не идеальная, и с некоторыми уравнениями может не справиться.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Web.config System.net connectionManagement generic address In an ASP.NET project I am limiting the number of concurrent connections to an external web service using the following in my Web.config:
  <system.net>
    <connectionManagement>
      <add address="http://test.domain.com" maxconnection="1"/>
    </connectionManagement>
  </system.net>

The above works however I would like to limit all requests to *.domain.com using something like:
  <system.net>
    <connectionManagement>
      <add address="http://*.domain.com" maxconnection="1"/>
    </connectionManagement>
  </system.net>

This does not work however, any ideas?


text:
Q: Windows 8.0 not discovering CBPeripheral I have a sample iPhone application taken from https://github.com/KhaosT/CBPeripheralManager-Demo/tree/master/PeripheralModeTest. I am advertising my peripheral service as follows.
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{
    NSLog(@"didAddService start");
    NSLog(@"Added");
    NSDictionary *advertisingData = @{CBAdvertisementDataLocalNameKey : @"BTService", CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:@"EBA38950-0D9B-4DBA-B0DF-BC7196DD44FC"]]};

    [peripheral startAdvertising:advertisingData];
    NSLog(@"didAddService end");
}

I have taken windows app code sample from https://code.msdn.microsoft.com/windowsapps/Bluetooth-Generic-5a99ef95. I replaced the Heart rate UUID with the service UUID. But on running it, it is unable to find the service mentioned.
void Scenario1_DeviceEvents::RunButton_Click(Object ^ /* sender */, RoutedEventArgs ^ /* e */)
{
    RunButton->IsEnabled = false;

    Vector<String^>^ additionalProperties = ref new Vector<String^>;
    additionalProperties->Append("System.Devices.ContainerId");

    Platform::Guid lol = Platform::Guid::Guid(0xEBA38950, 0x0D9B, 0x4DBA, 0xB0, 0xDF, 0xBC, 0x71, 0x96, 0xDD, 0x44, 0xFC);
    create_task(DeviceInformation::FindAllAsync(

        GattDeviceService::GetDeviceSelectorFromUuid(lol), additionalProperties))
        .then([this](Windows::Devices::Enumeration::DeviceInformationCollection^ devices)
    {
        this->devices = devices;

        if (devices->Size > 0)
        {
            Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, devices]()
            {
                DevicesListBox->Items->Clear();

                auto serviceNames = ref new Vector<String^>();

                for_each(begin(devices), end(devices), [=](DeviceInformation^ device)
                {
                    serviceNames->Append(device->Name);
                });

                cvs->Source = serviceNames;
                DevicesListBox->Visibility = Windows::UI::Xaml::Visibility::Visible;
            }));
        }
        else
        {
            MainPage::Current->NotifyUser(L"Could not find any Heart Rate devices. Please make sure your " +
                "device is paired and powered on!",
                NotifyType::StatusMessage);
        }

        Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
        {
            RunButton->IsEnabled = true;
        }));
    }).then([](task<void> finalTask)
    {
        try
        {
            // Capture any errors and exceptions that occured during device discovery
            finalTask.get();
        }
        catch (COMException^ e)
        {
            MainPage::Current->NotifyUser("Error: " + e->Message, NotifyType::ErrorMessage);
        }
    });
}

I tried pairing the device with windows. But still no luck. It has been so frustating, no proper support for discovering devices.


text:
Q: Is there an easy way to use JSP with RESTeasy? I developed a restful service to deliver xml and json using the RESTeasy framework.
Now I would like to develop a small web-frontent on top of that service but I wasn't able to find a way to use JSP-files in this framework directly without integrating Spring or another similar framework.
Is there an easy way to work with JSP-files (like rendering the jsp and delivering the resulting HTML to a web browser) in RESTeasy directly?
Maybe you know a tutorial which I couldn't find yet (every tutorial I could find so far is about json/xml or strings?


text:
Q: Maven pom.xml - build modules + self build I have the next project structure:
app
module1
module2
...
moduleN
parent-pom

Project app contains only properties files and JasperReports's reports templates. Pom.xml of app:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>my-group</groupId>
    <artifactId>parent-pom</artifactId>
    <version>1.0.0</version>
    <relativePath>../parent-pom</relativePath>
</parent>

<artifactId>app</artifactId>
<version>${app-version}</version>
<packaging>pom</packaging>
<modules>
    <module>../module1</module>
    <module>../module2</module>
    ...
    <module>../moduleN</module>
</modules>

I want to add jasperreports-maven-plugin for project app. I've tried next code (before <modules> section), but it doesn't work (self build wasn't called):
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jasperreports-maven-plugin</artifactId>
            <configuration>
                <sourceDirectory>${basedir}/config/templates</sourceDirectory>
                <outputDirectory>${basedir}/config/templates</outputDirectory>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile-reports</goal>
                    </goals>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>net.sf.jasperreports</groupId>
                    <artifactId>jasperreports</artifactId>
                    <version>${jasperreports.version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

Is it possible to add self build to pom with modules?

A: The app project packaging is set to pom - so it can't have any other artifacts.  You will need to move the jasper reports to one of the other modules or a separate module.


text:
Q: when preprocessor directives are called by a function, the output differs. why? This question was asked in an interview and i completely had no idea about how the output differs. Following is the question
#define a 10
void foo();
int main()
{
   printf("%d..",a);
   foo();
   printf("%d",a);
}
void foo()
{
   #undef a
   #define a 50
}

this gives me 10..10 as output while.,
#define a 10
void foo()
{
   #undef a
   #define a 50
}
int main()
{
   printf("%d..",a);
   foo();
   printf("%d",a);
}

this gives me 50..50 as the output.
please explain. thank you

A: This happens because, preprocessing substitution happens even before the actual compilation, it does not take place in run-time.
The value (or definition) of a #define directive is valid as per the written code syntax, not as per the calling convention.
So, in the first case
#define a 10                 // a is defined here
void foo();
int main()
{
   printf("%d..",a);         // a == 10, substitution happens
   foo();                    //nothing useful here
   printf("%d",a);           // a == 10, substitution happens
}
void foo()
{
   #undef a                 // a vanished
   #define a 50             // a is redefined as 50
}                           // a will be substituted to 50 hereon, is used

whereas, in second case
#define a 10               // a is defined here
void foo()
{
   #undef a                // a vanished
   #define a 50            // a is redefined as 50
}                          // a will be substituted to 50 hereon, is used
int main()
{
   printf("%d..",a);      // a == 50, substitution happens
   foo();                  // nothing useful here
   printf("%d",a);        // a == 50, substitution happens
}

A: Preprocessor is run before the code is compiled in the order in which preprocessor directives appear in the file and not in the order of functions defined in the file.


text:
Q: html5 canvas clear scale function Iam searching for a solution, in html5-canvas how to clear the scale function?
If I scaled a shape, for next shape it should not scale or scale less
thank you
  <!DOCTYPE html>
       <html>
       <body>

     <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
       Your browser does not support the HTML5 canvas tag.</canvas>

       <script>

      var c=document.getElementById("myCanvas");
      var ctx=c.getContext("2d");

      // first draw
      ctx.strokeRect(5,5,25,15);

      //scale
      ctx.scale(2,2);
      ctx.strokeRect(5,5,25,15);

      // how to clear scale this ? It should draw like first
      ctx.scale(-1,-1); // this is not working
      ctx.strokeRect(5,5,25,15);

    </script>

   </body>
</html>

A: Since you scaled by 2, you can un-scale by 1/2
 // first draw
  ctx.strokeRect(5,5,25,15);

  //scale
  ctx.scale(2,2);
  ctx.strokeRect(5,5,25,15);

  // un-scale
  ctx.scale(.5,.5); // unscale by 1/2
  ctx.strokeRect(5,5,25,15);

Another example, if you had scaled by 3 you would unscale by 1/3
// scale

ctx.scale(3,3);

// unscale

ctx.scale(1/3,1/3);

A: I think the most convenient solution for your problem is to save the context and then restore it after you are done drawing the stuff you want to be scaled.
// Draw the first rect with size 20x20
ctx.strokeRect(50,75,20,20);

// Save context
ctx.save();

// Double the scale
ctx.scale(2, 2);

// Draw the second rect with the same size
ctx.strokeRect(65,35,20,20);

// Restore context
ctx.restore();

// Draw the last rect, still with size 20x20
ctx.strokeRect(220,75,20,20);

Example: http://jsfiddle.net/8tXVL/


text:
Q: Стеганография LSB не корректное отображение русских символов Решил разобраться со стеганографией, очень заинтересовал эта тема, нашёл реализацию алгоритма на C# собственно сама реализация
начал разбираться, ввёл текст на английском и попробовал его скрыть в изображении, всё получилось и я смог извлечь этот текст из изображения. Я решил, что проблема в кодировке и решил загружать текст из файла подобной сточкой text = File.ReadAllText(open_dialog.FileName, Encoding.GetEncoding(1251));
но это не помогло. Собственно и решил обратится сюда.

A: Проблема у кода в том, что он считает char восьмибитным.
Например, код
// check if new 8 bits has been processed
if (pixelElementIndex % 8 == 0)

при записи и
// if 8 bits has been added,
// then add the current character to the result text
if (colorUnitIndex % 8 == 0)

при чтении портят старшие биты.

Символы в .NET 16-битные вне зависимости от того, какую кодировку вы указываете при чтении. Кодировка играет роль лишь в определении того, какой символ прочитан из файла, а внутреннее представление всегда одно и то же.


text:
Q: git push heroku master is giving me an error I have a react app i'm trying to deploy to heroku, However when I run git push heroku master, I'm receiving the error below. How can this be fixed please?
To https://git.heroku.com/getsoundtracks.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/getsoundtracks.git'

A: I am not familiar with Heroku, but this error basically means that you are trying to push directly to a protected branch - master.
This is quite normal actually (even the default IIRC) for the master branch. You will probably need to do one of the following:

*

*create a "development" branch and push that to the remote and then merge that into master in Heroku (merge request or such?)

*Edit the master branch in Heroku and set it to unprotected


text:
Q: How can I force a period at the end of a note in a tufte-book citation? In tufte-book, citations are rendered as sidenotes, which is great. However, the note field of a bibtex citation is not processed correctly in the sidenote:
.tex file:
\documentclass{tufte-book}

\begin{document}
Some text, with a citation~\cite{testcite}.

\bibliographystyle{plain}
\bibliography{tmpdoc}
\end{document}

.bib file:
@book{testcite,
  title={The},
  author={Book},
  year={1998},
  publisher={Pub},
  edition={second},
  note={Part 2.}
}

Truncated output with tufte-book as the document class:

Output with article as the document class:

A: tufte-book uses the package bibentry which always deletes the final period.  You have two options:

*

*Protect the final dot in the note field:
@book{testcite,
 title={The},
 author={Book},
 year={1998},
 publisher={Pub},
 edition={second},
 note={Part 2{.}}
}

*Make bibentry to always keep the final period by redefining \BR@nodot (the command that strips the dot).  Add to the preamble:
\makeatletter
\def\BR@nodot#1.\relax#2\relax{#1.}
\makeatother


text:
Q: VS Code + React + JSX + Components props intellisense is not working I have a project using .JS and it works perfectly for React Components, but with my other project that I'm using JSX as file extension, it's not working.
I found some similar issues, but I couldn't fix it doing what I supposed to do and I'm still with the problem.
When I press F12 to go to the definition of the component, I get this message:

And when I start to write a prop, the intellisense doesn't show the prop definition. Not even the prop name. And it works with .JS files like this:

A: For some reason react types choose when they want to be installed
Run
npm install @types/react

And you should be fine


text:
Q: If consumer grade hard drives and parts are so bad, how does Backblaze do it? In case you don't know, Backblaze is somewhat famous for making custom ginormous boxes of disks made entirely out of consumer grade parts for their file hosting business. Their newest version holds 135 terabytes for $7,384, which is significantly cheaper than any existing "enterprise" solution.
For reference, the "pod" holds 45 disks. If their 2.0 pod uses the same basic configuration as the 1.0 pod, every 15 disks is in its own RAID6 array with 2 pairity disks out of the 15. In total this leaves 87% usable space. Failure rate isn't too much of a problem; over their total 9,000+ hard drives, an average of 10 per week fail, or 5%. The newer 2.0 pods see less than 1% failure rate
However I thought that running consumer hardware as a server was bad. Especially on ServerFault, people get on to them like a pack of angry wolves saying "Don't use consumer hardware, use server hardware!" There was a giant answer I saw a while ago that talked about all the horrible things that result from using Consumer SATA disks (Failure rate, speed, RPMs, Bad Sector in Raid issues, not being "certified" etc). Here's another one. Sometimes they are called "toys". Mark wouldn't even put a consumer grade server ON the server's network.
With all the horrible issues with consumer hardware, how is Backblaze able to run their entire business from them? How was the Sysadmin able to sleep at night? Was all the hype about enterprise drives just fear mongering or blown out of proportion?
More importantly, why can't I or someone else do something similar? 135 terabytes seems like a lot of data for such a cheap price. Even two pods mirroring each other seems like it would be cheaper than the equivalent "enterprise" solution, and in some cases it might be more redundant since its essentially RAID-60 over two separate machines.
Thoughts?

A: Backblaze has a business model that allows them to do this. They need gobs of storage space (though it doesn't have to be particularly fast) and they need it cheaply. It's worth it for them to dote on storage because they need so much and they can scale their production to handle having sufficient spare parts and support labor on-site.
If your company's business model allows you the convenience of building your own hardware (and the curse of being the sole support provider when you have failures) then, by all means, go for it. For most companies it's cheaper to purchase "enterprise" solutions because of the technical support entitlement, compatibility testing and vendor certification, and warranty support that comes with an "enterprise" solution.
You're not going to get the performance out of "consumer" disks that you will with "enterprise" disks. If you're talking about large "near-line" storage needs that's one thing, but "enterprise" disks (magnetic or SSD) are necessary if you want to scale to large numbers of transactions (I/O operations per second) on an array of disks. SATA disks just aren't as fast as SAS disks.
If you have a business that needs massive amounts of raw storage and can handle being your own support provider and the expense of "rolling your own" then using the Backblaze designs might well work for you. I think you'll have to scale fairly large to see benefits as compared to just buying something off-the-shelf in terms of total cost of ownership and long-term reliability.

A: *

*lots of redundancy

*

*IMO Consumer grade hardware is not inherently evil, but you should certainly understand what you are getting and plan properly for their failure and replacement.  There is a big difference between the really low-end consumer gear, and the high-end server gear, there is also some stuff in the middle that could be perfectly fine in some production settings.

*The are running a backup business

*

*Which most likely means lots of nice long sequential writes, followed by lots of time where the drive is doing absolutely nothing, combined with the very rare read for recovery.  This is certainly a drastically different usage pattern then you would see for an Mail/Database server.

*Enterprise equipment is often focused on IOPS

*

*Low end-gear is almost certainly cheaper, but people buying enterprise solutions are frequently buying IOPS, not capacity.  The IOPS difference between a cheap device and a enterprise gear can be huge.


text:
Q: How to keep a TABLE "here defnitely" in R markdown I want to keep a table created in an rmarkdown document that outputs to pdf locked in place and not flexibly fitting between text.
For example, my code is:
---
title: "Rest"
author: "Dowdy"
date: "3/23/2019"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
library(stargazer)
library(data.table)
```

Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo.

Hello friend.

\begin{center}
```{r star, results='asis',echo=F,eval=T, message=FALSE}

star = capture.output(stargazer(data.table(cars)[1:15],digits=3,type = "latex",summary=F,digits.extra = 2,header = F))

star = gsub("& \\$([0-9]+)\\$", "& \\$ 0.000 \\$", star)

cat(star)

```
\end{center}

Welcome to my world of toys.  Welcome to my world of toys.Welcome to my world of toys.Welcome to my world of toys.Welcome to my world of toys.Welcome to my world of toys.Welcome to my world of toys.Welcome to my world of toys.Welcome to my world of toys.Welcome to my world of toys.
Welcome to my world of toys.
Welcome to my world of toys. gs I am testing heloo.
Of all the things I am testing heloo. Of all the things I am testing heloo. Of all the things I am testing heloo.

Of all the things I am testing heloo. Of all the things I am testing heloo.

1. Test hi hihhihihih

2. why is this hiiii

3. why test test test

4. test test test

Unfortunately, the output is this:

I do not want the image to split up my numbered list and text this way.  I want the order of the text and image to be exactly as I typed it in the rmarkdown document. Specifically, that numbered list and the paragraph about toys should appear all after the table as it is typed in the markdown.
For figures, this question tried to do what I want to do I believe.  Of course, I am asking this for tables instead of figures, so the solution does not help me.

A: As suggested in the link you provided, include
header-includes:
   - \usepackage{float}

in the YAML header. Then, and according to the the stargazer manual, you can set the float permission with argument table.placement = "H", which

Places the float at precisely the location in the LaTeX code.

Ref: LaTeX/Floats, Figures and Captions
In your case, it would be
star = capture.output(stargazer(data.table(cars)[1:15], digits=3,
                      type = "latex",summary=F,digits.extra = 2,
                      header = F, table.placement = "H"))

A: I have to check this when I update my tex, and I might need a little more information on what you want exactly, but if you want to have the table in the middle of the text, all you need to do is remove the \begin{center} and \end{center}. R chunks are really used as copy paste wherever you want, even working as web links if you want. Additionally, you can use kable() from knitr for tables and this sometimes helps sometimes makes things worse. I'll check back later when I have better internet.


text:
Q: How to bypass proxy in iOS programmatically? These are my steps
Network is available now for the Wifi.
Open system WiFi settings
Select manual proxy settings
Configure invalid parameters
Open browser and make sure that internet is not available
Start the app and make sure there is no internet
Is there any way that programmatically from inside the app, I can bypass those proxy settings so that I can connect to the internet?

A: Encounter your problem in 2018, after some time digging in the document found the key kCFStreamPropertyProxyLocalBypass for setting in the proxy dictionary.
fyi:https://developer.apple.com/documentation/cfnetwork/kcfstreampropertyproxylocalbypass
Objective-C
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

NSDictionary *proxyDict = @{
                        @"HTTPEnable"  : [NSNumber numberWithInt:1],
                        (NSString *)kCFStreamPropertyProxyLocalBypass  : @"10.26.*.*",
                        @"HTTPSEnable" : [NSNumber numberWithInt:1],
                       (NSString *)kCFStreamPropertyProxyLocalBypass  : @"10.26.*.*"
                          };
sessionConfig.connectionProxyDictionary = proxyDict;

Swift
let sessionConfig = URLSessionConfiguration.default
var proxyDict = [AnyHashable : Any]()
proxyDict[kCFStreamPropertyProxyLocalBypass as String] = "10.26.*.*"
sessionConfig.connectionProxyDictionary = proxyDict
let session = URLSession.init(configuration: config, delegate: nil, delegateQueue: OperationQueue.current)

A: You probably want to use CFHTTPStream, which by default does not automatically use the proxy settings.
For more information, read the CFNetwork Programming Guide.


text:
Q: Codeception, gherkin test, how organize my code? I followed the official Codeception guide (from their website of course) and I created a simple test written in Gherkin.
With the command codecept gherkin:snippets command, I printed all methods I must implement. Then I copied these methods to the tests/_support/AcceptanceTester.php file.
My question is: today, it's a sample test, but tomorrow, if I must create a lot of acceptance tests, how do I organize my code ?
I suppose I must write each main scenario in several PHP files. But, where I can save these files? How do I link these files together?
Let's say I must create two big scenarios of acceptance tests. The Scenario A can be run alone, but the Scenario B must be run after the Scenario A.
Where do I need to create the files A and B? And, how can I "say" to Codeception I can run the Scenario B only after the A has been executed?
Sorry for my English, I hope my questions are clear.

A: You can tell Codeception that a scenario depends on something else by using @depends followed by the test signature. According to the documentation:

And what is more interesting, you can make tests to depend on feature
  scenarios. Let's say we have login.feature file with "Log regular
  user" scenario in it. In this case you can specify that every test
  which requires login to pass to depend on "Log regular user" scenario:
@depends login:Log regular user
Inside @depends block you should use test signature. Execute your
  feature with dry-run to see signatures for all scenarios in it. By
  marking tests with @depends you ensure that this test won't be
  executed before the test it depends on.


text:
Q: Off-diagonal terms of the Husimi $Q$ function? The Husimi $Q$ function of a quantum state $\rho $ is defined as
$ Q (\alpha)=\langle \alpha \vert \rho \vert \alpha \rangle $, where $\alpha = (x, p) $ is a phase space coordinate and $\vert \alpha \rangle$ is a coherent state.
Is the off-diagonal generalization
$ Q (\alpha, \beta)=\langle \alpha \vert \rho \vert \beta \rangle $
used for anything? Does it have a name?
This is an interesting object because it essentially measures coherence (or decoherence) in the overcomplete basis of wavepackets .

A: I finally found some prior art.  This object has been introduced as the "Husimi Matrix" by Harriman

"Some properties of the Husimi function"     Harriman, John E., The
  Journal of Chemical Physics, 88, 6399-6408 (1988),
http://dx.doi.org/10.1063/1.454477

and briefly referred to by Morrison and Parr

"Approximate density matrices and Husimi functions using the maximum entropy formulation with constraints"
  Morrison, Robert C. and Parr, Robert G., International Journal of Quantum Chemistry, 39: 823–837
  http://dx.doi.org/10.1002/qua.560390607

The treatment was fairly basic.  From what I can tell, Harriman primarily introduced the Husimi matrix to highlight an analogy with density matrices (since you can use it as the kernel of an integral operator).  Morrison and Parr use it for something related to calculating a density matrix as a maximum entropy Husimi function, but I don't really understand.
I do not believe anyone has explored the relationship to decoherence.
EDIT: For an off-diagonal generalization of the Glauber P function, see the "Positive P function", developed by Drummond and Gardiner.


text:
Q: Do I have a way to avoid re-creating lots of String objects? My project uses Javascript and Java (Android) for the client and Java for the backend.
When I started working on my project, I stored dates as days from epoch (long) and all was good. I then found out that my project doesn't work well with timezones. Suddenly dates were +1 -1 days off. Depending on the client's location in the world.
After a short investigation, I saw that the foolproof way to avoid it was to store the dates as String yyyy-MM-ddT00:00 so when using the Javascript's new Date(dateStr), it creates it correctly and all was good. Ofcourse I could store the dates as yyyy-MM-dd and just send it to the client as yyyy-MM-ddT00:00 but that won't solve the question I have.
After that, I was wondering whether Java (backend) is handled correctly. I use LocalDate when I want to "play" with dates and LocalDate.parse doesn't like yyyy-MM-ddT00:00 format, instead it works with yyyy-MM-dd so whenever I needed dates, I did LocalDate.parse(dateStr.substring(0,10)). LocalDateTime does work with yyyy-MM-ddT00:00 but I don't need the time part and it had its own issues, which I don't remember what they were at the moment.
So now I have a lot of String manipulation (inside loops) that actually creates more String objects. One can say it's not that much of a stress and I shouldn't pay attention to that but I want to make sure I'm not missing something and maybe there's another way (maybe silly enough that I've missed) to overcome this.
Thanks
Update: The events are stored from a different source and only the date itself is important so if an event happened on 2020-06-17, this is the date all users should see, no matter where they are.
I'm using new Date(dateStr) in Javascript. If dateStr is 2020-06-17, the date object uses the client's timezone and the date might be +-1 depending on the client's timezone. If dateStr is 2020-06-17T00:00 then the date object is created as expected no matter where the client is located.
Assuming the above, which I hope is clearer now, creating String objects over and over again is a memory stress that I should consider or is it something Java handles with no problem and I shouldn't worry about this?
My question was closed and I was told to edit it to be more focused. After editing my question, how can I re-open my question to answers?

A: As you have discovered, storing dates in terms of days since some epoch only works if everyone who uses your system is using the same time zone. If two different users in different time zones have a different idea about the date on which some event occurred (e.g., the person in New York says that the system crashed on Sunday night, but the the person in Hong Kong says it crashed on Monday morning), then you have to store the time zone in which the event occurred in order to show the date of that event accurately.
But if that's the situation you're in, why not just store the time zone along with the date? There's no compelling reason to combine the date and timezone into a string.
When you parse a ISO-formatted timestamp into a LocalDate using only the first 10 characters, be aware that you're losing the time zone information. Implicitly the LocalDate that you get is in the time zone of the original timestamp. So if the original timestamp is New York time, and you take the date part and add 1 day, then you'll get the next day in the New York time zone. But if you then take the date from a second timestamp, you can't compare it to the date you got from the first timestamp, in terms of determining if it represents the "same day." You can only test for "same day" if both dates are implicitly in the same time zone.
UPDATE
After reading your additional comments, I realize that what's happening is this. You have a date stored in your database, like 2020-06-15. You send that to the UI as the string '2020-06-15' and then do new Date('2020-06-15') and then you're surprised when you render the date in the UI and get June 14!
This is the transformation that happens:

*

*The string '2016-06-15' gets parsed into a JavaScript Date representing midnight UTC on the June 15.

*When you render the date, it gets converted into a string using the browser's local time zone, which (if you're in the United States) will give you June 14, because at midnight UTC on June 15 it's still June 14 in all time zones west of Greenwich.

You discovered that if you make the string "2020-06-15T00:00" that it works, because now JavaScript uses the browser's local time zone to parse the string. In other words, this string means midnight local time, not UTC, on June 15. So now the sequence is:

*

*'2020-06-15T00:00' gets parsed using the local time zone and becomes June 15 4:00AM UTC.

*When you render the date, it gets converted back to local time and is rendered as June 15.

The easiest way to avoid all this messiness is just to send the regular date string '2020-06-15' to the UI and render it using DateTimeFormat, specifying the time zone as UTC:
new Intl.DateTimeFormat('en-US', {timeZone: 'UTC'}).format(d)

Since dates in JavaScript are always UTC, and you're asking DateTimeFormat to output the date in UTC, no date shift occurs.
You could also use the Date methods getUTCFullYear, getUTCMonth, etc. to get the date components and format them however you like.
Once you're no longer sending dates back and forth with "T00:00" appended, you can just use LocalDate on the Java side.
Don't spend even a second worrying about the time required to manipulate strings. Think about the incredible amount of string manipulation that is necessary to build even a simple web page. A few more strings here and there isn't going to make a difference.


text:
Q: starting wiremock as part of local development I have a hello world micronaut application which starts locally and makes some calls to an external service. What I want to do is start wiremock as part of the local build on my machine, so that wiremock can intercept the external calls and send responses
Im not sure how to do this in micronaut, in spring id create a "dev" config that would start wiremock... but not sure how that works in micronaut..
any help?

A: Have you tried instructions provided in https://github.com/tomakehurst/wiremock-jdk8-examples/ ?
Add dependency:
       test "com.github.tomakehurst:wiremock-jre8-standalone:2.33.2"
and than use it from your code e.g.:
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.matching.MatchResult;
import org.junit.Rule;
import org.junit.Test;

import java.net.HttpURLConnection;
import java.net.URL;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.requestMadeFor;
import static com.github.tomakehurst.wiremock.client.WireMock.requestMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class LambdaRequestMatcherTest {

    @Rule
    public WireMockRule wm = new WireMockRule(wireMockConfig().dynamicPort());

    @Test
    public void lambdaStubMatcher() throws Exception {
        wm.stubFor(requestMatching(
                request -> MatchResult.of(request.getUrl().contains("magic"))
            ).willReturn(aResponse()));

        URL url = new URL("http://localhost:" + wm.port() + "/the-magic-path");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        assertThat(connection.getResponseCode(), is(200));
    }

    @Test
    public void lambdaVerification() {
        wm.verify(requestMadeFor(request ->
            MatchResult.of(!request.header("My-Header").values().isEmpty()))
        );
    }

}


text:
Q: different values in same column, output in different columns Currently I am working on a project, which has to do with Formula 1.
That's my structure of the table for results.
CREATE TABLE IF NOT EXISTS `races_results` (
  `resultid` int(11) NOT NULL,
  `seasonyear` int(4) NOT NULL,
  `trackid` tinyint(2) NOT NULL,
  `raceid` int(2) NOT NULL,
  `session` tinyint(1) NOT NULL,
  `q` int(11) NOT NULL,
  `place` tinyint(2) NOT NULL,
  `driverid` int(2) NOT NULL,
  `teamid` int(2) NOT NULL,
  `time` int(11) NOT NULL,
  `laps` int(2) NOT NULL,
  `status` varchar(3) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

My big problem is that I don't get the result in output as I want.
SELECT place, driverid, teamid, if(q=1, time, '') as time1, if(q=2, time, '') as time2, if(q=3, time, '') as time3
FROM `races_results`
WHERE `seasonyear` = 2015 AND `raceid` = 3 AND `session` = 2 AND `q` IN (1,2,3)
GROUP BY driverid
ORDER BY CASE WHEN q = 3 THEN place >= 1 AND place <= 10 END ASC, CASE WHEN q = 2 THEN place >= 11 AND place <= 16 END ASC, CASE WHEN q = 1 THEN place >= 17 AND place <= 22 END ASC

My target is that I want that the all times of a driver will show side by side and after this should be ordered by the participants of the sections.
After this I should have an output like this http://www.formula1.com/content/fom-website/en/championship/results/2015-race-results/2015-japan-results/qualifying.html

A: From your question I understand that the table races_results has a line for each result, so the times of the different qualifications are on different lines. To get these on one line you can do a join of the same table:
SELECT place, driverid, teamid, r1.time as time1, r2.time as time2, r3.time as time3
FROM races_results r1 LEFT JOIN races_results r2 on (r1.driverid=r2.driverid and r1.raceid=r2.raceid)
LEFT JOIN races_results r3 on (r1.driverid=r3.driverid and r1.raceid=r3.raceid)
WHERE r1.q=1 AND r2.q=2 AND r3.q=3 AND
`seasonyear` = 2015 AND `raceid` = 3 AND `session` = 2
GROUP BY driverid
ORDER BY place;

I assume:

*

*that there is always a result for q=1;

*the driverid and raceid are unique for a race on a specific year for a driver;

*you want to order by place.


text:
Q: avada wordpress theme woocommerce site google page speed score 0/100 https://i.stack.imgur.com/8SUsD.png
All required things did for site optimization but page speed score not increasing from 0.Please help. (See Above image)

A: I think you have too much images on your site, the loading time is 5 second and the weight is 21mb.
Try to install a plugin to load image on scrolling action..
If you try on pagespeed a url like https://orange-eyewear.co.uk/about-us/ it works.


text:
Q: Recovering Deleted Files after Emptying Trash on OS X Lion I moved a complete folder to the trash, then I emptied my trash.
How do I recover those deleted files which I emptied from the trash on OS X Lion?
By searching with Google, I have found a few tools which do this. Either they cost a fortune or they are lousy. Is there a manual and generic way to recover these files?

A: You can try to use an Ubuntu live cd and a tool like PhotoRec to recover most of the files. The only problem is that it will recover ALL of the files that it can from a partition based on specific file types.
I recently used this tool on a dying drive with SMART errors, corrupt sectors, and a corrupted MBR and yet it worked like magic.
It might be overkill for your needs given that you only need to recover a folder, but if you really need that data, give it a shot.
See here: http://www.howtogeek.com/howto/15761/recover-data-like-a-forensics-expert-using-an-ubuntu-live-cd/


text:
Q: VBA Application/object defined error when outputting array to .Cell declared range I have an issue where I get the 'application-defined or object defined error' when trying to output an array into a range.
 Worksheets("Log").Range(.Cells(MnthCount + 4, 6), .Cells(MnthCount + 4, MnthDayCount + 5)) = FrstLtr

That is the code, the array FrstLtr is 31 values in length. MnthCount is 2, MnthDayCount is 31. There should be enough space in the range to output the array? What is the issue here?

A: Copy Array Values to Worksheet
A Quick Fix
With Worksheets("Log")
    .Range(.Cells(MnthCount + 4, 6), _
        .Cells(MnthCount + 4, MnthDayCount + 5)).Value = FrstLtr
End With

Understand This
Dim cCount As Long
cCount = (MnthDayCount + 5) - (6) + (1) ' 5 - 6 + 1 = 0
cCount = MnthDayCount

The Resize Connection
Worksheets("Log").Cells(MnthCount + 4, 6).Resize(, MnthDayCount).Value = FrstLtr
Worksheets("Log").Cells(MnthCount + 4, 6).Resize(, cCount).Value = FrstLtr

The Array Resize
With Worksheets("Log").Cells(MnthCount + 4, 6)
    .Resize(, UBound(FstrLtr) + 1).Value = FrstLtr ' 1D zero-based
    .Resize(, UBound(FstrLtr)).Value = FrstLtr ' 1D one-based
    .Resize(, UBound(FstrLtr, 2) + 1).Value = FrstLtr ' 2D zero-based
    .Resize(, UBound(FstrLtr, 2)).Value = FrstLtr ' 2D one-based
End With

A Common Scenario
Dim wb As Workbook: Set wb = ThisWorkbook

Dim dws As Worksheet: Set dws = wb.Worksheets("Log")

With dws.Cells(MnthCount + 4, 6)
    .Resize(, cCount).Value = FrstLtr
End With


text:
Q: Use an index to get the value in a div containing multiple rows (divs) I have a container div and within that div I have some rows like this:

        <input type="text" value="Foo" id="param1" />

        <input type="text" value="Bar" id="param2" />

What I want is to get all the paramRow divs within the containerDiv1 and then select a paramRow div by its index.
$(function(){
    var containerDiv = $('#containerDiv1');
    var paramRows = containerDiv.find('.paramRow');

    // Below should output "Foo"
    alert($(paramRows.get(0) + ' #param1').val());

    // Below should output "Bar"
    alert($(paramRows.get(1) + ' #param2').val());
});

When I run this code, I get the following error:

Uncaught error: Syntax error, unrecognized expression: [object
  HTMLDivElement] #param1

A: You have a couple of issues. Firstly, get() returns a native DOMElement, not a jQuery object. Also, you can't append a jQuery object and a string to form a selector.
You should use eq() to get the jQuery object containing an element by index, then find() to get the input within it. Try this:

var $containerDiv = $('#containerDiv1');
var $paramRows = $containerDiv.find('.paramRow');

// Below should output "Foo"
alert($paramRows.eq(0).find('#param1').val());

// Below should output "Bar"
alert($paramRows.eq(1).find('#param2').val());

    <input type="text" value="Foo" id="param1" />

    <input type="text" value="Bar" id="param2" />


text:
Q: Data migration tool: is it possible to exclude specific websites/stores (and all of their related settings, products, etc.) from the migration? I have a Magento 1 website with a bunch of legacy websites (stores) which haven't been used for years but which still contain a bunch of old products/settings/etc.
I'm migrating to Magento 2 but don't want to migrate the old stores.
What's the best way to exclude these old stores and only migrate the store(s) I need?
Obviously I would want to exclude not only the store data itself but all of the product associations and store-specific settings related to the old stores.


text:
Q: Environment variable not found in jenkinsfile My jenkinsfile starts out with something like this:
pipeline {
    environment {
      stackName = "jenkins5"
    }

    agent any
    options {
        lock(resource: "${stackName}", inversePrecedence: false)
    }

When I run the corresponding job, I get
groovy.lang.MissingPropertyException: No such property: stackName for class: groovy.lang.Binding

How come?
I tried using env.stackName but it just gets evaluated to "null" instead of "jenkins5".

A: I suppose it happening in cause of jenkins reads options before the environment step.

A: You can probably list in variable as below:
pipeline {
agent any
environment {
      stackName = "jenkins5"
    }
options {
        lock(label: 'resource1', variable: 'stackName', , inversePrecedence: false)
    }

for more information : https://www.jenkins.io/doc/pipeline/steps/lockable-resources/


text:
Q: How to return a boolean value from a function in MySQL? I have column a and column b in table emp. I'd like to retrieve values from those columns and find the difference between them with a function. The function would return true for a 0 difference otherwise return false. I don't know how to return a value.
Also, how do I store the retrieved values in a variable?

A: MySQL doesn't really have booleans. TRUE and FALSE are aliases to 1 and 0, and the BOOL column type is just an alias for TINYINT(1). All expressions that appear to give boolean results actually return 0 or 1.
You could write your query as:
SELECT (a = b) AS a_equals_b
FROM emp
WHERE ...

A: select a, b, if(a-b=0, true, false) as diff from emp;

A: go to
http://dev.mysql.com/doc/refman/5.1/en/numeric-type-overview.html
section
BOOL, BOOLEAN


text:
Q: Include Android platform jars when using javah tool How to include jar files of the Android platform when using the javah tool to create a C/C++ .h header file ???

A: Assuming:

*

*your android SDK is installed in C:\android\sdk (and you have downloaded Android 1.5 platform)

*your android NDK is installed in C:\android\ndk

Open command line window. Go to C:\android\ndk\samples\hello-jni folder. And execute the following:
javah -classpath C:\android\sdk\platforms\android-3;src com.example.hellojni.HelloJni

It will generate com_example_hellojni_HelloJni.h file with JNI functions for hello-jni example from Android NDK.


text:
Q: Unknown error in cloning a linked list of random pointers C++ code
There is C++ code for cloning a linked list
Please refer https://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/ for details
Node* getNewNode(int data)
{
    Node *newNode = new Node();
    newNode->next = NULL;
    newNode->data = data;
    newNode->arb = NULL;
    return newNode;
}
Node * copyList(Node *head)
{
    Node *cur = head, *copy=NULL, *copy_cur, *next;
    while(cur)
    {
        if(!copy)
        {
            copy = getNewNode(cur->data);
            copy_cur = copy;
        }
        else
        {
            copy_cur->next = getNewNode(cur->data);
            copy_cur = copy_cur->next;
        }
        cur = cur->next;
    }
    copy_cur = copy;
    cur = head;
    while(cur)
    {
        next = cur->next;
        cur->next = copy_cur;
        copy_cur->arb = cur;
        copy_cur = copy_cur->next;
        cur = next;
    }
    copy_cur = copy;
    while(copy_cur)
    {
        copy_cur->arb = copy_cur->arb->arb->next;
        copy_cur = copy_cur->next;
    }
    return copy;
}

Could anyone please help me in understanding the error in this implementation.

A: There are couple of things need to be corrected in your code.
Your first while loop is only creating a new singly link list with next pointers set but not the "arb" pointers. Rather then creating a complete new list, just embed the new nodes in the original list only. It would be easier for you to set the random pointers afterwards.
Node newlyClonedNode = createNewNode(node->data);
newlyClonedNode->next = node->next;
node->next = newlyClonedNode;

Then again traverse the list and set the random pointers of new cloned nodes.
node->next->arb = node->arb->next;

Once you have done that, break the new list from original list, thus you get your original list back plus the new cloned list with random pointers set.
Node clonedNode = node->next;
node->next = node->next->next;

clonedNode->next = clonedNode->next->next;


text:
Q: SQL Server partitioning when null I have a sql server table like this:
Value   RowID   Diff
153     48      1
68      49      1
50      57      NULL
75      58      1
65      59      1
70      63      NULL
66      64      1
79      66      NULL
73      67      1
82      68      1
85      69      1
66      70      1
118     88      NULL
69      89      1
67      90      1
178     91      1

How can I make it like this (note the partition after each null in 3rd column):
Value   RowID   Diff
153     48      1
68      49      1
50      57      NULL
75      58      2
65      59      2
70      63      NULL
66      64      3
79      66      NULL
73      67      4
82      68      4
85      69      4
66      70      4
118     88      NULL
69      89      5
67      90      5
178     91      5

A: It looks like you are partitioning over sequential values of RowID.  There is a trick to do this directly by grouping on RowID - Row_Number():
select
  value,
  rowID,
  Diff,
  RowID - row_number() over (order by RowID) Diff2
from
  Table1

Notice how this gets you similar groupings, except with distinct Diff values (in Diff2):
| VALUE | ROWID |   DIFF | DIFF2 |
|-------|-------|--------|-------|
|   153 |    48 |      1 |    47 |
|    68 |    49 |      1 |    47 |
|    50 |    57 | (null) |    54 |
|    75 |    58 |      1 |    54 |
|    65 |    59 |      1 |    54 |
|    70 |    63 | (null) |    57 |
|    66 |    64 |      1 |    57 |
|    79 |    66 | (null) |    58 |
|    73 |    67 |      1 |    58 |
|    82 |    68 |      1 |    58 |
|    85 |    69 |      1 |    58 |
|    66 |    70 |      1 |    58 |
|   118 |    88 | (null) |    75 |
|    69 |    89 |      1 |    75 |
|    67 |    90 |      1 |    75 |
|   178 |    91 |      1 |    75 |

Then to get ordered values for Diff, you can use Dense_Rank() to produce a numbering over each separate partition - except when a value is Null:
select
  value,
  rowID,
  case when Diff = 1
  then dense_rank() over (order by Diff2)
  else Diff end as Diff
from (
  select
    value,
    rowID,
    Diff,
    RowID - row_number() over (order by RowID) Diff2
  from
    Table1
) T

The result is the expected result, except keyed off of RowID directly rather than off of the existing Diff column.
| VALUE | ROWID |   DIFF |
|-------|-------|--------|
|   153 |    48 |      1 |
|    68 |    49 |      1 |
|    50 |    57 | (null) |
|    75 |    58 |      2 |
|    65 |    59 |      2 |
|    70 |    63 | (null) |
|    66 |    64 |      3 |
|    79 |    66 | (null) |
|    73 |    67 |      4 |
|    82 |    68 |      4 |
|    85 |    69 |      4 |
|    66 |    70 |      4 |
|   118 |    88 | (null) |
|    69 |    89 |      5 |
|    67 |    90 |      5 |
|   178 |    91 |      5 |


text:
Q: Algorithm to find distance of an uneven polygonal road While working for my summer internship I have got a task to implement an algorithm to find the crosssecting points of two roads or more and then place that cross-section point a number and then find the distance of the previous roads to the new point and update it in the table.
I tried Ramer Douglas Peucker Line Simplification Algorithm to convert the road into a straight line and then find the intersection point but the point coming after this is not exactly the cross section point and the distance coming is also not the exact.
Please help.

A: ArcGIS has the tool "Collapse Dual Lines To Centerline". A free solution, Jump Pilot, has the JUMP Skeletonizer Plugin that can be downloaded at SourceForge.


text:
Q: selecting images in PDF embedded in html I embedded a pdf in html using embed tag. I can select text for copying but couldn't select images present in the pdf. What change should I make in this html code?
<embed src="sample.pdf" type="application/pdf" width="800px" height="650px">

A: The way image can be selected is dependent of the pdf browser.
When you embed like that, your web browser will use a plugin to display the pdf. if that plugin don't allow selection and copy of images, then it cannot be done.
If you want to extract image from a pdf, there is tools for that.


text:
Q: Incorrect operation of the sort () method on Node v.8.1.3? There is an array at the input
['1:nnn','1:vvv','2:zzz','1:yy','1:cc','2:xx','2:uu','2:tt','2:qq','2:aa','1:ff','1:ll','1:pp']

You must specify a comparator in the sort () method so that the array is sorted according to the following principles:
1) Keep the original sorting by the length of the elements (do not interchange elements of different lengths, for example, elements 1: nnn and 1: yy)
2) If the elements are the same length, then compare the first character of each element, first the elements with the prefix 1 must go, then the elements with the prefix 2.
I tried to write the following code, but I can't understand why it does not work as I would like on Node v.8.1.3? The incorrect result that I get looks like this:
['2:uu','1:nnn','1:ll','1:yy','1:cc','2:xx','1:ff','2:tt','2:qq','2:aa','1:vvv','2:zzz','1:pp']

If I run the code in a browser or in stackoverflow, then I get the expected result:
["1:nnn","1:vvv","2:zzz","1:yy","1:cc","1:ff","1:ll","1:pp","2:xx","2:uu","2:tt","2:qq","2:aa"]

What could be the problem and what am I doing wrong?

let output=['1:nnn','1:vvv','2:zzz','1:yy','1:cc','2:xx','2:uu','2:tt','2:qq','2:aa','1:ff','1:ll','1:pp']

output.sort((a,b) => {
  if(a.length===b.length) {
     if ((+a.slice(0,1))<(+b.slice(0,1))) return -1
     else return 1
  } else return 0
})

console.log(output)

A: You need a symetrically sorting and not a boolean value for only returning one or two values.
Array#sort expects three values, depending of the wanted and given order, but your result misses one value, which might be important, depending on the sort algorithm of the implementation.
Instead, you could return the delta of the values and get a perfect sorted result, independent of the implementation.

let output=['1:nnn','1:vvv','2:zzz','1:yy','1:cc','2:xx','2:uu','2:tt','2:qq','2:aa','1:ff','1:ll','1:pp']

output.sort((a, b) => b.length - a.length || a.split(':', 1) - b.split(':', 1));

console.log(output);


text:
Q: Implementing Horizontally Scrollable Date Picker in Angular 6 I am trying to implement a horizontally scroll able date picker in angular 6 app just like this. How Can I ??

A: you can use NG2HzDatePicker with 6 version
https://ahsanayaz.github.io/ng2-hz-datepicker-example/
after integrating you can overwrite its CSS according to your needs


text:
Q: Transmiting data throught the Serial Port I'm working with the SerialPort class in the Compact Framework, but I can't recive more than 2047 bytes. Exists any limit for the amount of bytes that I can recive? or How can I setup the object? I was trying with the WriteBufferSize and ReadBufferSize properties but they didn't work.

A: My guess is that it is either a processor or platform limitation. This post from the MSDN forums seems to confirm my suspicions.

A: Can you set up a thread to pull the data into another (larger) buffer that you allocate yourself?  I'd say that's the best workaround.


text:
Q: error converting YAML to JSON, did not find expected key kubernetes I am doing a lab about kubernetes in google cloud.
I have create the YAML file, but when I am trying to deploy it a shell shows me this error:
error converting YAML to JSON: yaml: line 34: did not find expected key

YAML file:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
    spec:
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: php-config
        configMap:
          name: php-config
      containers:
      - image: php-fpm:7.2
        name: php
        ports:
        - containerPort: 9000
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: php-config
          mountPath: /usr/local/etc/php-fpm.d/www.conf
          subPath: www.conf
      - image: nginx:latest
        name: nginx
        - containerPort: 80
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: nginx-config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
      volumes:
        - name: persistent-storage
          persistentVolumeClaim:
            claimName: nfs-pvc

A: yamllint package is useful to debug and find this kind of errors, just do yamllint filename and it will list the possible problems it finds. Install via your distro package manager (usually recommended if available) or via the below npm install command (it will install globally)
npm install -g yaml-lint
Thanks to Kyle VG for the npm command

A: The overall file looks good.
There are some issues with indentation.
YAML file
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
    spec:
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: php-config
        configMap:
          name: php-config
      containers:
      - image: php-fpm:7.2
        name: php
        ports:
        - containerPort: 9000
        volumeMounts:
        - name: persistent-storage
            # looks like indentation issue here
            mountPath: /var/www/data
        - name: php-config
            # looks like indentation issue here
            mountPath: /usr/local/etc/php-fpm.d/www.conf
            subPath: www.conf
      - image: nginx:latest
        name: nginx
        - containerPort: 80
        volumeMounts:
        - name: persistent-storage
            mountPath: /var/www/data
        - name: nginx-config
            mountPath: /etc/nginx/nginx.conf
            subPath: nginx.conf
      volumes:
        - name: persistent-storage
          persistentVolumeClaim:
            claimName: nfs-pvc

A: Use a yaml parser to find the source of the problem
There is many online ones, like https://yaml-online-parser.appspot.com/

A: I got that error while creating a yaml file for an Ingress using Helm. I had something like this as my Ingress specification
spec:
  tls:
  - hosts:
    - {{ .Values.ingress.host }}

and in the values.yaml
ingress:
  host: "[NAMESPACE]-example.com"

Turned out that the brackets where causing the error.
The issue could be fixed by putting quotes on the value using the quote function.
- {{ .Values.ingress.host | quote }}

This is also what the Helm doc recommends

The easiest way to avoid type conversion errors is to be explicit about strings, and implicit about everything else. Or, in short, quote all strings.

and here

When you are working with string data, you are always safer quoting the strings than leaving them as bare words:

A: Following higuita's answer you can lint your yaml and check for errors without installing a module in your machine using npx. I prefer this approach for commands that I do not intend to use often. NPX downloads the package, executes the command and remove the package when finishes.
npx yaml-lint yamllint file_name

A: Although the above yaml file looked fine, the indentation was the issue(which is hardly visible when looking at the file). Another issue that could cause this error, is having a problem with the file, such as a missing field name, or collon.

A: I had the same problem, but I solve copying the link of the RAW Github file and set it on kubectl
kubectl create -f https://raw.githubusercontent.com/user/project/master/file.yml

A: Ensure you don't have any invisible characters which are causing you issue.
This error:
error converting YAML to JSON: yaml: line 96: could not find expected '':''

Was because of an invisible break between the : and the C in this line:
- name: CERT_ALIAS

A: I got this error, because of missing |- in values.yaml
WRONG
myconf:
  application:
    properties:
      my.prop=1

RIGHT
myconf:
  application:
    properties: |-
      my.prop=1

A: I recently came across this same error when attempting to create a template yaml file for multiple cronjobs where the settings were stored in an array in a values.yaml file.
Here is an example of the values data based on my actual code:
allCronJobs:
  - cron1:
    cronJobName: hello-world
    enabled: true
    cronJob:
      schedule: "2 * * * *"
    job:
      backoffLimit: 3
    pod:
      restartPolicy: OnFailure
  - cron2:
    cronJobName: foo-bar
    enabled: true
    cronJob:
      schedule: "0 11 * * *"
    job:
      activeDeadlineSeconds: 10800
    pod:
      restartPolicy: OnFailure

Here is a snippet from the template file using the
range syntax. (This is the code that resulted in the error converting YAML to JSON)
{{ range $index, $currCron := .Values.allCronJobs -}}
{{- if $currCron.enabled -}}
{{- with $ }}
apiVersion: batch/v1
kind: CronJob
metadata:
  name: {{ include "api-payments.fullname" . }}-{{ $currCron.cronJobName }}
  labels:
    {{- include "api-payments.labels" . | nindent 4 }}
spec:
  schedule: {{ $currCron.cronJob.schedule | quote }}
  startingDeadlineSeconds: {{ $currCron.cronJob.startingDeadlineSeconds }}

Thankfully, after much searching, I came across this post that helped me figure it out:  https://dev.to/ujwaldhakal/manage-multiple-cron-with-helm-flow-control-32i7
I needed to include "---" between each iteration of cronjob, just like helm does when processing multiple files (which are usually a single resource per file).
Here is the corrected code that now works.  The change is on line 4.
{{ range $index, $currCron := .Values.allCronJobs -}}
{{- if $currCron.enabled -}}
{{- with $ }}
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: {{ include "api-payments.fullname" . }}-{{ $currCron.cronJobName }}
  labels:
    {{- include "api-payments.labels" . | nindent 4 }}
spec:
  schedule: {{ $currCron.cronJob.schedule | quote }}
  startingDeadlineSeconds: {{ $currCron.cronJob.startingDeadlineSeconds }}


text:
Q: Integral of exponential with rational argument Is there any way to solve the following integral?
$$\int_0^\infty \exp\Bigl(-\frac{(y^2 - x^2)^2}{x^2}\Bigr) \mathrm{d}x$$
Assume $y>0$.

A: Following the aproach of How to evaluate $\int_{0}^{+\infty}\exp(-ax^2-\frac b{x^2})\,dx$ for $a,b>0$ I got
$$\begin{align}I=&\int_0^\infty \exp\bigl(-\frac{(y^2-x^2)^2}{x^2}\bigr)\mathrm{d}x\\ =& \begin{Vmatrix}t =\frac{x}{y}\end{Vmatrix}=y\int_0^\infty \exp\bigl(-(t-t^{-1})^2y^2\bigr)\mathrm{d}t
= y\biggl(\int_0^1+\int_1^\infty\biggr) \exp\bigl(-(t-t^{-1})^2y^2\bigr)\mathrm{d}t\\
=&\begin{Vmatrix}s=\frac{1}{t}\text{ in first integral}\end{Vmatrix}
=\int_1^\infty \frac{1}{s^2}\exp\bigl(-(s-s^{-1})^2y^2\bigr)\mathrm{d}s+\int_1^\infty \exp\bigl(-(t-t^{-1})^2y^2\bigr)\mathrm{d}x\\
=&\int_1^\infty (1+t^{-2})\exp\bigl(-(t-t^{-1})^2y^2\bigr)\mathrm{d}x
=\begin{Vmatrix}z=t-\frac{1}{t}\end{Vmatrix}=y\int_0^\infty \exp(-z^2y^2)\mathrm{d}z\\
=&y\frac{1}{2}\sqrt{\frac{\pi}{y^2}}=\frac{\sqrt{\pi}}{2}
\end{align}$$
Thanks again, @Zacky.


text:
Q: trouble importing Pytorch in Jupyter notebook Iam new to deep learning and Iam trying to import Pytorch on Jupyter Notebook.
I installed Pytorch with the following lines of code in Anaconda Prompt.
conda create -n pytorch_p37 python=3.7
conda activate pytorch_p37
conda install pytorch torchvision -c pytorch
conda install jupyter
conda list

it all executed well.
but on importing pytorch it shows errors.
import torch

this error below:-
OSError: [WinError 126] The specified module could not be found

error showing image

A: The problem lied where I was installing a CUDA version.
I tried installing the CPU version and it worked fine (CUDA None).
conda install pytorch torchvision cpuonly -c pytorch

A: !pip install torch

It worked for me in a Anaconda's Jupyter notebook.

A: I lost one hour and found that launching the conda environment as stacked version does not lead to error:
in your example:
conda activate pytorch_p37

and from jupyter
import torch  # error

from terminal:
conda activate --stack pytorch_p37

and from jupyter:
import torch  # success

I could not figure out why :/
https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#activating-an-environment


text:
Q: How to inject dynamic DbContext object into repository using Autofac I have an .net core web api application where I'm using entity framework core with service layer, unit of work and repository layer pattern. For DI I'm using Autofac.
The application has multiple clients and each client has its own database and the schema for all these databases is same. With each API call I'll get the client specific connection string, using which I have to create a DbContext and use it for all its operations.
On Startup class I have registered my dbcontext ClientDbContext and all other classes. When the unit-of-work class is  called I am creating my new DbContext based on the connection string. I want the repository to use this instance, but the repository is still using the initial ClientDbContext instance which was created at startup.
How can I make the repository use the new DbContext instance?
Unit of Work:
public class UnitOfWork : IUnitOfWork
{
    public ClientDbContext ClientDbContext { get; private set; }

    public UnitOfWork ()
    {

    }

    public void SetDbContext(string connectionString)
    {
        if(ClientDbContext == null)
        {
            //creating new db context instance here
            ClientDbContext = MembershipRepository.CreateDbContext(connectionString);
        }
    }
    //property injection
    public IGenericRepository<SomeEntity, ClientDbContext> SomeEntityGenericRepository { get; }
}

Generic Repository:
public class GenericRepository<TEntity, TDbContext> : IGenericRepository<TEntity, TDbContext> where TEntity : class
where TDbContext : DbContext
{
    private readonly TDbContext _context;
    private readonly DbSet<TEntity> _dbset;
    public GenericRepository(TDbContext context)
    {
        // need to get updated context here, but getting the initial one
        _context = context;
        _dbset = _context.Set<TEntity>();
    }
}

Autofac module called in Startup.cs:
builder.Register(a => new ClientDbContext()).InstancePerLifetimeScope();

builder.RegisterGeneric(typeof(GenericRepository<,>)).As(typeof(IGenericRepository<,>)).InstancePerLifetimeScope();

//Register Unit of Work here
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope().PropertiesAutowired();

//Register Services here
builder.RegisterType<SomeService>().As<ISomeService>().InstancePerLifetimeScope();

Can anyone please help me out on how to achieve the above requirement?
Is there any way I can make Autofac use my new created dbcontext object?

A: Instead of
builder.Register(a => new ClientDbContext()).InstancePerLifetimeScope();

you could use
builder.Register(c => c.Resolve<IUnitOfWork>().ClientDbContext)
       .InstancePerLifetimeScope();

By the way I'm not sure what is the responsibility of your IUnitOfWork. Another way of doing this would be to have a class that would provide information about the current user :
public interface IClientContext
{
    public String ClientIdentifier { get; }
}

Then a DbContextFactory that would create the DbContext based on the IClientContext
public interface IDbContextFactory
{
    IDbContext CreateDbContext();
}

public class DbContextFactory
{
    public DbContextFactory(IClientContext clientContext)
    {
        this._clientContext = clientContext;
    }

    private readonly IClientContext _clientContext;

    public IDbContext CreateDbContext()
    {
        // get the connectionstring from IClientContext and return the IDbContext
    }
}

The concrete implementation of IClientContext depends on the way you can get this information, it could be from current HttpContext or any other way it's up to you.
It seems that at some point you call SetDbContext you can keep this way by creating a XXXClientContextProvider where XXX is relative to the way you get this information.
public class XXXClientContextProvider
{
    private IClientContext _clientContext;

    public IClientContext GetClientContext()
    {
        if(this._clientContext == null)
        {
           throw new Exception("client context is null. You should do X or Y");
        }
        return this._clientContext;
    }
    public void SetClientContext(String clientId)
    {
        if(this._clientContext != null)
        {
            throw new Exception("client context has already been set");
        }
        this._clientContext = new StaticClientContext(clientId);
    }
}

and then register everything like this :
builder.Register(c => c.Resolve<IClientContextProvider>().GetClientContext())
       .As<IClientContext>()
       .InstancePerLifetime();

builder.Register(c => c.Resolve<IDbContextFactory>().CreateDbContext())
       .As<IDbContext>()
       .InstancePerLifetime();


text:
Q: Clear Android Studio file type cache This might seem weird, but for some reason Android Studio is acting up, I accidentally created a regular file called MessageC, it asked me to set the file type and I set KT. Afterwords I noticed my mistake, deleted the file and created a new KOTLIN FILE with the same name, but for some reason it seems to have stayed saved in the IDE that MessageC is regular file and not Kotlin file (as renaming it to anything else works fine). This is even after restarting the project, where can I remove this cache?

A: Check these types under Preferences | Editor | File Types:

*

*Text

*File type auto-detected by file content

*Files supported via TextMate bundles


text:
Q: Accessing "Salesforce Files Settings" in Apex Is it possible to see in Apex if an org has the following setting enabled?

Files uploaded to the Attachments related list on records are uploaded
  as Salesforce Files, not as attachments

It doesn't have to be an explicit boolean that I can call; even if running a query could give me the answer that'd work just as well.
If not is it possible via the API at least?


text:
Q: Why I can't put proxy_set_header inside an if clause? With this configuration:
server {
    listen 8080;
    location / {
        if ($http_cookie ~* "mycookie") {
            proxy_set_header X-Request $request;
            proxy_pass http://localhost:8081;
        }
    }
}

I have this error when I reload nginx service:
Reloading nginx configuration: nginx: [emerg] "proxy_set_header" directive is not allowed here in /etc/nginx/conf.d/check_cookie.conf:5
nginx: configuration file /etc/nginx/nginx.conf test failed

This configuration works OK, but it does not do what I want:
server {
    listen 8080;
    location / {
        proxy_set_header X-Request $request;
        if ($http_cookie ~* "mycookie") {
            proxy_pass http://localhost:8081;
        }
    }
}

Why I can't put proxy_set_header directive inside an if clause?

A: Inside location try something like this
# default header value in a new variable
set $esb "$remote_addr, $host";

# if my custom header exists
if ($http_my_header){
  set $esb "$http_my_header, $remote_addr, $host";
}

proxy_set_header my-header $esb;

A: Unlike proxy_pass, you cannot put proxy_set_header inside an if block. You can only put it in http/server/location block. So your 2nd config is good.
Reference: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header

context:  http, server, location

Don't know what the $request variable is. It doesn't appear in nginx variable list: http://wiki.nginx.org/HttpCoreModule#Variables. What are you trying to achieve here?


text:
Q: Why does WWW::Mechanize fail with "X-Died: Illegal field name 'X-Meta-Twitter:title'"? Why does WWW::Mechanize have blank content after getting the following URL?  Using a browser or curl there is a full HTML page retrieved.
use WWW::Mechanize;
$mech = new WWW::Mechanize;
$mech->get("http://www.belizejudiciary.org/web/judgements2/");
print $mech->content  # prints nothing

Here is the dump of the response:
HTTP/1.1 200 OK
Connection: close
Date: Fri, 10 Feb 2017 00:51:47 GMT
Server: Apache/2.4
Content-Type: text/html; charset=UTF-8
Client-Aborted: die
Client-Date: Fri, 10 Feb 2017 00:51:48 GMT
Client-Peer: 98.129.229.64:80
Client-Response-Num: 1
Client-Transfer-Encoding: chunked
Link: <http://www.belizejudiciary.org/web/wp-json/>; rel="https://api.w.org/"
Link: <http://www.belizejudiciary.org/web/?p=468>; rel=shortlink
Set-Cookie: X-Mapping-hepadkon=FAB86566672CEB74D66B2818CA030616; path=/
X-Died: Illegal field name 'X-Meta-Twitter:title' at /usr/local/lib/perl5/site_perl/5.16.3/sun4-solaris/HTML/HeadParser.pm line 207.
X-Pingback: http://www.belizejudiciary.org/web/xmlrpc.php

I have version 3.70 of HTML::Parser installed.

A: Your dump shows that there was an error parsing the response:

X-Died: Illegal field name 'X-Meta-Twitter:title' at /usr/local/lib/perl5/site_perl/5.16.3/sun4-solaris/HTML/HeadParser.pm line 207.

This is caused by a bug in HTML::HeadParser:

<meta> tags can have name attributes with colons in them, and this is perfectly valid. But HTML::HeadParser then tries to register these as X-Meta-<name> headers using HTTP::Headers. Newer versions of HTTP::Headers (since 6.05) have stricter checks for headers, and will refuse them if they contain colons.

This was fixed in version 3.71 of the HTML-Parser distribution, so you should upgrade.


text:
Q: Assign values to a column conditionally based on text category in R I need to assign values to a new column based on the "keyword". I did some simple trial like below. The rule is I need to tag all the keyword containing "advertising" or "marketing" as "Marketing".
keyword <- c("advertising plan",
           "advertising budget",
           "marketing plan",
           "marketing budget",
           "hr plan",
           "hr budget",
           "operation plan",
           "operation budget")
indicator <- c(1,0,0,1,1,1,0,1)
sample <- cbind(keyword,indicator)

I used to use this method to do the tagging.
sample$topic <- ifelse(grepl("(marketing|advertising)",sample$keyword),"Marketing",0)

But now, I have longer rules, which are stored as another string factor like below:
rule <- c("marketing", "advertising", "word 3", "word 4" .... "word 500")

It is hard to type the rules one by one in the previous code. I wonder if there is way to run all the rules together in R or I should write a loop to do this.

A: We can collapse the vector in to a single string with delimiter | for the pattern in grepl
ifelse(grepl(paste(rule, collapse="|"), sample$keyword), "Marketing", 0)


text:
Q: Locator issue for element which has apostrophe (') in text I have to find text -'To' email address is formatted incorrectly- using xpath. Below xpath is working well for me
(//*[contains(.,"'To' email address is formatted incorrectly.")])[5]

But when I put this xpath in my locator.
@FindBy(xpath="(//*[contains(.,"'To' email address is formatted incorrectly.")])[5]") public WebElement incorrectEmailFormatLabel;

I am getting warning error message in code. I know this is because of double quotes used("'To'..."), but if I change it to single quote(''To'...') I get this error message
invalid selector: Unable to locate an element with the xpath expression (//*[contains(.,''To' email address is formatted incorrectly.')])[5]

Let me know how to resolve it? I followed this post also, here xpath is not working for me.
(//*[contains(.,\" 'To' email address is formatted incorrectly.\")])[5]

A: In the question, you provided the excepted answer shows using \ helps!
Try this:
@FindBy(xpath="(//*[contains(.,\"\'To\' email address is formatted incorrectly.\")])[5]") public WebElement incorrectEmailFormatLabel;

Hope this helps!


text:
Q: Peg Thing example in Clojure for the brave and true:will there be a stack overflow problem? I am trying to learn Clojure by following the book "Clojure for the Brave and True". In chapter five there is an example program "Peg Thing". The full source code for the problem can be found at github.
My question is, it looks like the functions are calling each other and the stack is growing with every move, until you exit the game. Am I correct? So, potentially if we make a robot play this game for millions of rounds, at some point we will get a stack overflow. prompt-move calls itself, but without calling recur. And in a successful move, game-over will be called, and if the user wants to play more, there will be more stacks on top of the current stack frame. Am I getting it wrong, or is this implemented in a simplistic way as a demo and the implementer doesn't care about possibility of a million game plays?


text:
Q: mock modules works only outside describe statement I'm trying to mock a function as follow, it works for one test because I can only mock the function outside of describe, but when I try to mock that module inside it it doesn't work and code as follows:
import * as someModule from './someModule'
jest.mock('./someModule')

describe('functions', () => {
    it('do first test', () => {
  //  jest.mock('./someModule')
        expect(jest.isMockFunction(someModule.oneFunction)).toBeTruthy()
    })
})

jest.mock('./someModule') inside it doesn't work
So, how can I do mocking for only one test?

A: You should require the module after calling jest.mock(). See official test case
E.g.
someModule.ts:
export function oneFunction() {}

someModule.test.ts:
describe('functions', () => {
  it('do first test', () => {
    jest.mock('./someModule');
    const someModule = require('./someModule');
    expect(jest.isMockFunction(someModule.oneFunction)).toBeTruthy();
  });
});

test result:
 PASS  examples/66284054/someModule.test.js
  functions
    ✓ do first test (8 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.537 s

source code: https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/66284054