Programs & Examples On #Windows services

Windows services are background service processes run by the Service Control Manager on Windows NT based operating systems, similar to daemons or UNIX services.

How do you run CMD.exe under the Local System Account?

I would recommend you work out the minimum permission set that your service really needs and use that, rather than the far too privileged Local System context. For example, Local Service.

Interactive services no longer work - or at least, no longer show UI - on Windows Vista and Windows Server 2008 due to session 0 isolation.

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

Service will not start: error 1067: the process terminated unexpectedly

I resolved the problem.This is for EAServer Windows Service

Resolution is --> Open Regedit in Run prompt

Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\EAServer

In parameters, give SERVERNAME entry as EAServer.

[It is sometime overwritten with Envirnoment variable : Path value]

How to uninstall a Windows Service when there is no executable for it left on the system?

You should be able to uninstall it using sc.exe (I think it is included in the Windows Resource Kit) by running the following in an "administrator" command prompt:

sc.exe delete <service name>

where <service name> is the name of the service itself as you see it in the service management console, not of the exe.

You can find sc.exe in the System folder and it needs Administrative privileges to run. More information in this Microsoft KB article.

Alternatively, you can directly call the DeleteService() api. That way is a little more complex, since you need to get a handle to the service control manager via OpenSCManager() and so on, but on the other hand it gives you more control over what is happening.

Automatically start a Windows Service on install

You can use the GetServices method of ServiceController class to get an array of all the services. Then, find your service by checking the ServiceName property of each service. When you've found your service, call the Start method to start it.

You should also check the Status property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).

How to force uninstallation of windows service

sc delete sericeName

Just make sure the service is stopped before doing this. I have seen this work most times. There are times where I have seen windows get stuck on something and it insists on a reboot.

What are the specific differences between .msi and setup.exe file?

MSI is basically an installer from Microsoft that is built into windows. It associates components with features and contains installation control information. It is not necessary that this file contains actual user required files i.e the application programs which user expects. MSI can contain another setup.exe inside it which the MSI wraps, which actually contains the user required files.

Hope this clears you doubt.

Run batch file as a Windows service

No need for extra software. Use the task scheduler -> create task -> hidden. The checkbox for hidden is in the bottom left corner. Set the task to trigger on login (or whatever condition you like) and choose the task in the actions tab. Running it hidden ensures that the task runs silently in the background like a service.

Note that you must also set the program to run "whether the user is logged in or not" or the program will still run in the foreground.

How can I verify if a Windows Service is running

Here you get all available services and their status in your local machine.

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx

Can't start Tomcat as Windows Service

I had the similar issue, But installing tomcat 32bit and jdk 32 bit worked, This happens mostly because of mismatch Bit.

How do I get the currently-logged username from a Windows service in .NET?

Completing the answer from @xanblax

private static string getUserName()
    {
        SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
        {
            foreach (System.Management.ManagementObject Process in searcher.Get())
            {
                if (Process["ExecutablePath"] != null &&
                    string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
                {
                    string[] OwnerInfo = new string[2];
                    Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

                    return OwnerInfo[0];
                }
            }
        }
        return "";
    }

Modifying the "Path to executable" of a windows service

A little bit deeper with 'SC' command, we are able to extract all 'Services Name' and got all 'QueryServiceConfig' :)

>SC QUERY > "%computername%-services.txt" [enter]

>FIND "SERVICE_NAME: " "%computername%-services.txt" /i > "%computername%-services-name.txt" [enter]

>NOTEPAD2 "%computername%-services-name.txt" [enter]

Do 'small' NOTEPAD2 editing.. Select 'SERVICE_NAME: ', CTRL+H, click 'Replace All' Imagine that we can do 'Replace All' within 'CMD'

Then, continue with 'CMD'..

>FOR /F "DELIMS= SKIP=2" %S IN ('TYPE "%computername%-services-name.txt"') DO @SC QC "%S" >> "%computername%-services-list-config.txt" [enter]

>NOTEPAD2 "%computername%-services-list-config.txt" [enter]

it is 'SERVICES on Our Machine' Raw data is ready for feeding 'future batch file' so the result is look like this below!!!

+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
| SERVICE_NAME | TYPE                    | START_TYPE                | ERROR_CONTROL | BINARY_PATH_NAME                                 | LOAD_ORDER_GROUP | TAG | DISPLAY_NAME   | DEPENDENCIES | SERVICE_START_NAME |
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
+ WSearch      | 10  WIN32_OWN_PROCESS   | 2   AUTO_START  (DELAYED) | 1   NORMAL    | C:\Windows\system32\SearchIndexer.exe /Embedding | none             | 0   | Windows Search | RPCSS        | LocalSystem        |
+ wuauserv     | 20  WIN32_SHARE_PROCESS | 2   AUTO_START  (DELAYED) | 1   NORMAL    | C:\Windows\system32\svchost.exe -k netsvcs       | none             | 0   | Windows Update | rpcss        | LocalSystem        |

But, HTML will be pretty easier :D

Any bright ideas for improvement are welcome V^_^

Check if a Windows service exists and delete in PowerShell

You can use WMI or other tools for this since there is no Remove-Service cmdlet until Powershell 6.0 (See Remove-Service doc)

For example:

$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
$service.delete()

Or with the sc.exe tool:

sc.exe delete ServiceName

Finally, if you do have access to PowerShell 6.0:

Remove-Service -Name ServiceName

How to check if a service is running via batch file and start it, if it is not running?

That should do it:

FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

Install a .NET windows service without InstallUtil.exe

In the case of trying to install a command line application as a Windows service try the 'NSSM' utility. Related ServerFault details found here.

Windows service start failure: Cannot start service from the command line or debugger

To install Open CMD and type in {YourServiceName} -i once its installed type in NET START {YourserviceName} to start your service

to uninstall

To uninstall Open CMD and type in NET STOP {YourserviceName} once stopped type in {YourServiceName} -u and it should be uninstalled

How to uninstall a windows service and delete its files without rebooting

Both Jonathan and Charles are right... you've got to stop the service first, then uninstall/reinstall. Combining their two answers makes the perfect batch file or PowerShell script.

I will make mention of a caution learned the hard way -- Windows 2000 Server (possibly the client OS as well) will require a reboot before the reinstall no matter what. There must be a registry key that is not fully cleared until the box is rebooted. Windows Server 2003, Windows XP and later OS versions do not suffer that pain.

When creating a service with sc.exe how to pass in context parameters?

I use to just create it without parameters, and then edit the registry HKLM\System\CurrentControlSet\Services\[YourService].

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Best Timer for using in a Windows service

I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:

This will:

  • Reduce plumbing code that replicates scheduler behaviour
  • Provide greater flexibility in terms of scheduling behaviour (e.g. only run on weekends) with all scheduling logic abstracted from application code
  • Utilise the command line arguments for parameters without having to setup configuration values in config files etc
  • Far easier to debug/test during development
  • Allow a support user to execute by invoking the console application directly (e.g. useful during support situations)

Easier way to debug a Windows service


static void Main()
{
#if DEBUG
                // Run as interactive exe in debug mode to allow easy
                // debugging.

                var service = new MyService();
                service.OnStart(null);

                // Sleep the main thread indefinitely while the service code
                // runs in .OnStart

                Thread.Sleep(Timeout.Infinite);
#else
                // Run normally as service in release mode.

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]{ new MyService() };
                ServiceBase.Run(ServicesToRun);
#endif
}

How to restart service using command prompt?

You can use sc start [service] to start a service and sc stop [service] to stop it. With some services net start [service] is doing the same.

But if you want to use it in the same batch, be aware that sc stop won't wait for the service to be stopped. In this case you have to use net stop [service] followed by net start [service]. This will be executed synchronously.

Install windows service without InstallUtil.exe

This Problem is due to Security, Better open Developer Command prompt for VS 2012 in RUN AS ADMINISTRATOR and install your Service, it fix your problem surely.

How can I run MongoDB as a Windows service?

Consider using

mongod --install --rest --master

(SC) DeleteService FAILED 1072

What I've done is go to this location in regedit:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

From here, you will see a folder for every service on your machine. Simply delete the folder for the service you wish, and you're done.

N.B: Stop the service before you try this.

Simplest way to restart service on a remote computer

As of Windows XP, you can use sc.exe to interact with local and remote services. Schedule a task to run a batch file similar to this:

sc \\server stop service
sc \\server start service

Make sure the task runs under a user account privileged on the target server.

psservice.exe from the Sysinternals PSTools would also be doing the job:

psservice \\server restart service

.NET console application as Windows service

You need to seperate the functionality into a class or classes and launch that via one of two stubs. The console stub or service stub.

As its plain to see, when running windows, the myriad services that make up the infrastructure do not (and can't directly) present console windows to the user. The service needs to communicate with the user in a non graphical way: via the SCM; in the event log, to some log file etc. The service will also need to communicate with windows via the SCM, otherwise it will get shutdown.

It would obviously be acceptable to have some console app that can communicate with the service but the service needs to run independently without a requirement for GUI interaction.

The Console stub can very useful for debugging service behaviour but should not be used in a "productionized" environment which, after all, is the purpose of creating a service.

I haven't read it fully but this article seems to pint in the right direction.

How do I uninstall a Windows service if the files do not exist anymore?

The easiest way is to use Sys Internals Autoruns

enter image description here

Start it in admin mode and then you can remove obsolete services by delete key

Windows service on Local Computer started and then stopped error

I came across the same issue. My service is uploading/receiving XMLS and write the errors to the Event Log.

When I went to the Event Log, I tried to filter it. It prompt me that the Event Log was corrupted.

I cleared the Event Log and all OK.

Get startup type of Windows service using PowerShell

You can use also:

(Get-Service 'winmgmt').StartType

It returns just the startup type, for example, disabled.

How can I delete a service in Windows?

Before removing the service you should review the dependencies.

You can check it:

Open services.msc and find the service name, switch to the "Dependencies" tab.

Source: http://www.sysadmit.com/2016/03/windows-eliminar-un-servicio.html

Start / Stop a Windows Service from a non-Administrator user account

It's significantly easier to grant management permissions to a service using one of these tools:

  • Group Policy
  • Security Template
  • subinacl.exe command-line tool.

Here's the MSKB article with instructions for Windows Server 2008 / Windows 7, but the instructions are the same for 2000 and 2003.

How to create an installer for a .net Windows Service using Visual Studio

Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.

Here is my brief steps how to create service with installer:

  1. Run Visual Studio, Go to File->New->Project
  2. Select .NET Framework 4, in 'Search Installed Templates' type 'Service'
  3. Select 'Windows Service'. Type Name and Location. Press OK.
  4. Double click Service1.cs, right click in designer and select 'Add Installer'
  5. Double click ProjectInstaller.cs. For serviceProcessInstaller1 open Properties tab and change 'Account' property value to 'LocalService'. For serviceInstaller1 change 'ServiceName' and set 'StartType' to 'Automatic'.
  6. Double click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall event. Write code:

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (System.ServiceProcess.ServiceController sc = new 
        System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
    
  7. Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.

  8. Create install.bat with below script:

    :::::::::::::::::::::::::::::::::::::::::
    :: Automatically check & get admin rights
    :::::::::::::::::::::::::::::::::::::::::
    @echo off
    CLS 
    ECHO.
    ECHO =============================
    ECHO Running Admin shell
    ECHO =============================
    
    :checkPrivileges 
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges ) 
    
    :getPrivileges 
    if '%1'=='ELEV' (shift & goto gotPrivileges)  
    ECHO. 
    ECHO **************************************
    ECHO Invoking UAC for Privilege Escalation 
    ECHO **************************************
    
    setlocal DisableDelayedExpansion
    set "batchPath=%~0"
    setlocal EnableDelayedExpansion
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs" 
    ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs" 
    "%temp%\OEgetPrivileges.vbs" 
    exit /B 
    
    :gotPrivileges 
    ::::::::::::::::::::::::::::
    :START
    ::::::::::::::::::::::::::::
    setlocal & pushd .
    
    cd /d %~dp0
    %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
    pause
    
  9. Create uninstall.bat file (change in pen-ult line /i to /u)
  10. To install and start service run install.bat, to stop and uninstall run uninstall.bat

Install Windows Service created in Visual Studio

You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".

It won't install right out of the box... you need to create the installer class first.

Some reference on service installer:

How to: Add Installers to Your Service Application

Quite old... but this is what I am talking about:

Windows Services in C#: Adding the Installer (part 3)

By doing this, a ProjectInstaller.cs will be automaticaly created. Then you can double click this, enter the designer, and configure the components:

  • serviceInstaller1 has the properties of the service itself: Description, DisplayName, ServiceName and StartType are the most important.

  • serviceProcessInstaller1 has this important property: Account that is the account in which the service will run.

For example:

this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;

The type initializer for 'MyClass' threw an exception

Dictionary keys should be unique !

In my case, I was using a Dictionary, and I found two items in it have accidentally the same key.

Dictionary<string, string> myDictionary = new Dictionary<string, string>() {
            {"KEY1", "V1"},
            {"KEY1", "V2" },
            {"KEY3", "V3"},
        };

How can I run an EXE program from a Windows Service using C#?

First, we are going to create a Windows Service that runs under the System account. This service will be responsible for spawning an interactive process within the currently active User’s Session. This newly created process will display a UI and run with full admin rights. When the first User logs on to the computer, this service will be started and will be running in Session0; however the process that this service spawns will be running on the desktop of the currently logged on User. We will refer to this service as the LoaderService.

Next, the winlogon.exe process is responsible for managing User login and logout procedures. We know that every User who logs on to the computer will have a unique Session ID and a corresponding winlogon.exe process associated with their Session. Now, we mentioned above, the LoaderService runs under the System account. We also confirmed that each winlogon.exe process on the computer runs under the System account. Because the System account is the owner of both the LoaderService and the winlogon.exe processes, our LoaderService can copy the access token (and Session ID) of the winlogon.exe process and then call the Win32 API function CreateProcessAsUser to launch a process into the currently active Session of the logged on User. Since the Session ID located within the access token of the copied winlogon.exe process is greater than 0, we can launch an interactive process using that token.

Try this one. Subverting Vista UAC in Both 32 and 64 bit Architectures

Are there any log file about Windows Services Status?

Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.

You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.

Stopping a windows service when the stop option is grayed out

I solved the problem with the following steps:

  1. Open "services.msc" from command / Windows RUN.

  2. Find the service (which is greyed out).

  3. Double click on that service and go to the "Recovery" tab.

  4. Ensure that

    • First Failure action is selected as "Take No action".
    • Second Failure action is selected as "Take No action".
    • Subsequent Failures action is selected as "Take No action".

    and Press OK.

Now, the service will not try to restart and you can able to delete the greyed out service from services list (i.e. greyed out will be gone).

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

We found a different solution to a problem with the same symptom:

We saw this error when we updated the project from .net 4.7.1 to 4.7.2.

The problem was that even though we were not referencing System.Net.Http any more in the project, it was listed in the dependentAssembily section of our web.config. Removing this and any other unused assembly references from the web.config solved the problem.

Create Windows service from executable

Extending (Kevin Tong) answer.

Step 1: Download & Unzip nssm-2.24.zip

Step 2: From command line type:

C:\> nssm.exe install [servicename]

it will open GUI as below (the example is UT2003 server), then simply browse it to: yourapplication.exe

enter image description here

More information on: https://nssm.cc/usage

How do I debug Windows services in Visual Studio?

I just added this code to my service class so I could indirectly call OnStart, similar for OnStop.

    public void MyOnStart(string[] args)
    {
        OnStart(args);
    }

How to solve "The specified service has been marked for deletion" error

I had the same problem, finally I decide to kill service process.

for it try below steps:

  • get process id of service with

    sc queryex <service name>

  • kill process with

    taskkill /F /PID <Service PID>

Cannot start MongoDB as a service

Remember to create the database before starting the service

C:\>"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --dbpath d:\MONGODB\DB
2016-10-13T18:18:23.135+0200 I CONTROL  [main] Hotfix KB2731284 or later update is installed, no need to zero-out data files
2016-10-13T18:18:23.147+0200 I CONTROL  [initandlisten] MongoDB starting : pid=4024 port=27017 dbpath=d:\MONGODB\DB 64-bit host=mongosvr
2016-10-13T18:18:23.148+0200 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2016-10-13T18:18:23.149+0200 I CONTROL  [initandlisten] db version v3.2.8
2016-10-13T18:18:23.149+0200 I CONTROL  [initandlisten] git version: ed70e33130c977bda0024c125b56d159573dbaf0
2016-10-13T18:18:23.150+0200 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1p-fips 9 Jul 2015
2016-10-13T18:18:23.151+0200 I CONTROL  [initandlisten] allocator: tcmalloc
2016-10-13T18:18:23.151+0200 I CONTROL  [initandlisten] modules: none
2016-10-13T18:18:23.152+0200 I CONTROL  [initandlisten] build environment:
2016-10-13T18:18:23.152+0200 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2016-10-13T18:18:23.153+0200 I CONTROL  [initandlisten]     distarch: x86_64
2016-10-13T18:18:23.153+0200 I CONTROL  [initandlisten]     target_arch: x86_64
2016-10-13T18:18:23.154+0200 I CONTROL  [initandlisten] options: { storage: { dbPath: "d:\MONGODB\DB" } }
2016-10-13T18:18:23.166+0200 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=8G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2016-10-13T18:18:23.722+0200 I NETWORK  [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2016-10-13T18:18:23.723+0200 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'd:/MONGODB/DB/diagnostic.data'
2016-10-13T18:18:23.895+0200 I NETWORK  [initandlisten] waiting for connections on port 27017

Then you can stop the process Control-C

2016-10-13T18:18:44.787+0200 I CONTROL  [thread1] Ctrl-C signal
2016-10-13T18:18:44.788+0200 I CONTROL  [consoleTerminate] got CTRL_C_EVENT, will terminate after current cmd ends
2016-10-13T18:18:44.789+0200 I FTDC     [consoleTerminate] Shutting down full-time diagnostic data capture
2016-10-13T18:18:44.792+0200 I CONTROL  [consoleTerminate] now exiting
2016-10-13T18:18:44.792+0200 I NETWORK  [consoleTerminate] shutdown: going to close listening sockets...
2016-10-13T18:18:44.793+0200 I NETWORK  [consoleTerminate] closing listening socket: 380
2016-10-13T18:18:44.793+0200 I NETWORK  [consoleTerminate] shutdown: going to flush diaglog...
2016-10-13T18:18:44.793+0200 I NETWORK  [consoleTerminate] shutdown: going to close sockets...
2016-10-13T18:18:44.795+0200 I STORAGE  [consoleTerminate] WiredTigerKVEngine shutting down
2016-10-13T18:18:45.116+0200 I STORAGE  [consoleTerminate] shutdown: removing fs lock...
2016-10-13T18:18:45.117+0200 I CONTROL  [consoleTerminate] dbexit:  rc: 12

Now your database is prepared and you can start the service using

C:\>net start MongoDB
The MongoDB service is starting.
The MongoDB service was started successfully.

How to install node.js as windows service?

I found the thing so useful that I built an even easier to use wrapper around it (npm, github).

Installing it:

npm install -g qckwinsvc

Installing your service:

qckwinsvc

prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed

Uninstalling your service:

qckwinsvc --uninstall

prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled

Elevating process privilege programmatically?

You should use Impersonation to elevate the state.

WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();

Don't forget to undo the impersonated context when you are done.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

If you are running a website, you could also try to set your application pool to disable 32-bit Applications (under advanced settings of a pool).

Windows command to get service status?

Well i see "Nick Kavadias" telling this:

"according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST ..."

If you type in Windows XP this:

NET START /LIST

you will get an error, just type instead

NET START

The /LIST is only for Windows 2000... If you fully read such web you would see the /LIST is only on Windows 2000 section.

Hope this helps!!!

How to create windows service from java jar?

Tanuki changed license of jsw some time ago, if I was to begin a project, I would use Yet Another Java Service Wrapper, http://yajsw.sourceforge.net/ that is more or less an open source implementation that mimics JWS, and then builds on it and improves it even further.

EDIT: I have been using YAJSW for several years on several platorms (Windows, several linuxes...) and it is great, development is ongoing.

Error 5 : Access Denied when starting windows service

Your code may be running in the security context of a user that is not allowed to start a service.

Since you are using WCF, I am guessing that you are in the context of NETWORK SERVICE.

see: http://support.microsoft.com/kb/256299

How to make a .NET Windows Service start right after the installation?

To start it right after installation, I generate a batch file with installutil followed by sc start

It's not ideal, but it works....

How to run console application from Windows Service?

Services are required to connect to the Service Control Manager and provide feedback at start up (ie. tell SCM 'I'm alive!'). That's why C# application have a different project template for services. You have two alternatives:

  • wrapp your exe on srvany.exe, as described in KB How To Create a User-Defined Service
  • have your C# app detect when is launched as a service (eg. command line param) and switch control to a class that inherits from ServiceBase and properly implements a service.

How to create a windows service from java app

Apache Commons Daemon is a good alternative. It has Procrun for windows services, and Jsvc for unix daemons. It uses less restrictive Apache license, and Apache Tomcat uses it as a part of itself to run on Windows and Linux! To get it work is a bit tricky, but there is an exhaustive article with working example.

Besides that, you may look at the bin\service.bat in Apache Tomcat to get an idea how to setup the service. In Tomcat they rename the Procrun binaries (prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe).

Something I struggled with using Procrun, your start and stop methods must accept the parameters (String[] argv). For example "start(String[] argv)" and "stop(String[] argv)" would work, but "start()" and "stop()" would cause errors. If you can't modify those calls, consider making a bootstrapper class that can massage those calls to fit your needs.

Error 1053 the service did not respond to the start or control request in a timely fashion

My issue was due to target framework mentioned in windows service config was

<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
 </startup>

and my server in which I tried to install windows service was not supported for this .Net version.

Changing which , I could able to resolve the issue.

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

Install a Windows service using a Windows command prompt?

Navigate to the installutil.exe in your .net folder (for .net 4 it's C:\Windows\Microsoft.NET\Framework\v4.0.30319 for example) and use it to install your service, like this:

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" "c:\myservice.exe"

How might I schedule a C# Windows Service to perform a task daily?

The way I accomplish this is with a timer.

Run a server timer, have it check the Hour/Minute every 60 seconds.

If it's the right Hour/Minute, then run your process.

I actually have this abstracted out into a base class I call OnceADayRunner.

Let me clean up the code a bit and I'll post it here.

    private void OnceADayRunnerTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (NDC.Push(GetType().Name))
        {
            try
            {
                log.DebugFormat("Checking if it's time to process at: {0}", e.SignalTime);
                log.DebugFormat("IsTestMode: {0}", IsTestMode);

                if ((e.SignalTime.Minute == MinuteToCheck && e.SignalTime.Hour == HourToCheck) || IsTestMode)
                {
                    log.InfoFormat("Processing at: Hour = {0} - Minute = {1}", e.SignalTime.Hour, e.SignalTime.Minute);
                    OnceADayTimer.Enabled = false;
                    OnceADayMethod();
                    OnceADayTimer.Enabled = true;

                    IsTestMode = false;
                }
                else
                {
                    log.DebugFormat("Not correct time at: Hour = {0} - Minute = {1}", e.SignalTime.Hour, e.SignalTime.Minute);
                }
            }
            catch (Exception ex)
            {
                OnceADayTimer.Enabled = true;
                log.Error(ex.ToString());
            }

            OnceADayTimer.Start();
        }
    }

The beef of the method is in the e.SignalTime.Minute/Hour check.

There are hooks in there for testing, etc. but this is what your elapsed timer could look like to make it all work.

How do I restart a service on a remote machine in Windows?

You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.

If you wish to use the command line only, you can use

sc \\machine stop <service>

How can a windows service programmatically restart itself?

The easiest way is to have a batch file with:

net stop net start

and add the file to the scheduler with your desired time interval

Map a network drive to be used by a service

There is a good answer here: https://superuser.com/a/651015/299678

I.e. You can use a symbolic link, e.g.

mklink /D C:\myLink \\127.0.0.1\c$

How to access full source of old commit in BitBucket?

I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well.

When you're browsing your code the URL is something like:

https://bitbucket.org/user/repo/src/

and by adding a commit hash at the end like this:

https://bitbucket.org/user/repo/src/a0328cb

You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.

How to display a Windows Form in full screen on top of the taskbar?

Use:

FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;

And then your form is placed over the taskbar.

How to remove an element from the flow?

None?

I mean, other than removing it from the layout entirely with display: none, I'm pretty sure that's it.

Are you facing a particular situation in which position: absolute is not a viable solution?

Intellij reformat on file save

I set it to automatically clean up on check-in, which is usually good enough for me. If something is too ugly, I'll just hit the shortcut (Ctrl-Alt-L, Return). And I see they have an option for auto-formatting pasted code, although I've never used that.

Remove spaces from std::string in C++

  string str = "2C F4 32 3C B9 DE";
  str.erase(remove(str.begin(),str.end(),' '),str.end());
  cout << str << endl;

output: 2CF4323CB9DE

how to modify an existing check constraint?

You have to drop it and recreate it, but you don't have to incur the cost of revalidating the data if you don't want to.

alter table t drop constraint ck ;
alter table t add constraint ck check (n < 0) enable novalidate;

The enable novalidate clause will force inserts or updates to have the constraint enforced, but won't force a full table scan against the table to verify all rows comply.

Creating a new directory in C

I want to write a program that (...) creates the directory and a (...) file inside of it

because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.

void rek_mkdir(char *path) {
    char *sep = strrchr(path, '/');
    if(sep != NULL) {
        *sep = 0;
        rek_mkdir(path);
        *sep = '/';
    }
    if(mkdir(path, 0777) && errno != EEXIST)
        printf("error while trying to create '%s'\n%m\n", path); 
}

FILE *fopen_mkdir(char *path, char *mode) {
    char *sep = strrchr(path, '/');
    if(sep) { 
        char *path0 = strdup(path);
        path0[ sep - path ] = 0;
        rek_mkdir(path0);
        free(path0);
    }
    return fopen(path,mode);
}

JavaScript Chart.js - Custom data formatting to display on tooltip

You need to make use of Label Callback. A common example to round data values, the following example rounds the data to two decimal places.

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {
                    var label = data.datasets[tooltipItem.datasetIndex].label || '';

                    if (label) {
                        label += ': ';
                    }
                    label += Math.round(tooltipItem.yLabel * 100) / 100;
                    return label;
                }
            }
        }
    }
});

Now let me write the scenario where I used the label callback functionality.

Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart. In my case it's 4, that's why length of datasets array is 4.

enter image description here

In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.

To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.

  callbacks: {
    label: function (tooltipItem, data) {
      console.log('data', data);
      console.log('tooltipItem', tooltipItem);
      let updatedToolTip: number;
      if (tooltipItem.datasetIndex == 0) {
        updatedToolTip = tooltipItem.yLabel;
      }
      if (tooltipItem.datasetIndex == 1) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
      }
      if (tooltipItem.datasetIndex == 2) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
      }
      if (tooltipItem.datasetIndex == 3) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
      }
      return updatedToolTip;
    }
  } 

Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.

How to resolve "gpg: command not found" error during RVM installation?

You can also use:

$ sudo gem install rvm

It should give you the following output:

Fetching: rvm-1.11.3.9.gem (100%)
Successfully installed rvm-1.11.3.9
Parsing documentation for rvm-1.11.3.9
Installing ri documentation for rvm-1.11.3.9
1 gem installed

Converting a float to a string without rounding it

Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses).

For example:

>>> .1
0.10000000000000001

In this case, you're seeing .1 converted to a string using repr:

>>> repr(.1)
'0.10000000000000001'

I believe python chops off the last few digits when you use str() in order to work around this problem, but it's a partial workaround that doesn't substitute for understanding what's going on.

>>> str(.1)
'0.1'

I'm not sure exactly what problems "rounding" is causing you. Perhaps you would do better with string formatting as a way to more precisely control your output?

e.g.

>>> '%.5f' % .1
'0.10000'
>>> '%.5f' % .12345678
'0.12346'

Documentation here.

Redefining the Index in a Pandas DataFrame object

If you don't want 'a' in the index

In :

col = ['a','b','c']

data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

data

Out:

    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In :

data2 = data.set_index('a')

Out:

     b   c
a
1    2   3
10  11  12
20  21  22

In :

data2.index.name = None

Out:

     b   c
 1   2   3
10  11  12
20  21  22

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

$ gcc test.c -o testc
$ file testc
testc: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ldd testc 
    linux-vdso.so.1 =>  (0x00007fff227ff000)
    libc.so.6 => /lib64/libc.so.6 (0x000000391f000000)
    /lib64/ld-linux-x86-64.so.2 (0x000000391ec00000)
$ gcc -m32 test.c -o testc
$ file testc
testc: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ldd testc
    linux-gate.so.1 =>  (0x009aa000)
    libc.so.6 => /lib/libc.so.6 (0x00780000)
    /lib/ld-linux.so.2 (0x0075b000)

In short: use the -m32 flag to compile a 32-bit binary.

Also, make sure that you have the 32-bit versions of all required libraries installed (in my case all I needed on Fedora was glibc-devel.i386)

List of Timezone IDs for use with FindTimeZoneById() in C#?

List of time zone identifiers, included by default in Windows XP and Vista: Finding the Time Zones Defined on a Local System

iOS - Ensure execution on main thread

This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!

bool to int conversion

Section 6.5.8.6 of the C standard says:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.

Redirect to Action by parameter mvc

This should work!

[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index", "ProductImageManeger", new  { id = id });
}

[HttpGet]
public ViewResult Index(int id)
{
    return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}

Notice that you don't have to pass the name of view if you are returning the same view as implemented by the action.

Your view should inherit the model as this:

@model <Your class name>

You can then access your model in view as:

@Model.<property_name>

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

Multiple argument IF statement - T-SQL

Not sure what the problem is, this seems to work just fine?

DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        Select 'This works just fine' as Msg
    END
Else
    BEGIN
    Select 'No Lol' as Msg
    END

How do I analyze a .hprof file?

You can use JHAT, The Java Heap Analysis Tool provided by default with the JDK. It's command line but starts a web server/browser you use to examine the memory. Not the most user friendly, but at least it's already installed most places you'll go. A very useful view is the "heap histogram" link at the very bottom.

ex: jhat -port 7401 -J-Xmx4G dump.hprof

jhat can execute OQL "these days" as well (bottom link "execute OQL")

How can I get a list of all classes within current module in Python?

What about

g = globals().copy()
for name, obj in g.iteritems():

?

How to get UTC+0 date in Java 8?

In java8, I would use the Instant class which is already in UTC and is convenient to work with.

import java.time.Instant;

Instant ins = Instant.now();
long ts = ins.toEpochMilli();

Instant ins2 = Instant.ofEpochMilli(ts)

Alternatively, you can use the following:

import java.time.*;

Instant ins = Instant.now(); 

OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));

Back to Instant

Instant ins4 = Instant.from(odt);

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

My solution is similar to Payam's, except I am using

//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());

If you hit the "3 dots" on the folder and click "Edit"

enter image description here

Then set Pre-Request Scripts for the all calls, so the global variable is always available.

enter image description here

When to use "ON UPDATE CASCADE"

I think you've pretty much nailed the points!

If you follow database design best practices and your primary key is never updatable (which I think should always be the case anyway), then you never really need the ON UPDATE CASCADE clause.

Zed made a good point, that if you use a natural key (e.g. a regular field from your database table) as your primary key, then there might be certain situations where you need to update your primary keys. Another recent example would be the ISBN (International Standard Book Numbers) which changed from 10 to 13 digits+characters not too long ago.

This is not the case if you choose to use surrogate (e.g. artifically system-generated) keys as your primary key (which would be my preferred choice in all but the most rare occasions).

So in the end: if your primary key never changes, then you never need the ON UPDATE CASCADE clause.

Marc

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

How to make PopUp window in java

The same answer : JOptionpane with an example :)

package experiments;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class CreateDialogFromOptionPane {

    public static void main(final String[] args) {
        final JFrame parent = new JFrame();
        JButton button = new JButton();

        button.setText("Click me to show dialog!");
        parent.add(button);
        parent.pack();
        parent.setVisible(true);

        button.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String name = JOptionPane.showInputDialog(parent,
                        "What is your name?", null);
            }
        });
    }
}

enter image description here

JavaScript implementation of Gzip

Edit There appears to be a better LZW solution that handles Unicode strings correctly at http://pieroxy.net/blog/pages/lz-string/index.html (Thanks to pieroxy in the comments).


I don't know of any gzip implementations, but the jsolait library (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the LGPL.

// LZW-compress a string
function lzw_encode(s) {
    var dict = {};
    var data = (s + "").split("");
    var out = [];
    var currChar;
    var phrase = data[0];
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict[phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
            dict[phrase + currChar] = code;
            code++;
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join("");
}

// Decompress an LZW-encoded string
function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code] = oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    return out.join("");
}

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Here's another solution not using date(). not so smart:)

$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How do I get hour and minutes from NSDate?

If you were to use the C library then this could be done:

time_t t;
struct tm * timeinfo;

time (&t);
timeinfo = localtime (&t);

NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);

And using Swift:

var t = time_t()
time(&t)
let x = localtime(&t)

println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")

For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/

tsconfig.json: Build:No inputs were found in config file

If you are using the vs code for editing then try restarting the editor.This scenario fixed my issue.I think it's the issue with editor cache.

Check for file exists or not in sql server?

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END

Updating property value in properties file without deleting other values

Open the output stream and store properties after you have closed the input stream.

FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();

FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();

"use database_name" command in PostgreSQL

The basic problem while migrating from MySQL I faced was, I thought of the term database to be same in PostgreSQL also, but it is not. So if we are going to switch the database from our application or pgAdmin, the result would not be as expected. As in my case, we have separate schemas (Considering PostgreSQL terminology here.) for each customer and separate admin schema. So in application, I have to switch between schemas.

For this, we can use the SET search_path command. This does switch the current schema to the specified schema name for the current session.

example:

SET search_path = different_schema_name;

This changes the current_schema to the specified schema for the session. To change it permanently, we have to make changes in postgresql.conf file.

Linux: where are environment variables stored?

If you want to put the environment for system-wide use you can do so with /etc/environment file.

BeautifulSoup: extract text from anchor tag

This will help:

from bs4 import BeautifulSoup

data = '''<div class="image">
        <a href="http://www.example.com/eg1">Content1<img  
        src="http://image.example.com/img1.jpg" /></a>
        </div>
        <div class="image">
        <a href="http://www.example.com/eg2">Content2<img  
        src="http://image.example.com/img2.jpg" /> </a>
        </div>'''

soup = BeautifulSoup(data)

for div in soup.findAll('div', attrs={'class':'image'}):
    print(div.find('a')['href'])
    print(div.find('a').contents[0])
    print(div.find('img')['src'])

If you are looking into Amazon products then you should be using the official API. There is at least one Python package that will ease your scraping issues and keep your activity within the terms of use.

Concatenate chars to form String in java

Use the Character.toString(char) method.

Example of SOAP request authenticated with WS-UsernameToken

The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:

Digest Password Support

The WSS 1.1 Username Token Profile allows digest passwords to be sent in a wsse:UsernameToken of a SOAP message. Two more optional elements are included in the wsse:UsernameToken in this case: wsse:Nonce and wsse:Created. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:

Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )

This is how a UsernameToken with Digest Password looks like:

<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c">
   <wsse:Username>Alice</wsse:Username>
   <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password>
   <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce>
   <wsu:Created>2008-04-28T10:02:11Z</wsu:Created>
</wsse:UsernameToken>

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

For me, this problem was solved by uninstalling the latest version of node and replacing it with the LTS version.

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I have no idea why the other answers didn't work for me (error 500) but this works

@GetMapping("")
public String getAll() {
    List<Entity> entityList = entityManager.findAll();
    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return entities.toString();
}

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Make sure:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

is the first <meta> tag on your page, otherwise IE may not respect it.

Alternatively, the problem may be that IE is using Enterprise Mode for this website:

  • Your question mentioned that the console shows: HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.
  • If so you may need to disable enterprise mode (or like this) or turn it off for that website from the Tools menu in IE.
  • However Enterprise Mode should in theory be overridden by the X-UA-Compatible tag, but IE might have a bug...

Auto height div with overflow and scroll when needed

Try this:
CSS:

#content {
  margin: 0 auto;
  border: 1px solid red;
  width:800px;
  position:absolute;
  bottom:0px;
  top:0px;
  overflow:auto
}

HTML:

<body>
<div id="content">
...content goes here...
</div>
<body>

If you don't like absolute positioning in this case, just can play with making a parent and child div to this one, both with position:relative.

EDIT: Below should work (I just put the css inline for the moment):

<div style="margin:0 auto; width:800px; height:100%; overflow:hidden">
<div style="border: 1px solid red; width:800px; position:absolute; bottom:0px; top:0px; overflow:auto">
...content goes here...
</div>
</div>

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

<context:annotation-config> declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.

<mvc:annotation-driven /> declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping, @Controller, although support for those is the default behaviour), as well as adding support for declarative validation via @Valid and message body marshalling with @RequestBody/ResponseBody.

how to specify new environment location for conda create

You can create it like this

conda create --prefix C:/tensorflow2 python=3.7

and you don't have to move to that folder to activate it.

# To activate this environment, use:
# > activate C:\tensorflow2

As you see I do it like this.

D:\Development_Avector\PycharmProjects\TensorFlow>activate C:\tensorflow2

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>conda --version
conda 4.5.13

Compare a string using sh shell

-eq is the shell comparison operator for comparing integers. For comparing strings you need to use =.

How can I show/hide component with JSF?

Generally, you need to get a handle to the control via its clientId. This example uses a JSF2 Facelets view with a request-scope binding to get a handle to the other control:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
  <h:head><title>Show/Hide</title></h:head>
  <h:body>
    <h:form>
      <h:button value="toggle"
               onclick="toggle('#{requestScope.foo.clientId}'); return false;" />
      <h:inputText binding="#{requestScope.foo}" id="x" style="display: block" />
    </h:form>
    <script type="text/javascript">
      function toggle(id) {
        var element = document.getElementById(id);
        if(element.style.display == 'block') {
          element.style.display = 'none';
        } else {
          element.style.display = 'block'
        }
      }
    </script>
  </h:body>
</html>

Exactly how you do this will depend on the version of JSF you're working on. See this blog post for older JSF versions: JSF: working with component identifiers.

c# search string in txt file

If you whant only one first string, you can use simple for-loop.

var lines = File.ReadAllLines(pathToTextFile);

var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
   if(!firstFound && lines[index].Contains("CustomerEN"))
   {
      firstFound = true;
   }
   if(firstFound && lines[index].Contains("CustomerCh"))
   {
      //do, what you want, and exit the loop
      // return lines[index];
   }
}

Using moment.js to convert date to string "MM/dd/yyyy"

StartDate = moment(StartDate).format('MM-YYYY');

...and MySQL date format:

StartDate = moment(StartDate).format('YYYY-MM-DD');

Incrementing in C++ - When to use x++ or ++x?

You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.

An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.

Edit: fixed the mixup of prefix and suffix notation

HTTP Get with 204 No Content: Is that normal

Http GET returning 204 is perfectly fine, and so is returning 404.

The important thing is that you define the design standards/guidelines for your API, so that all your endpoints use status codes consistently.

For example:

  • you may indicate that a GET endpoint that returns a collection of resources will return 204 if the collection is empty. In this case GET /complaints/year/2019/month/04 may return 204 if there are no complaints filed in April 2019. This is not an error on the client side, so we return a success status code (204). OTOH, GET /complaints/12345 may return 404 if complaint number 12345 doesn't exist.
  • if your API uses HATEOAS, 204 is probably a bad idea because the response should contain links to navigate to other states.

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

Determine the path of the executing BASH script

Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:

prg=$0
if [ ! -e "$prg" ]; then
  case $prg in
    (*/*) exit 1;;
    (*) prg=$(command -v -- "$prg") || exit;;
  esac
fi
dir=$(
  cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit 

printf '%s\n' "$prg"

How to write a simple Java program that finds the greatest common divisor between two numbers?

Now, I just started programing about a week ago, so nothing fancy, but I had this as a problem and came up with this, which may be easier for people who are just getting into programing to understand. It uses Euclid's method like in previous examples.

public class GCD {
  public static void main(String[] args){
    int x = Math.max(Integer.parseInt(args[0]),Integer.parseInt(args[1]));    
    int y = Math.min(Integer.parseInt(args[0]),Integer.parseInt(args[1]));     
    for (int r = x % y; r != 0; r = x % y){
      x = y;
      y = r;
    }
    System.out.println(y);
  }
}

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

Check if a time is between two times (time DataType)

This should also work (even in SQL-Server 2005):

SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
  AND Created <  DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))

DEMO

RESTful call in Java

If you are calling a RESTful service from a Service Provider (e.g Facebook, Twitter), you can do it with any flavour of your choice:

If you don't want to use external libraries, you can use java.net.HttpURLConnection or javax.net.ssl.HttpsURLConnection (for SSL), but that is call encapsulated in a Factory type pattern in java.net.URLConnection. To receive the result, you will have to connection.getInputStream() which returns you an InputStream. You will then have to convert your input stream to string and parse the string into it's representative object (e.g. XML, JSON, etc).

Alternatively, Apache HttpClient (version 4 is the latest). It's more stable and robust than java's default URLConnection and it supports most (if not all) HTTP protocol (as well as it can be set to Strict mode). Your response will still be in InputStream and you can use it as mentioned above.


Documentation on HttpClient: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

Random strings in Python

try importing the below package from random import*

What is the difference between user variables and system variables?

Environment variables are 'evaluated' (ie. they are attributed) in the following order:

  1. System variables
  2. Variables defined in autoexec.bat
  3. User variables

Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone). A child process inherits the environment variables of its parent process by default.

Programs started by the command processor inherit the command processor's environment variables.

Environment variables specify search paths for files, directories for temporary files, application-specific options, and other similar information. The system maintains an environment block for each user and one for the computer. The system environment block represents environment variables for all users of the particular computer. A user's environment block represents the environment variables the system maintains for that particular user, including the set of system environment variables.

Constructor of an abstract class in C#

an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.

How to create a zip archive of a directory in Python?

For adding compression to the resulting zip file, check out this link.

You need to change:

zip = zipfile.ZipFile('Python.zip', 'w')

to

zip = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)

Accessing nested JavaScript objects and arrays by string path

You can manage to obtain value of a deep object member with dot notation without any external JavaScript library with the simple following trick:

new Function('_', 'return _.' + path)(obj);

In your case to obtain value of part1.name from someObject just do:

new Function('_', 'return _.part1.name')(someObject);

Here is a simple fiddle demo: https://jsfiddle.net/harishanchu/oq5esowf/

Change the color of a checked menu item in a navigation drawer

Here's how you can do it in your Activity's onCreate method:

NavigationView navigationView = findViewById(R.id.nav_view);
ColorStateList csl = new ColorStateList(
    new int[][] {
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_checked}  // checked
    },
    new int[] {
        Color.BLACK,
        Color.RED
    }
);
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl);

Retrieving Property name from lambda expression

Starting with .NET 4.0 you can use ExpressionVisitor to find properties:

class ExprVisitor : ExpressionVisitor {
    public bool IsFound { get; private set; }
    public string MemberName { get; private set; }
    public Type MemberType { get; private set; }
    protected override Expression VisitMember(MemberExpression node) {
        if (!IsFound && node.Member.MemberType == MemberTypes.Property) {
            IsFound = true;
            MemberName = node.Member.Name;
            MemberType = node.Type;
        }
        return base.VisitMember(node);
    }
}

Here is how you use this visitor:

var visitor = new ExprVisitor();
visitor.Visit(expr);
if (visitor.IsFound) {
    Console.WriteLine("First property in the expression tree: Name={0}, Type={1}", visitor.MemberName, visitor.MemberType.FullName);
} else {
    Console.WriteLine("No properties found.");
}

?: ?? Operators Instead Of IF|ELSE

The ?: Operator returns one of two values depending on the value of a Boolean expression.

Condition-Expression ? Expression1 : Expression2

Find here more on ?: operator, also know as a Ternary Operator:

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app perfectly

Using a dispatch_once singleton model in Swift

Just for reference, here is an example Singleton implementation of Jack Wu/hpique's Nested Struct implementation. The implementation also shows how archiving could work, as well as some accompanying functions. I couldn't find this complete of an example, so hopefully this helps somebody!

import Foundation

class ItemStore: NSObject {

    class var sharedStore : ItemStore {
        struct Singleton {
            // lazily initiated, thread-safe from "let"
            static let instance = ItemStore()
        }
        return Singleton.instance
    }

    var _privateItems = Item[]()
    // The allItems property can't be changed by other objects
    var allItems: Item[] {
        return _privateItems
    }

    init() {
        super.init()
        let path = itemArchivePath
        // Returns "nil" if there is no file at the path
        let unarchivedItems : AnyObject! = NSKeyedUnarchiver.unarchiveObjectWithFile(path)

        // If there were archived items saved, set _privateItems for the shared store equal to that
        if unarchivedItems {
            _privateItems = unarchivedItems as Array<Item>
        } 

        delayOnMainQueueFor(numberOfSeconds: 0.1, action: {
            assert(self === ItemStore.sharedStore, "Only one instance of ItemStore allowed!")
        })
    }

    func createItem() -> Item {
        let item = Item.randomItem()
        _privateItems.append(item)
        return item
    }

    func removeItem(item: Item) {
        for (index, element) in enumerate(_privateItems) {
            if element === item {
                _privateItems.removeAtIndex(index)
                // Delete an items image from the image store when the item is 
                // getting deleted
                ImageStore.sharedStore.deleteImageForKey(item.itemKey)
            }
        }
    }

    func moveItemAtIndex(fromIndex: Int, toIndex: Int) {
        _privateItems.moveObjectAtIndex(fromIndex, toIndex: toIndex)
    }

    var itemArchivePath: String {
        // Create a filepath for archiving
        let documentDirectories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        // Get the one document directory from that list
        let documentDirectory = documentDirectories[0] as String
        // append with the items.archive file name, then return
        return documentDirectory.stringByAppendingPathComponent("items.archive")
    }

    func saveChanges() -> Bool {
        let path = itemArchivePath
        // Return "true" on success
        return NSKeyedArchiver.archiveRootObject(_privateItems, toFile: path)
    }
}

And if you didn't recognize some of those functions, here is a little living Swift utility file I've been using:

import Foundation
import UIKit

typealias completionBlock = () -> ()

extension Array {
    func contains(#object:AnyObject) -> Bool {
        return self.bridgeToObjectiveC().containsObject(object)
    }

    func indexOf(#object:AnyObject) -> Int {
        return self.bridgeToObjectiveC().indexOfObject(object)
    }

    mutating func moveObjectAtIndex(fromIndex: Int, toIndex: Int) {
        if ((fromIndex == toIndex) || (fromIndex > self.count) ||
            (toIndex > self.count)) {
                return
        }
        // Get object being moved so it can be re-inserted
        let object = self[fromIndex]

        // Remove object from array
        self.removeAtIndex(fromIndex)

        // Insert object in array at new location
        self.insert(object, atIndex: toIndex)
    }
}

func delayOnMainQueueFor(numberOfSeconds delay:Double, action closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue()) {
            closure()
    }
}

'IF' in 'SELECT' statement - choose output value based on column values

SELECT id, amount
FROM report
WHERE type='P'

UNION

SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'

ORDER BY id;

Change Image of ImageView programmatically in Android

You can use

val drawableCompat = ContextCompat.getDrawable(context, R.drawable.ic_emoticon_happy)

or in java java

Drawable drawableCompat = ContextCompat.getDrawable(getContext(), R.drawable.ic_emoticon_happy)

Setting selected values for ng-options bound select elements

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.

<select 
    ng-model="Choice.SelectedOption"                 
    ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>

Updated fiddle http://jsfiddle.net/gFCzV/34/

Reading binary file and looping over each byte

if you are looking for something speedy, here's a method I've been using that's worked for years:

from array import array

with open( path, 'rb' ) as file:
    data = array( 'B', file.read() ) # buffer the file

# evaluate it's data
for byte in data:
    v = byte # int value
    c = chr(byte)

if you want to iterate chars instead of ints, you can simply use data = file.read(), which should be a bytes() object in py3.

correct quoting for cmd.exe for multiple arguments

Note the "" at the beginning and at the end!

Run a program and pass a Long Filename

cmd /c write.exe "c:\sample documents\sample.txt"

Spaces in Program Path

cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in Program Path + parameters

cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2

Spaces in Program Path + parameters with spaces

cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch Demo1 and then Launch Demo2

cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

CMD.exe (Command Shell)

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

On Android >=6.0, We have to request permission runtime.

Step1: add in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Step2: Request permission.

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
    //TODO
}

Step3: Handle callback when you request permission.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

Edit: Read official guide here Requesting Permissions at Run Time

Set keyboard caret position in html textbox

I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.

function setCaretPosition(elem, caretPos) {
    var range;

    if (elem.createTextRange) {
        range = elem.createTextRange();
        range.move('character', caretPos);
        range.select();
    } else {
        elem.focus();
        if (elem.selectionStart !== undefined) {
            elem.setSelectionRange(caretPos, caretPos);
        }
    }
}

Clean out Eclipse workspace metadata

One of the things that you might want to try out is starting eclipse with the -clean option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.

However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.

See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.

Show message box in case of exception

        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }

Regex match text between tags

Try

str.match(/<b>(.*?)<\/b>/g);

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

Get Current Session Value in JavaScript?

The session is a server side thing, you cannot access it using jQuery. You can write an Http handler (that will share the sessionid if any) and return the value from there using $.ajax.

ASP.NET Core - Swashbuckle not creating swagger.json file

Try to follow these steps, easy and clean.

  1. Check your console are you getting any error like "Ambiguous HTTP method for action. Actions require an explicit HttpMethod binding for Swagger 2.0."
  2. If YES: Reason for this error: Swagger expects

each endpoint should have the method (get/post/put/delete)

. Solution:

Revisit your each and every controller and make sure you have added expected method.

(or you can just see in console error which controller causing ambiguity)

  1. If NO. Please let us know your issue and solution if you have found any.

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

I did this:

import re

def requirements(filename):
    with open(filename) as f:
        ll = f.read().splitlines()
    d = {}
    for l in ll:
        k, v = re.split(r'==|>=', l)
        d[k] = v
    return d

def packageInfo():
    try:
        from pip._internal.operations import freeze
    except ImportError:
        from pip.operations import freeze

    d = {}
    for kv in freeze.freeze():
        k, v = re.split(r'==|>=', kv)
        d[k] = v
    return d

req = getpackver('requirements.txt')
pkginfo = packageInfo()

for k, v in req.items():
    print(f'{k:<16}: {v:<6} -> {pkginfo[k]}')

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

From IEEE floating-point exceptions in C++ :

This page will answer the following questions.

  • My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
  • How can I tell if a number is really a number and not a NaN or an infinity?
  • How can I find out more details at runtime about kinds of NaNs and infinities?
  • Do you have any sample code to show how this works?
  • Where can I learn more?

These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.

Debugging 1.#IND, 1.#INF, nan, and inf

If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.

Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.

In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.

How to remove all the null elements inside a generic list in one go?

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);

Loop through an array in JavaScript

var obj = ["one","two","three"];

for(x in obj){
    console.log(obj[x]);
}

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

How can I list (ls) the 5 last modified files in a directory?

Try using head or tail. If you want the 5 most-recently modified files:

ls -1t | head -5

The -1 (that's a one) says one file per line and the head says take the first 5 entries.

If you want the last 5 try

ls -1t | tail -5

How to connect wireless network adapter to VMWare workstation?

Change your network adapter to a bridged connection, this will directly connect to your computers physical network.

Python loop for inside lambda

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')

Make a borderless form movable?

I was trying to make a borderless windows form movable which contained a WPF Element Host control and a WPF User control.

I ended up with a stack panel called StackPanel in my WPF user control which seemed the logical thing to try click on to move. Trying junmats's code worked when I moved the mouse slowly, but if I moved the mouse faster, the mouse would move off the form and the form would be stuck somewhere mid move.

This improved on his answer for my situation using CaptureMouse and ReleaseCaptureMouse and now the mouse does not move off the form while moving it even if I move it quickly.

private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
{
    _start_point = e.GetPosition(this);
    StackPanel.CaptureMouse();
}

private void StackPanel_MouseUp(object sender, MouseButtonEventArgs e)
{
    StackPanel.ReleaseMouseCapture();
}

private void StackPanel_MouseMove(object sender, MouseEventArgs e)
{
    if (StackPanel.IsMouseCaptured)
    {
        var p = _form.GetMousePositionWindowsForms();
        _form.Location = new System.Drawing.Point((int)(p.X - this._start_point.X), (int)(p.Y - this._start_point.Y));
    }
}

    //Global variables;
    private Point _start_point = new Point(0, 0);

How can I close a window with Javascript on Mozilla Firefox 3?

For security reasons, your script cannot close a window/tab that it did not open.

The solution is to present the age prompt at an earlier point in the navigation history. Then, you can choose to allow them to enter your site or not based on their input.

Instead of closing the page that presents the prompt, you can simply say, "Sorry", or perhaps redirect the user to their homepage.

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

Call Stored Procedure within Create Trigger in SQL Server

The following should do the trick - Only SqlServer


Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN

SET NOCOUNT ON;

Declare @id int
DECLARE @cDate as DateTime
    set @cDate =(select Getdate())

select @id=deleted.Catagory_id from deleted
print @cDate

execute dbo.psp_Update_Category @id

END

Alter PROCEDURE dbo.psp_Update_Category
@id int
AS
BEGIN

DECLARE @cDate as DateTime
    set @cDate =(select Getdate())
    --Update Catagory_Master Set Modify_date=''+@cDate+'' Where Catagory_ID=@id   --@UserID
    Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END 

Filter element based on .data() key/value

your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.

var $previous = $('.navlink').filter(function() { 
  return $(this).data("selected") == true 
});

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

Simply uninstalling and reinstalling openssl with homebrew solved this issue for me.

brew uninstall --force openssl

brew install openssl

How to read and write excel file

For reading data from .xlsx workbooks we need to use XSSFworkbook classes.

XSSFWorkbook xlsxBook = new XSSFWorkbook(fis);

XSSFSheet sheet = xlsxBook.getSheetAt(0); etc.

We need to use Apache-poi 3.9 @ http://poi.apache.org/

For detailed info with example visit : http://java-recent.blogspot.in

getting integer values from textfield

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

Angular 2 change event on every keypress

For Reactive Forms, you can subscribe to the changes made to all fields or just a particular field.

Get all changes of a FormGroup:

this.orderForm.valueChanges.subscribe(value => {
    console.dir(value);
});

Get the change of a specific field:

this.orderForm.get('orderPriority').valueChanges.subscribe(value => {
    console.log(value);
  });

Java, How do I get current index/key in "for each" loop

###################################################
###################################################
###################################################
AVOID THIS
###################################################
###################################################
###################################################

/*for (Song s: songList){
    System.out.println(s + "," + songList.indexOf(s); 
}*/

it is possible in linked list.

you have to make toString() in song class. if you don't it will print out reference of the song.

probably irrelevant for you by now. ^_^

java.math.BigInteger cannot be cast to java.lang.Long

Your error might be in this line:

List<Long> result = query.list();

where query.list() is returning a BigInteger List instead of Long list. Try to change it to.

List<BigInteger> result = query.list();

Limit characters displayed in span

use js:

 $(document).ready(function ()
   { $(".class-span").each(function(i){
        var len=$(this).text().trim().length;
        if(len>100)
        {
            $(this).text($(this).text().substr(0,100)+'...');
        }
    });
 });

Finding the position of bottom of a div with jquery

The answers so far will work.. if you only want to use the height without padding, borders, etc.

If you would like to account for padding, borders, and margin, you should use .outerHeight.

var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);

How to escape special characters in building a JSON string?

The answer the direct question:
To be safe, replace the required character with \u+4-digit-hex-value

Example: If you want to escape the apostrophe ' replace with \u0027
D'Amico becomes D\u0027Amico

NICE REFERENCE: http://es5.github.io/x7.html#x7.8.4

https://mathiasbynens.be/notes/javascript-escapes

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

http://www.eclipse.org/cdt/ ^Give that a try

I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.

How can I connect to Android with ADB over TCP?

I'm struct at the same issue but a simple hack adb reverse tcp:<PORT> tcp:<PORT> worked for me. It allows the system to accept tcp requests.

Thank You for reading

How do I list loaded plugins in Vim?

If you use vim-plug (Plug), " A minimalist Vim plugin manager.":

:PlugStatus

That will not only list your plugins but check their status.

Proxy setting for R

On Mac OS, I found the best solution here. Quoting the author, two simple steps are:

1) Open Terminal and do the following:

export http_proxy=http://staff-proxy.ul.ie:8080
export HTTP_PROXY=http://staff-proxy.ul.ie:8080

2) Run R and do the following:

Sys.setenv(http_proxy="http://staff-proxy.ul.ie:8080")

double-check this with:

Sys.getenv("http_proxy")

I am behind university proxy, and this solution worked perfectly. The major issue is to export the items in Terminal before running R, both in upper- and lower-case.

Spring MVC Controller redirect using URL parameters instead of in response

@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
    if (!validate(appUrl)) {
       redirectAttrs.addFlashAttribute("error", "Validation failed");
    }
    return "redirect:/apps/add"
} 

@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
    String error = model.asMap().get("error");
}

Countdown timer using Moment js

I thought I'd throw this out there too (no plugins). It counts down for 10 seconds into the future.

_x000D_
_x000D_
    var countDownDate = moment().add(10, 'seconds');_x000D_
_x000D_
      var x = setInterval(function() {_x000D_
        diff = countDownDate.diff(moment());_x000D_
    _x000D_
        if (diff <= 0) {_x000D_
          clearInterval(x);_x000D_
           // If the count down is finished, write some text _x000D_
          $('.countdown').text("EXPIRED");_x000D_
        } else_x000D_
          $('.countdown').text(moment.utc(diff).format("HH:mm:ss"));_x000D_
_x000D_
      }, 1000);
_x000D_
<script src="https://momentjs.com/downloads/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div class="countdown"></div>
_x000D_
_x000D_
_x000D_

How to get just the responsive grid from Bootstrap 3?

Made a Grunt build with the Bootstrap 3.3.5 grid only:

https://github.com/horgen/grunt-builds/tree/master/bootstrap-grid

~10KB minimized.

If you need some other parts from Bootstrap just include them in /src/less/bootstrap.less.

java.text.ParseException: Unparseable date

  • Your formatting pattern fails to match the input string, as noted by other Answers.
  • Your input format is terrible.
  • You are using troublesome old date-time classes that were supplanted years ago by the java.time classes.

ISO 8601

Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.

The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.

Proper time zone name

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Your IST could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your input strings.

String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]

If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST to Asia/Kolkata.

String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

for this small example:

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print (data);

mysock.close()

adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem

Lock, mutex, semaphore... what's the difference?

I will try to cover it with examples:

Lock: One example where you would use lock would be a shared dictionary into which items (that must have unique keys) are added.
The lock would ensure that one thread does not enter the mechanism of code that is checking for item being in dictionary while another thread (that is in the critical section) already has passed this check and is adding the item. If another thread tries to enter a locked code, it will wait (be blocked) until the object is released.

private static readonly Object obj = new Object();

lock (obj) //after object is locked no thread can come in and insert item into dictionary on a different thread right before other thread passed the check...
{
    if (!sharedDict.ContainsKey(key))
    {
        sharedDict.Add(item);
    }
}

Semaphore: Let's say you have a pool of connections, then an single thread might reserve one element in the pool by waiting for the semaphore to get a connection. It then uses the connection and when work is done releases the connection by releasing the semaphore.

Code example that I love is one of bouncer given by @Patric - here it goes:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TheNightclub
{
    public class Program
    {
        public static Semaphore Bouncer { get; set; }

        public static void Main(string[] args)
        {
            // Create the semaphore with 3 slots, where 3 are available.
            Bouncer = new Semaphore(3, 3);

            // Open the nightclub.
            OpenNightclub();
        }

        public static void OpenNightclub()
        {
            for (int i = 1; i <= 50; i++)
            {
                // Let each guest enter on an own thread.
                Thread thread = new Thread(new ParameterizedThreadStart(Guest));
                thread.Start(i);
            }
        }

        public static void Guest(object args)
        {
            // Wait to enter the nightclub (a semaphore to be released).
            Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
            Bouncer.WaitOne();          

            // Do some dancing.
            Console.WriteLine("Guest {0} is doing some dancing.", args);
            Thread.Sleep(500);

            // Let one guest out (release one semaphore).
            Console.WriteLine("Guest {0} is leaving the nightclub.", args);
            Bouncer.Release(1);
        }
    }
}

Mutex It is pretty much Semaphore(1,1) and often used globally (application wide otherwise arguably lock is more appropriate). One would use global Mutex when deleting node from a globally accessible list (last thing you want another thread to do something while you are deleting the node). When you acquire Mutex if different thread tries to acquire the same Mutex it will be put to sleep till SAME thread that acquired the Mutex releases it.

Good example on creating global mutex is by @deepee

class SingleGlobalInstance : IDisposable
{
    public bool hasHandle = false;
    Mutex mutex;

    private void InitMutex()
    {
        string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
        string mutexId = string.Format("Global\\{{{0}}}", appGuid);
        mutex = new Mutex(false, mutexId);

        var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
        var securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);
        mutex.SetAccessControl(securitySettings);
    }

    public SingleGlobalInstance(int timeOut)
    {
        InitMutex();
        try
        {
            if(timeOut < 0)
                hasHandle = mutex.WaitOne(Timeout.Infinite, false);
            else
                hasHandle = mutex.WaitOne(timeOut, false);

            if (hasHandle == false)
                throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
        }
        catch (AbandonedMutexException)
        {
            hasHandle = true;
        }
    }


    public void Dispose()
    {
        if (mutex != null)
        {
            if (hasHandle)
                mutex.ReleaseMutex();
            mutex.Dispose();
        }
    }
}

then use like:

using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
{
    //Only 1 of these runs at a time
    GlobalNodeList.Remove(node)
}

Hope this saves you some time.

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

Difference between Math.Floor() and Math.Truncate()

Math.floor() will always round down ie., it returns LESSER integer. While round() will return the NEAREST integer

math.floor()

Returns the largest integer less than or equal to the specified number.

math.truncate()

Calculates the integral part of a number.

Using numpy to build an array of all combinations of two arrays

It looks like you want a grid to evaluate your function, in which case you can use numpy.ogrid (open) or numpy.mgrid (fleshed out):

import numpy
my_grid = numpy.mgrid[[slice(0,1,0.1)]*6]

Change the "No file chosen":

Try this its just a trick

<input type="file" name="uploadfile" id="img" style="display:none;"/>
<label for="img">Click me to upload image</label>

How it works

It's very simple. the Label element uses the "for" tag to reference to a form's element by id. In this case, we used "img" as the reference key between them. Once it is done, whenever you click on the label, it automatically trigger the form's element click event which is the file element click event in our case. We then make the file element invisible by using display:none and not visibility:hidden so that it doesn't create empty space.

Enjoy coding

Regex for checking if a string is strictly alphanumeric

Considering you want to check for ASCII Alphanumeric characters, Try this: "^[a-zA-Z0-9]*$". Use this RegEx in String.matches(Regex), it will return true if the string is alphanumeric, else it will return false.

public boolean isAlphaNumeric(String s){
    String pattern= "^[a-zA-Z0-9]*$";
    return s.matches(pattern);
}

If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html

The Use of Multiple JFrames: Good or Bad Practice?

If the frames are going to be the same size, why not create the frame and pass the frame then as a reference to it instead.

When you have passed the frame you can then decide how to populate it. It would be like having a method for calculating the average of a set of figures. Would you create the method over and over again?

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to program a fractal?

I would start with something simple, like a Koch Snowflake. It's a simple process of taking a line and transforming it, then repeating the process recursively until it looks neat-o.

Something super simple like taking 2 points (a line) and adding a 3rd point (making a corner), then repeating on each new section that's created.

fractal(p0, p1){
    Pmid = midpoint(p0,p1) + moved some distance perpendicular to p0 or p1;
    fractal(p0,Pmid);
    fractal(Pmid, p1);
}

how to Call super constructor in Lombok

As an option you can use com.fasterxml.jackson.databind.ObjectMapper to initialize a child class from parent

public class A {
    int x;
    int y;
}

public class B extends A {
    int z;
}

ObjectMapper MAPPER = new ObjectMapper(); //it's configurable
MAPPER.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
MAPPER.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

//Then wherever you need to initialize child from parent:
A parent = new A(x, y);
B child = MAPPER.convertValue( parent, B.class);
child.setZ(z);

You can still use any lombok annotations on A and B if you need.

What is the proper declaration of main in C++?

The main function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).

The name main is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.

You can declare a function named main as a member function or in a namespace, but such a function would not be the main function that designates where the program starts.

The main function cannot be declared as static or inline. It also cannot be overloaded; there can be only one function named main in the global namespace.

The main function cannot be used in your program: you are not allowed to call the main function from anywhere in your code, nor are you allowed to take its address.

The return type of main must be int. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main with a return type of void; this is probably the most frequently violated rule concerning the main function).

There are two declarations of main that must be allowed:

int main()               // (1)
int main(int, char*[])   // (2)

In (1), there are no parameters.

In (2), there are two parameters and they are conventionally named argc and argv, respectively. argv is a pointer to an array of C strings representing the arguments to the program. argc is the number of arguments in the argv array.

Usually, argv[0] contains the name of the program, but this is not always the case. argv[argc] is guaranteed to be a null pointer.

Note that since an array type argument (like char*[]) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:

int main(int argc, char* argv[])
int main(int argc, char** argv)

Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.

main() is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return statement in main(): if you let main() return without an explicit return statement, it's the same as if you had written return 0;. The following two main() functions have the same behavior:

int main() { }
int main() { return 0; }

There are two macros, EXIT_SUCCESS and EXIT_FAILURE, defined in <cstdlib> that can also be returned from main() to indicate success and failure, respectively.

The value returned by main() is passed to the exit() function, which terminates the program.

Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main() function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.

How do I use shell variables in an awk script?

Getting shell variables into awk

may be done in several ways. Some are better than others. This should cover most of them. If you have a comment, please leave below.                                                                                    v1.5


Using -v (The best way, most portable)

Use the -v option: (P.S. use a space after -v or it will be less portable. E.g., awk -v var= not awk -vvar=)

variable="line one\nline two"
awk -v var="$variable" 'BEGIN {print var}'
line one
line two

This should be compatible with most awk, and the variable is available in the BEGIN block as well:

If you have multiple variables:

awk -v a="$var1" -v b="$var2" 'BEGIN {print a,b}'

Warning. As Ed Morton writes, escape sequences will be interpreted so \t becomes a real tab and not \t if that is what you search for. Can be solved by using ENVIRON[] or access it via ARGV[]

PS If you like three vertical bar as separator |||, it can't be escaped, so use -F"[|][|][|]"

Example on getting data from a program/function inn to awk (here date is used)

awk -v time="$(date +"%F %H:%M" -d '-1 minute')" 'BEGIN {print time}'

Variable after code block

Here we get the variable after the awk code. This will work fine as long as you do not need the variable in the BEGIN block:

variable="line one\nline two"
echo "input data" | awk '{print var}' var="${variable}"
or
awk '{print var}' var="${variable}" file
  • Adding multiple variables:

awk '{print a,b,$0}' a="$var1" b="$var2" file

  • In this way we can also set different Field Separator FS for each file.

awk 'some code' FS=',' file1.txt FS=';' file2.ext

  • Variable after the code block will not work for the BEGIN block:

echo "input data" | awk 'BEGIN {print var}' var="${variable}"


Here-string

Variable can also be added to awk using a here-string from shells that support them (including Bash):

awk '{print $0}' <<< "$variable"
test

This is the same as:

printf '%s' "$variable" | awk '{print $0}'

P.S. this treats the variable as a file input.


ENVIRON input

As TrueY writes, you can use the ENVIRON to print Environment Variables. Setting a variable before running AWK, you can print it out like this:

X=MyVar
awk 'BEGIN{print ENVIRON["X"],ENVIRON["SHELL"]}'
MyVar /bin/bash

ARGV input

As Steven Penny writes, you can use ARGV to get the data into awk:

v="my data"
awk 'BEGIN {print ARGV[1]}' "$v"
my data

To get the data into the code itself, not just the BEGIN:

v="my data"
echo "test" | awk 'BEGIN{var=ARGV[1];ARGV[1]=""} {print var, $0}' "$v"
my data test

Variable within the code: USE WITH CAUTION

You can use a variable within the awk code, but it's messy and hard to read, and as Charles Duffy points out, this version may also be a victim of code injection. If someone adds bad stuff to the variable, it will be executed as part of the awk code.

This works by extracting the variable within the code, so it becomes a part of it.

If you want to make an awk that changes dynamically with use of variables, you can do it this way, but DO NOT use it for normal variables.

variable="line one\nline two"
awk 'BEGIN {print "'"$variable"'"}'
line one
line two

Here is an example of code injection:

variable='line one\nline two" ; for (i=1;i<=1000;++i) print i"'
awk 'BEGIN {print "'"$variable"'"}'
line one
line two
1
2
3
.
.
1000

You can add lots of commands to awk this way. Even make it crash with non valid commands.


Extra info:

Use of double quote

It's always good to double quote variable "$variable"
If not, multiple lines will be added as a long single line.

Example:

var="Line one
This is line two"

echo $var
Line one This is line two

echo "$var"
Line one
This is line two

Other errors you can get without double quote:

variable="line one\nline two"
awk -v var=$variable 'BEGIN {print var}'
awk: cmd. line:1: one\nline
awk: cmd. line:1:    ^ backslash not last character on line
awk: cmd. line:1: one\nline
awk: cmd. line:1:    ^ syntax error

And with single quote, it does not expand the value of the variable:

awk -v var='$variable' 'BEGIN {print var}'
$variable

More info about AWK and variables

Read this faq.

Should methods in a Java interface be declared with or without a public access modifier?

I disagree with the popular answer, that having public implies that there are other options and so it shouldn't be there. The fact is that now with Java 9 and beyond there ARE other options.

I think instead Java should enforce/require 'public' to be specified. Why? Because the absence of a modifier means 'package' access everywhere else, and having this as a special case is what leads to the confusion. If you simply made it a compile error with a clear message (e.g. "Package access is not allowed in an interface.") we would get rid of the apparent ambiguity that having the option to leave out 'public' introduces.

Note the current wording at: https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4

"A method in the body of an interface may be declared public or private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface."

See that 'private' IS allowed now. I think that last sentence should have been removed from the JLS. It is unfortunate that the "implicitly public" behaviour was ever allowed as it will now likely remain for backward compatibilty and lead to the confusion that the absence of the access modifier means 'public' in interfaces and 'package' elsewhere.

Spring RestTemplate GET with parameters

If you pass non-parametrized params for RestTemplate, you'll have one Metrics for everyone single different URL that you pass, considering the parameters. You would like to use parametrized urls:

http://my-url/action?param1={param1}&param2={param2}

instead of

http://my-url/action?param1=XXXX&param2=YYYY

The second case is what you get by using UriComponentsBuilder class.

One way to implement the first behavior is the following:

Map<String, Object> params = new HashMap<>();
params.put("param1", "XXXX");
params.put("param2", "YYYY");

String url = "http://my-url/action?%s";

String parametrizedArgs = params.keySet().stream().map(k ->
    String.format("%s={%s}", k, k)
).collect(Collectors.joining("&"));

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> entity = new HttpEntity<>(headers);

restTemplate.exchange(String.format(url, parametrizedArgs), HttpMethod.GET, entity, String.class, params);

How is a non-breaking space represented in a JavaScript string?

The jQuery docs for text() says

Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.

I'd use $td.html() instead.

sql server convert date to string MM/DD/YYYY

As of SQL Server 2012+, you can use FORMAT(value, format [, culture ])

Where the format param takes any valid standard format string or custom formatting string

Example:

SELECT FORMAT(GETDATE(), 'MM/dd/yyyy')

Further Reading:

Uncaught (in promise) TypeError: Failed to fetch and Cors error

In my case, the problem was the protocol. I was trying to call a script url with http instead of https.

What's the difference between echo, print, and print_r in PHP?

print and echo are more or less the same; they are both language constructs that display strings. The differences are subtle: print has a return value of 1 so it can be used in expressions whereas echo has a void return type; echo can take multiple parameters, although such usage is rare; echo is slightly faster than print. (Personally, I always use echo, never print.)

var_dump prints out a detailed dump of a variable, including its type and the type of any sub-items (if it's an array or an object). print_r prints a variable in a more human-readable form: strings are not quoted, type information is omitted, array sizes aren't given, etc.

var_dump is usually more useful than print_r when debugging, in my experience. It's particularly useful when you don't know exactly what values/types you have in your variables. Consider this test program:

$values = array(0, 0.0, false, '');

var_dump($values);
print_r ($values);

With print_r you can't tell the difference between 0 and 0.0, or false and '':

array(4) {
  [0]=>
  int(0)
  [1]=>
  float(0)
  [2]=>
  bool(false)
  [3]=>
  string(0) ""
}

Array
(
    [0] => 0
    [1] => 0
    [2] => 
    [3] => 
)

How do I redirect in expressjs while passing some context?

use app.set & app.get

Setting data

router.get(
  "/facebook/callback",
  passport.authenticate("facebook"),
  (req, res) => {
    req.app.set('user', res.req.user)
    return res.redirect("/sign");
  }
);

Getting data

router.get("/sign", (req, res) => {
  console.log('sign', req.app.get('user'))
});

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Try This:

            $.ajax({
                    url:"",
                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    contentType:false,
                    cache: false,
                    processData:false,
                    success:function (msg) {}
                  });

How to configure CORS in a Spring Boot + Spring Security application?

// https://docs.spring.io/spring-boot/docs/2.4.2/reference/htmlsingle/#boot-features-cors
@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(final CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("*").allowedHeaders("*");
            }
        };
    }
}

If using Spring Security, set additional:

// https://docs.spring.io/spring-security/site/docs/5.4.2/reference/html5/#cors
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        // ...

        // if Spring MVC is on classpath and no CorsConfigurationSource is provided,
        // Spring Security will use CORS configuration provided to Spring MVC
        http.cors(Customizer.withDefaults());
    }
}

if else in a list comprehension

I just had a similar problem, and found this question and the answers really useful. Here's the part I was confused about. I'm writing it explicitly because no one actually stated it simply in English:

The iteration goes at the end.

Normally, a loop goes

for this many times:
    if conditional: 
        do this thing
    else:
        do something else  

Everyone states the list comprehension part simply as the first answer did,

[ expression for item in list if conditional ] 

but that's actually not what you do in this case. (I was trying to do it that way)

In this case, it's more like this:

[ expression if conditional else other thing for this many times ] 

How to properly URL encode a string in PHP?

Based on what type of RFC standard encoding you want to perform or if you need to customize your encoding you might want to create your own class.

/**
 * UrlEncoder make it easy to encode your URL
 */
class UrlEncoder{
    public const STANDARD_RFC1738 = 1;
    public const STANDARD_RFC3986 = 2;
    public const STANDARD_CUSTOM_RFC3986_ISH = 3;
    // add more here

    static function encode($string, $rfc){
        switch ($rfc) {
            case self::STANDARD_RFC1738:
                return  urlencode($string);
                break;
            case self::STANDARD_RFC3986:
                return rawurlencode($string);
                break;
            case self::STANDARD_CUSTOM_RFC3986_ISH:
                // Add your custom encoding
                $entities = ['%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'];
                $replacements = ['!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"];
                return str_replace($entities, $replacements, urlencode($string));
                break;
            default:
                throw new Exception("Invalid RFC encoder - See class const for reference");
                break;
        }
    }
}

Use example:

$dataString = "https://www.google.pl/search?q=PHP is **great**!&id=123&css=#kolo&[email protected])";

$dataStringUrlEncodedRFC1738 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC1738);
$dataStringUrlEncodedRFC3986 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC3986);
$dataStringUrlEncodedCutom = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_CUSTOM_RFC3986_ISH);

Will output:

string(126) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP+is+%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(130) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP%20is%20%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(86)  "https://www.google.pl/search?q=PHP+is+**great**!&id=123&css=#kolo&[email protected])"

* Find out more about RFC standards: https://datatracker.ietf.org/doc/rfc3986/ and urlencode vs rawurlencode?

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Whilst you certainly can use MySQL's IF() control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE expression instead:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
         ELSE A
       END
WHERE  A IS NOT NULL

Of course, in this specific example it's a little wasteful to set A to itself in the ELSE clause—better entirely to filter such conditions from the UPDATE, via the WHERE clause:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
       END
WHERE  (A > 0 AND A < 1) OR (A > 1 AND A < 2)

(The inequalities entail A IS NOT NULL).

Or, if you want the intervals to be closed rather than open (note that this would set values of 0 to 1—if that is undesirable, one could explicitly filter such cases in the WHERE clause, or else add a higher precedence WHEN condition):

UPDATE Table
SET    A = CASE
         WHEN A BETWEEN 0 AND 1 THEN 1
         WHEN A BETWEEN 1 AND 2 THEN 2
       END
WHERE  A BETWEEN 0 AND 2

Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL() instead:

UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2

Jquery $(this) Child Selector

The best way with the HTML you have would probably be to use the next function, like so:

var div = $(this).next('.class2');

Since the click handler is happening to the <a>, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent and children. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:

var div = $(this).parent().children('.class2');

If you wanted the "search" to not be limited to immediate children, you would use find instead of children in the example above.

Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div> tags are going to have those classes, make the selector be div.class1, div.class2.

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

The source of your confusion is evident in your comment:

The whole point of ceil/floor operations is to convert floats to integers!

The point of the ceil and floor operations is to round floating-point data to integral values. Not to do a type conversion. Users who need to get integer values can do an explicit conversion following the operation.

Note that it would not be possible to implement a round to integral value as trivially if all you had available were a ceil or float operation that returned an integer. You would need to first check that the input is within the representable integer range, then call the function; you would need to handle NaN and infinities in a separate code path.

Additionally, you must have versions of ceil and floor which return floating-point numbers if you want to conform to IEEE 754.

Get the second highest value in a MySQL table

SELECT DISTINCT Salary
FROM emp
ORDER BY salary DESC
LIMIT 1 , 1

This query will give second highest salary of the duplicate records as well.

How to find all occurrences of an element in a list

If you need to search for all element's positions between certain indices, you can state them:

[i for i,x in enumerate([1,2,3,2]) if x==2 & 2<= i <=3] # -> [3]

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.

1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?

YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).

But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.

2. If yes, is there other way that I don't have to install them but still can run my application?

Yes, there is at least one way. And it is the Managed port of ODP.NET.

Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.

But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using statements, for example: using Oracle.DataAccess.Client becomes using Oracle.ManagedDataAccess.Client and that's it! (Unless you were supposedly using some of the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect nodes from your app.config/web.config files and never sweat that junk again!

References:

Troubleshooting:

That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).

Common solutions I have found to this problem:

App is 64-bit?

  • Install 64-bit Oracle Client (32-bit one wont work)

App is 32-bit?

  • Install 32-bit Oracle Client (64-bit one wont work)

Oracle Client is already installed for the correct architecture?

  • Verify your environment PATH and ORACLE_HOME variables, make sure Oracle can be found (newer versions may use Registry instead)
  • Verify the ORACLE_HOME and settings in the Registry (And remember: Registry is either 32-bit or 64-bit, so make sure you check the one that matches your app!)
  • Verify permissions on the ORACLE_HOME folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users group.. fixing perms on the home folder fixed this.
  • As always, it is handy to Use SysInternals Process Monitor to find out what file is missing or can't be read.

Shortcut to open file in Vim

You can search for a file in the current path by using **:

:tabe **/header.h

Hit tab to see various completions if there is more than one match.

pandas groupby sort descending order

This kind of operation is covered under hierarchical indexing. Check out the examples here

When you groupby, you're making new indices. If you also pass a list through .agg(). you'll get multiple columns. I was trying to figure this out and found this thread via google.

It turns out if you pass a tuple corresponding to the exact column you want sorted on.

Try this:

# generate toy data 
ex = pd.DataFrame(np.random.randint(1,10,size=(100,3)), columns=['features', 'AUC', 'recall'])

# pass a tuple corresponding to which specific col you want sorted. In this case, 'mean' or 'AUC' alone are not unique. 
ex.groupby('features').agg(['mean','std']).sort_values(('AUC', 'mean'))

This will output a df sorted by the AUC-mean column only.

How to save an HTML5 Canvas as an image on a server?

I just made an imageCrop and Upload feature with

https://www.npmjs.com/package/react-image-crop

to get the ImagePreview ( the cropped image rendering in a canvas)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

I prefer sending data in blob with content type image/jpeg rather than toDataURL ( a huge base64 string`

My implementation for uploading to Azure Blob using SAS URL

axios.post(azure_sas_url, image_in_blob, {
   headers: {
      'x-ms-blob-type': 'BlockBlob',
      'Content-Type': 'image/jpeg'
   }
})

Python + Django page redirect

You can do this in the Admin section. It's explained in the documentation.

https://docs.djangoproject.com/en/dev/ref/contrib/redirects/

finding the type of an element using jQuery

You can use .prop() with tagName as the name of the property that you want to get:

$("#elementId").prop('tagName'); 

Set background image in CSS using jquery

Remove the semi-colon after no-repeat, in the url and try it .

$("#globalsearchstr").focus(function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
});

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

Based on user @andygjp's answer, its better if you override the base Db.SaveChanges() method and add a function to override any date which does not fall between SqlDateTime.MinValue and SqlDateTime.MaxValue.

Here is the sample code

public class MyDb : DbContext
{
    public override int SaveChanges()
    {
        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries().Where(x => (x.State == EntityState.Added || x.State == EntityState.Modified)))
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Taken from the user @sky-dev's comment on https://stackoverflow.com/a/11297294/9158120

How to get Database Name from Connection String using SqlConnectionStringBuilder

A much simpler alternative is to get the information from the connection object itself. For example:

IDbConnection connection = new SqlConnection(connectionString);
var dbName = connection.Database;

Similarly you can get the server name as well from the connection object.

DbConnection connection = new SqlConnection(connectionString);
var server = connection.DataSource;

Calculate correlation with cor(), only for numerical columns

For numerical data you have the solution. But it is categorical data, you said. Then life gets a bit more complicated...

Well, first : The amount of association between two categorical variables is not measured with a Spearman rank correlation, but with a Chi-square test for example. Which is logic actually. Ranking means there is some order in your data. Now tell me which is larger, yellow or red? I know, sometimes R does perform a spearman rank correlation on categorical data. If I code yellow 1 and red 2, R would consider red larger than yellow.

So, forget about Spearman for categorical data. I'll demonstrate the chisq-test and how to choose columns using combn(). But you would benefit from a bit more time with Agresti's book : http://www.amazon.com/Categorical-Analysis-Wiley-Probability-Statistics/dp/0471360937

set.seed(1234)
X <- rep(c("A","B"),20)
Y <- sample(c("C","D"),40,replace=T)

table(X,Y)
chisq.test(table(X,Y),correct=F)
# I don't use Yates continuity correction

#Let's make a matrix with tons of columns

Data <- as.data.frame(
          matrix(
            sample(letters[1:3],2000,replace=T),
            ncol=25
          )
        )

# You want to select which columns to use
columns <- c(3,7,11,24)
vars <- names(Data)[columns]

# say you need to know which ones are associated with each other.
out <-  apply( combn(columns,2),2,function(x){
          chisq.test(table(Data[,x[1]],Data[,x[2]]),correct=F)$p.value
        })

out <- cbind(as.data.frame(t(combn(vars,2))),out)

Then you should get :

> out
   V1  V2       out
1  V3  V7 0.8116733
2  V3 V11 0.1096903
3  V3 V24 0.1653670
4  V7 V11 0.3629871
5  V7 V24 0.4947797
6 V11 V24 0.7259321

Where V1 and V2 indicate between which variables it goes, and "out" gives the p-value for association. Here all variables are independent. Which you would expect, as I created the data at random.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.

In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.

build.gradle

android {

    // [...]

    defaultConfig {

        // [...]

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // add the schema location to the source sets
    // used by Room, to test migrations
    sourceSets {
        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
    }

    // [...]
}

Naming Conventions: What to name a boolean variable?

How about:

 hasSiblings
 or isFollowedBySiblings (or isFolloedByItems, or isFollowedByOtherItems etc.)
 or moreItems

Although I think that even though you shouldn't make a habit of braking 'the rules' sometimes the best way to accomplish something may be to make an exception of the rule (Code Complete guidelines), and in your case, name the variable isNotLast

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Bootstrap 3 jquery event for active tab change

$(function () {
    $('#myTab a:last').tab('show');
});

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var target = $(e.target).attr("href");
    if ((target == '#messages')) {
        alert('ok');
    } else {
        alert('not ok');
    }
});

the problem is that attr('href') is never empty.

Or to compare the #id = "#some value" and then call the ajax.

How to enable ASP classic in IIS7.5

So it turns out that if I add the Handler Mappings on the Website and Application level, everything works beautifully. I was only adding them on the server level, thus IIS did not know to map the asp pages to the IsapiModule.

So to resolve this issue, go to the website you want to add your application to, then double click on Handler Mappings. Click "Add Script Map" and enter in the following information:

RequestPath: *.asp
Executable: C:\Windows\System32\inetsrv\asp.dll
Name: Classic ASP (this can be anything you want it to be

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

String.contains in Java

Empty is a subset of any string.

Think of them as what is between every two characters.

Kind of the way there are an infinite number of points on any sized line...

(Hmm... I wonder what I would get if I used calculus to concatenate an infinite number of empty strings)

Note that "".equals("") only though.

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Unbelievably, in 3 years nobody has answered your excellent question with examples of both ways to map the relationship.

As mentioned by others, the "owner" side contains the pointer (foreign key) in the database. You can designate either side as the owner, however, if you designate the One side as the owner, the relationship will not be bidirectional (the inverse aka "many" side will have no knowledge of its "owner"). This can be desirable for encapsulation/loose coupling:

// "One" Customer owns the associated orders by storing them in a customer_orders join table
public class Customer {
    @OneToMany(cascade = CascadeType.ALL)
    private List<Order> orders;
}

// if the Customer owns the orders using the customer_orders table,
// Order has no knowledge of its Customer
public class Order {
    // @ManyToOne annotation has no "mappedBy" attribute to link bidirectionally
}

The only bidirectional mapping solution is to have the "many" side own its pointer to the "one", and use the @OneToMany "mappedBy" attribute. Without the "mappedBy" attribute Hibernate will expect a double mapping (the database would have both the join column and the join table, which is redundant (usually undesirable)).

// "One" Customer as the inverse side of the relationship
public class Customer {
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
    private List<Order> orders;
}

// "many" orders each own their pointer to a Customer
public class Order {
    @ManyToOne
    private Customer customer;
}

Is there a date format to display the day of the week in java?

SimpleDateFormat sdf=new SimpleDateFormat("EEE");

EEE stands for day of week for example Thursday is displayed as Thu.

Get error message if ModelState.IsValid fails?

It is sample extension

public class GetModelErrors
{
    //Usage return Json to View :
    //return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
    public class KeyMessages
    {
        public string Key { get; set; }
        public string Message { get; set; }
    }
    private readonly ModelStateDictionary _entry;
    public GetModelErrors(ModelStateDictionary entry)
    {
        _entry = entry;
    }

    public int Count()
    {
        return _entry.ErrorCount;
    }
    public string Exceptions(string sp = "\n")
    {
        return string.Join(sp, _entry.Values
            .SelectMany(v => v.Errors)
            .Select(e => e.Exception));
    }
    public string Messages(string sp = "\n")
    {
        string msg = string.Empty;
        foreach (var item in _entry)
        {
            if (item.Value.ValidationState == ModelValidationState.Invalid)
            {
                msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
            }
        }
        return msg;
    }

    public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
    {
        List<KeyMessages> list = new List<KeyMessages>();
        foreach (var item in _entry)
        {
            if (item.Value.ValidationState == ModelValidationState.Invalid)
            {
                list.Add(new KeyMessages
                {
                    Key = item.Key,
                    Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
                });
            }
        }
        return list;
    }
}

Inserting values to SQLite table in Android

I see it is an old thread but I had the same error.

I found the explanation here: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

void execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.

How to get Toolbar from fragment?

For Kotlin users (activity as AppCompatActivity).supportActionBar?.show()

What is the difference between compileSdkVersion and targetSdkVersion?

My 2 cents: Compile against any version of the SDK but take care not to call any APIs that your "minimum SDK version" does not support. That means you "could" compile against the latest version of the SDK.

As for "target version" it simply refers to what you planned to target in the first place and have possibly tested against. If you haven't done the due diligence then this is the way to inform Android that it needs to perform some additional checks before it deploys your lets say "Lollipop" targeted app on "Oreo".

So the "target version" is obviously not lower than your "minimum SDK version" but it can't be higher than your "compiled version".

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Try using the property ForeColor. Like this :

TextBox1.ForeColor = Color.Red;

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

It took me a while to find it but here's the best code that I found......http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/

var $viewportMeta = $('meta[name="viewport"]');
$('input, select, textarea').bind('focus blur', function(event) {
$viewportMeta.attr('content', 'width=device-width,initial-scale=1,maximum-scale=' +        (event.type == 'blur' ? 10 : 1));
});

Illegal mix of collations error in MySql

I was getting this same error on PhpMyadmin and did the solution indicated here which worked for me

ALTER TABLE table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci

Illegal mix of collations MySQL Error Also I would recommend going with General instead of swedish since that one is default and not to use the language unless your application is using Swedish.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection from wget if you're behind a proxy and don't have HTTP_PROXY and HTTPS_PROXY environment variables set correctly. Make sure to set HTTP_PROXY and HTTPS_PROXY to point to your proxy.

This is a common situation if you work for a large corporation.

What is the difference between Digest and Basic Authentication?

Digest Authentication communicates credentials in an encrypted form by applying a hash function to: the username, the password, a server supplied nonce value, the HTTP method and the requested URI.

Whereas Basic Authentication uses non-encrypted base64 encoding.

Therefore, Basic Authentication should generally only be used where transport layer security is provided such as https.

See RFC-2617 for all the gory details.

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

Async/Await Class Constructor

This can never work.

The async keyword allows await to be used in a function marked as async but it also converts that function into a promise generator. So a function marked with async will return a promise. A constructor on the other hand returns the object it is constructing. Thus we have a situation where you want to both return an object and a promise: an impossible situation.

You can only use async/await where you can use promises because they are essentially syntax sugar for promises. You can't use promises in a constructor because a constructor must return the object to be constructed, not a promise.

There are two design patterns to overcome this, both invented before promises were around.

  1. Use of an init() function. This works a bit like jQuery's .ready(). The object you create can only be used inside it's own init or ready function:

    Usage:

    var myObj = new myClass();
    myObj.init(function() {
        // inside here you can use myObj
    });
    

    Implementation:

    class myClass {
        constructor () {
    
        }
    
        init (callback) {
            // do something async and call the callback:
            callback.bind(this)();
        }
    }
    
  2. Use a builder. I've not seen this used much in javascript but this is one of the more common work-arounds in Java when an object needs to be constructed asynchronously. Of course, the builder pattern is used when constructing an object that requires a lot of complicated parameters. Which is exactly the use-case for asynchronous builders. The difference is that an async builder does not return an object but a promise of that object:

    Usage:

    myClass.build().then(function(myObj) {
        // myObj is returned by the promise, 
        // not by the constructor
        // or builder
    });
    
    // with async/await:
    
    async function foo () {
        var myObj = await myClass.build();
    }
    

    Implementation:

    class myClass {
        constructor (async_param) {
            if (typeof async_param === 'undefined') {
                throw new Error('Cannot be called directly');
            }
        }
    
        static build () {
            return doSomeAsyncStuff()
               .then(function(async_result){
                   return new myClass(async_result);
               });
        }
    }
    

    Implementation with async/await:

    class myClass {
        constructor (async_param) {
            if (typeof async_param === 'undefined') {
                throw new Error('Cannot be called directly');
            }
        }
    
        static async build () {
            var async_result = await doSomeAsyncStuff();
            return new myClass(async_result);
        }
    }
    

Note: although in the examples above we use promises for the async builder they are not strictly speaking necessary. You can just as easily write a builder that accept a callback.


Note on calling functions inside static functions.

This has nothing whatsoever to do with async constructors but with what the keyword this actually mean (which may be a bit surprising to people coming from languages that do auto-resolution of method names, that is, languages that don't need the this keyword).

The this keyword refers to the instantiated object. Not the class. Therefore you cannot normally use this inside static functions since the static function is not bound to any object but is bound directly to the class.

That is to say, in the following code:

class A {
    static foo () {}
}

You cannot do:

var a = new A();
a.foo() // NOPE!!

instead you need to call it as:

A.foo();

Therefore, the following code would result in an error:

class A {
    static foo () {
        this.bar(); // you are calling this as static
                    // so bar is undefinned
    }
    bar () {}
}

To fix it you can make bar either a regular function or a static method:

function bar1 () {}

class A {
    static foo () {
        bar1();   // this is OK
        A.bar2(); // this is OK
    }

    static bar2 () {}
}

How to search file text for a pattern and replace it with a given value

If you need to do substitutions across line boundaries, then using ruby -pi -e won't work because the p processes one line at a time. Instead, I recommend the following, although it could fail with a multi-GB file:

ruby -e "file='translation.ja.yml'; IO.write(file, (IO.read(file).gsub(/\s+'$/, %q('))))"

The is looking for white space (potentially including new lines) following by a quote, in which case it gets rid of the whitespace. The %q(')is just a fancy way of quoting the quote character.

Using sed, Insert a line above or below the pattern?

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
 pattern
 line1 line2 

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
 line1 line2 
 pattern

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

JavaFX "Location is required." even though it is in the same package

If you look at the docs [1], you see that the load() method can take a URL:

load(URL location)

So if you're running Java 7 or newer, you can load the FXML file like this:

URL url = Paths.get("./src/main/resources/fxml/Fxml.fxml").toUri().toURL();
Parent root = FXMLLoder.load(url);

This example is from a Maven project, which is why the FXML file is in the resources folder.

[1] https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.htm

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

Getting the current date in SQL Server?

As you are using SQL Server 2008, go with Martin's answer.

If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

SQLFiddle

How to get param from url in angular 4?

The accepted answer uses the observable to retrieve the parameter which can be useful in the parameter will change throughtout the component lifecycle.

If the parameter will not change, one can consider using the params object on the snapshot of the router url.

snapshot.params returns all the parameters in the URL in an object.

constructor(private route: ActivateRoute){}

ngOnInit() {
   const allParams = this.route.snapshot.params // allParams is an object
   const param1 = allParams.param1 // retrieve the parameter "param1"
}

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

I believe another solution to this problem would be use to variables of type long instead of int.

I was just working on some code where the % operator was returning a negative value which caused some issues (for generating uniform random variables on [0,1] you don't really want negative numbers :) ), but after switching the variables to type long, everything was running smoothly and the results matched the ones I was getting when running the same code in python (important for me as I wanted to be able to generate the same "random" numbers across several platforms.

Merge Two Lists in R

merged = map(names(first), ~c(first[[.x]], second[[.x]])
merged = set_names(merged, names(first))

Using purrr. Also solves the problem of your lists not being in order.

How can I show a message box with two buttons?

Remember - if you set the buttons to vbOkOnly - it will always return 1.

So you can't decide if a user clicked on the close or the OK button. You just have to add a vbOk option.

How do I change the android actionbar title and icon

ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getString(R.string.titolo));
actionBar.setIcon(R.mipmap.ic_launcher);
actionBar.setDisplayShowHomeEnabled(true);

How to get Spinner value?

add setOnItemSelectedListener to spinner reference and get the data like that`

 mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            selectedSize=adapterView.getItemAtPosition(position).toString();

Hive load CSV with commas in quoted fields

If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:

ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';

Will accept this line as 4 fields

1,some text\, with comma in it,123,more text

Get Return Value from Stored procedure in asp.net

2 things.

  • The query has to complete on sql server before the return value is sent.

  • The results have to be captured and then finish executing before the return value gets to the object.

In English, finish the work and then retrieve the value.

this will not work:

                cmm.ExecuteReader();
                int i = (int) cmm.Parameters["@RETURN_VALUE"].Value;

This will work:

                        SqlDataReader reader = cmm.ExecuteReader();
                        reader.Close();

                        foreach (SqlParameter prm in cmd.Parameters)
                        {
                           Debug.WriteLine("");
                           Debug.WriteLine("Name " + prm.ParameterName);
                           Debug.WriteLine("Type " + prm.SqlDbType.ToString());
                           Debug.WriteLine("Size " + prm.Size.ToString());
                           Debug.WriteLine("Direction " + prm.Direction.ToString());
                           Debug.WriteLine("Value " + prm.Value);

                        }

if you are not sure check the value of the parameter before during and after the results have been processed by the reader.

Launch Image does not show up in my iOS App

For some reason, I had to change the asset catalog location to "relative to project" for this to work.

I had also deleted the app from my phone and reinstalled, but it was probably the "relative to project" that did it.

Select from where field not equal to Mysql Php

$sqlquery = "SELECT field1, field2 FROM table WHERE columnA <> 'x' AND columbB <> 'y'";

I'd suggest using the diamond operator (<>) in favor of != as the first one is valid SQL and the second one is a MySQL addition.

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

How to select records from last 24 hours using SQL?

select ...
from ...
where YourDateColumn >= getdate()-1

How do I get into a Docker container's shell?

$ docker exec -it <Container-Id> /bin/bash

Or depending on the shell, it can be

$ docker exec -it <Container-Id> /bin/sh

You can get the container-Id via docker ps command

-i = interactive

-t = to allocate a psuedo-TTY

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

Media query to detect if device is touchscreen

In 2017, CSS media query from second answer still doesn't work on Firefox. I found a soluton for that: -moz-touch-enabled


So, here is cross-browser media query:

@media (-moz-touch-enabled: 1), (pointer:coarse) {
    .something {
        its: working;
    }
}

Functions are not valid as a React child. This may happen if you return a Component instead of from render

Adding to sagiv's answer, we should create the parent component in such a way that it can consist all children components rather than returning the child components in the way you were trying to return.

Try to intentiate the parent component and pass the props inside it so that all children can use it like below

const NewComponent = NewHOC(Movie);

Here NewHOC is the parent component and all its child are going to use movie as props.

But any way, you guyd6 have solved a problem for new react developers as this might be a problem that can come too and here is where they can find the solution for that.

How to get a parent element to appear above child

Cracked it. Basically, what's happening is that when you set the z-index to the negative, it actually ignores the parent element, whether it is positioned or not, and sits behind the next positioned element, which in your case was your main container. Therefore, you have to put your parent element in another, positioned div, and your child div will sit behind that.

Working that out was a life saver for me, as my parent element specifically couldn't be positioned, in order for my code to work.

I found all this incredibly useful to achieve the effect that's instructed on here: Using only CSS, show div on hover over <a>

Remove menubar from Electron app

The menu can be hidden or auto-hidden (like in Slack or VS Code - you can press Alt to show/hide the menu).

Relevant methods:

---- win.setMenu(menu) - Sets the menu as the window’s menu bar, setting it to null will remove the menu bar. (This will remove the menu completly)

mainWindow.setMenu(null)


---- win.setAutoHideMenuBar(hide) - Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only
show
when users press the single Alt key.

mainWindow.setAutoHideMenuBar(true)

Source: https://github.com/Automattic/simplenote-electron/issues/293

There is also the method for making a frameless window as shown bellow:

(no close button no anything. Can be what we want (better design))

const { BrowserWindow } = require('electron')
let win = new BrowserWindow({ width: 800, height: 600, frame: false })
win.show()

https://electronjs.org/docs/api/browser-window#winremovemenu-linux-windows

doc: https://electronjs.org/docs/api/frameless-window

Edit: (new)

win.removeMenu() Linux Windows Remove the window's menu bar.

https://electronjs.org/docs/api/browser-window#winremovemenu-linux-windows

Added win.removeMenu() to remove application menus instead of using win.setMenu(null)

That is added from v5 as per:

https://github.com/electron/electron/pull/16570

https://github.com/electron/electron/pull/16657

Electron v7 bug

For Electron 7.1.1 use Menu.setApplicationMenu instead of win.removeMenu()

as per this thread:
https://github.com/electron/electron/issues/16521

And the big note is: you have to call it before creating the BrowserWindow! Or it will not work!

const {app, BrowserWindow, Menu} = require('electron')

Menu.setApplicationMenu(null);

const browserWindow = new BrowserWindow({/*...*/});

UPDATE (Setting autoHideMenuBar on BrowserWindow construction)

As by @kcpr comment! We can set the property and many on the constructor

That's available on the latest stable version of electron by now which is 8.3!
But too in old versions i checked for v1, v2, v3, v4!
It's there in all versions!

As per this link
https://github.com/electron/electron/blob/1-3-x/docs/api/browser-window.md

And for the v8.3
https://github.com/electron/electron/blob/v8.3.0/docs/api/browser-window.md#new-browserwindowoptions

The doc link
https://www.electronjs.org/docs/api/browser-window#new-browserwindowoptions

From the doc for the option:

autoHideMenuBar Boolean (optional) - Auto hide the menu bar unless the Alt key is pressed. Default is false.

Here a snippet to illustrate it:


let browserWindow = new BrowserWindow({
    width: 800,
    height: 600,
    autoHideMenuBar: true // <<< here
})

Circle line-segment collision detection algorithm?

I just needed that, so I came up with this solution. The language is maxscript, but it should be easily translated to any other language. sideA, sideB and CircleRadius are scalars, the rest of the variables are points as [x,y,z]. I'm assuming z=0 to solve on the plane XY

fn projectPoint p1 p2 p3 = --project  p1 perpendicular to the line p2-p3
(
    local v= normalize (p3-p2)
    local p= (p1-p2)
    p2+((dot v p)*v)
)
fn findIntersectionLineCircle CircleCenter CircleRadius LineP1 LineP2=
(
    pp=projectPoint CircleCenter LineP1 LineP2
    sideA=distance pp CircleCenter
    --use pythagoras to solve the third side
    sideB=sqrt(CircleRadius^2-sideA^2) -- this will return NaN if they don't intersect
    IntersectV=normalize (pp-CircleCenter)
    perpV=[IntersectV.y,-IntersectV.x,IntersectV.z]
    --project the point to both sides to find the solutions
    solution1=pp+(sideB*perpV)
    solution2=pp-(sideB*perpV)
    return #(solution1,solution2)
)

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

It could be related with your Java version. Go ahead and download the Database version which includes Java.

However, if you are configuring a local development workstation I recommend you to download the Express Edition.

Here is the link: http://www.oracle.com/technetwork/products/express-edition/downloads/index-083047.html

or google this: OracleXE112_Win64

Good luck!

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

for me it worked the approach that I used in eclipselink as well. Just call the size() of the collection that should be loaded before using it as parameter to pages.

for (Entity e : entityListKeeper.getEntityList()) {
    e.getListLazyLoadedEntity().size();
}

Here entityListKeeper has List of Entity that has list of LazyLoadedEntity. If you have just therelation Entity has list of LazyLoadedEntity then the solution is:

getListLazyLoadedEntity().size();