Programs & Examples On #Qualified

Target class controller does not exist - Laravel 8

I got the same error when I installed Laravel version 8.27.0: The error is as follow:

The Error that I got:

But when I saw my app/Providers/RouteServiceProvider.php I have namespaces inside my boot method, then I just uncommented this => "protected $namespace = 'App\Http\Controllers';"

Just Uncomment The protected $namespace = 'App\Http\Controllers';';

Now My Project is working:

Project is working safe and sound

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Visual Studio Code pylint: Unable to import 'protorpc'

For your case, add the following code to vscode's settings.json.

"python.linting.pylintArgs": [
    "--init-hook='import sys; sys.path.append(\"~/google-cloud-sdk/platform/google_appengine/lib\")'"
]

For the other who got troubles with pip packages, you can go with

"python.linting.pylintArgs": [
    "--init-hook='import sys; sys.path.append(\"/usr/local/lib/python3.7/dist-packages\")'"
]

You should replace python3.7 above with your python version.

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I have Windows 10 and PowerShell 5.1 was already installed. For whatever reason the x86 version works and can find "Install-Module", but the other version cannot.

Search your Start Menu for "powershell", and find the entry that ends in "(x86)":

Windows 10 Start Menu searching for PowerShell

Here is what I experience between the two different versions:

PowerShell x86 vs x64 running Install-Module cmdlet comparison

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

No assembly found containing an OwinStartupAttribute Error

For those who do want owin to start, <add key="owin:AutomaticAppStartup" value="false" /> won't work, but the following worked for me.

  1. if you have a partial class "Startup" in your Startup.Auth file, create another partial Startup class in the root of your project.

  2. define an assembly owinstartup attribute pointing to that class

  3. create a "Configuration" method

  4. rebuild your application

You could also create the "Configuration" method, and add the assembly attribute to the Startup.Auth, but doing it this way allows you to keep your Startup class separated by leveraging C# class definition splitting. Read more here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods

This is what my Startup.cs file looked like:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(ProjectNameSpace.Startup))]

namespace ProjectNameSpace
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

You can alternatively download winutils.exe from GITHub:

https://github.com/steveloughran/winutils/tree/master/hadoop-2.7.1/bin

replace hadoop-2.7.1 with the version you want and place the file in D:\hadoop\bin

If you do not have access rights to the environment variable settings on your machine, simply add the below line to your code:

System.setProperty("hadoop.home.dir", "D:\\hadoop");

How do I check if a PowerShell module is installed?

Coming from Linux background. I would prefer using something similar to grep, therefore I use Select-String. So even if someone is not sure of the complete module name. They can provide the initials and determine whether the module exists or not.

Get-Module -ListAvailable -All | Select-String Module_Name(can be a part of the module name)

REST API - Bulk Create or Update in single request

PUT ing

PUT /binders/{id}/docs Create or update, and relate a single document to a binder

e.g.:

PUT /binders/1/docs HTTP/1.1
{
  "docNumber" : 1
}

PATCH ing

PATCH /docs Create docs if they do not exist and relate them to binders

e.g.:

PATCH /docs HTTP/1.1
[
    { "op" : "add", "path" : "/binder/1/docs", "value" : { "doc_number" : 1 } },
    { "op" : "add", "path" : "/binder/8/docs", "value" : { "doc_number" : 8 } },
    { "op" : "add", "path" : "/binder/3/docs", "value" : { "doc_number" : 6 } }
] 

I'll include additional insights later, but in the meantime if you want to, have a look at RFC 5789, RFC 6902 and William Durand's Please. Don't Patch Like an Idiot blog entry.

Convert a secure string to plain text

You are close, but the parameter you pass to SecureStringToBSTR must be a SecureString. You appear to be passing the result of ConvertFrom-SecureString, which is an encrypted standard string. So call ConvertTo-SecureString on this before passing to SecureStringToBSTR.

$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

How do I use Join-Path to combine more than two strings into a file path?

Since Join-Path can be piped a path value, you can pipe multiple Join-Path statements together:

Join-Path "C:" -ChildPath "Windows" | Join-Path -ChildPath "system32" | Join-Path -ChildPath "drivers"

It's not as terse as you would probably like it to be, but it's fully PowerShell and is relatively easy to read.

How to list AD group membership for AD users using input list?

First: As it currently stands, the $User variable does not have a .Users property. In your code, $User simply represents one line (the "current" line in the foreach loop) from the text file.

$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof

Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:

  1. Query forest for list of domains
  2. Call Get-ADUser for each domain (you may have to specify alternate credentials via the -Credential parameter

Thirdly, to get a list of groups that a user is a member of:

$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';

# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins

Fourthly: To get the final, desired string format, simply add the $User.Name, a semicolon, and the $GroupMembership string together:

$User.SamAccountName + ';' + $GroupMembership;

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:

http://mvnrepository.com

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.12</version>
</dependency>

How to getText on an input in protractor

This code works. I have a date input field that has been set to read only which forces the user to select from the calendar.

for a start date:

var updateInput = "var input = document.getElementById('startDateInput');" +
    "input.value = '18-Jan-2016';" +
    "angular.element(input).scope().$apply(function(s) { s.$parent..searchForm[input.name].$setViewValue(input.value);})";
browser.executeScript(updateInput);

for an end date:

var updateInput = "var input = document.getElementById('endDateInput');" +
    "input.value = '22-Jan-2016';" +
    "angular.element(input).scope().$apply(function(s) { s.$parent.searchForm[input.name].$setViewValue(input.value);})";
    browser.executeScript(updateInput);

PowerShell script to check the status of a URL

You must update the Windows PowerShell to minimum of version 4.0 for the script below to work.


[array]$SiteLinks = "http://mypage.global/Chemical/test.html"
"http://maypage2:9080/portal/site/hotpot/test.json"


foreach($url in $SiteLinks) {

   try {
      Write-host "Verifying $url" -ForegroundColor Yellow
      $checkConnection = Invoke-WebRequest -Uri $url
      if ($checkConnection.StatusCode -eq 200) {
         Write-Host "Connection Verified!" -ForegroundColor Green
      }

   } 
   catch [System.Net.WebException] {
      $exceptionMessage = $Error[0].Exception
      if ($exceptionMessage -match "503") {
         Write-Host "Server Unavaiable" -ForegroundColor Red
      }
      elseif ($exceptionMessage -match "404") {
         Write-Host "Page Not found" -ForegroundColor Red
      }


   }
}

OWIN Startup Class Missing

It is also possible to get this exception (even when you have a correctly configured startup class) if running through IIS Express and your virtual directory is not configured correctly.

When I encountered this issue, the resolution was simply to press the 'Create Virtual Directory' button in the 'Web' tab of project properties (Using Visual Studio 2013)

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

In my case, the issue was not about binding redirects or missing/mismatched Microsoft.AspNet.Razor package/dlls, so the above solutions didn't work.

The issue, in my non-web project, was that RazorEngine+Microsoft.AspNet.Razor were installed in a different project (Project A) than the calling assembly/start-up project (Project B). Because there's no explicit reference to Razor, the System.Web.Razor did NOT get copied to /bin in a Release build.

The solution was to Install RazorEngine+Microsoft.AspNet.Razor in the application entry point (Project B, ConsoleApplication in my case), then the System.Web.Razor gets copied to /bin and everyone's happy.

How do I get an object's unqualified (short) class name?

A good old regex seems to be faster than the most of the previous shown methods:

// both of the below calls will output: ShortClassName

echo preg_replace('/.*\\\\/', '', 'ShortClassName');
echo preg_replace('/.*\\\\/', '', 'SomeNamespace\SomePath\ShortClassName');

So this works even when you provide a short class name or a fully qualified (canonical) class name.

What the regex does is that it consumes all previous chars until the last separator is found (which is also consumed). So the remaining string will be the short class name.

If you want to use a different separator (eg. / ) then just use that separator instead. Remember to escape the backslash (ie. \) and also the pattern char (ie. /) in the input pattern.

Failed to locate the winutils binary in the hadoop binary path

I used "hbase-1.3.0" and "hadoop-2.7.3" versions. Setting HADOOP_HOME environment variable and copying 'winutils.exe' file under HADOOP_HOME/bin folder solves the problem on a windows os. Attention to set HADOOP_HOME environment to the installation folder of hadoop(/bin folder is not necessary for these versions). Additionally I preferred using cross platform tool cygwin to settle linux os functionality (as possible as it can) because Hbase team recommend linux/unix env.

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the "PSModulePath" environment variable.

The default path should be "%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\"

Loop X number of times

Use:

1..10 | % { write "loop $_" }

Output:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

OUTDATED: Many modern browsers now have first-class support for crypto operations. See Vitaly Zdanevich's answer below.


The Stanford JS Crypto Library contains an implementation of SHA-256. While crypto in JS isn't really as well-vetted an endeavor as other implementation platforms, this one is at least partially developed by, and to a certain extent sponsored by, Dan Boneh, who is a well-established and trusted name in cryptography, and means that the project has some oversight by someone who actually knows what he's doing. The project is also supported by the NSF.

It's worth pointing out, however...
... that if you hash the password client-side before submitting it, then the hash is the password, and the original password becomes irrelevant. An attacker needs only to intercept the hash in order to impersonate the user, and if that hash is stored unmodified on the server, then the server is storing the true password (the hash) in plain-text.

So your security is now worse because you decided add your own improvements to what was previously a trusted scheme.

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

We get this error because of build path issue. You should add "Server Runtime" libraries in Build Path.

"java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer"

Please follow below steps to resolve class not found exception.

Right click on project --> Build Path --> Java Build Path --> Add Library --> Server Runtime --> Apache Tomcat v7.0

error: expected unqualified-id before ‘.’ token //(struct)

You are trying to access the struct statically with a . instead of ::, nor are its members static. Either instantiate ReducedForm:

ReducedForm rf;
rf.iSimplifiedNumerator = 5;

or change the members to static like this:

struct ReducedForm
{
    static int iSimplifiedNumerator;
    static int iSimplifiedDenominator;
};

In the latter case, you must access the members with :: instead of . I highly doubt however that the latter is what you are going for ;)

No connection could be made because the target machine actively refused it (PHP / WAMP)

Kindly check is your mysql-service is running.

for windows user: check the services - mysql service

for Linux user: Check the mysql service/demon is running (services mysql status)

Thanks & Regards Jaiswar Vipin Kumar R

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Open Turn On/Off Windows Features.

Make sure you have Active Directory Domain Services selected. If not, install it. enter image description here

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

Dependency injection with Jersey 2.0

Late but I hope this helps someone.

I have my JAX RS defined like this:

@Path("/examplepath")
@RequestScoped //this make the diference
public class ExampleResource {

Then, in my code finally I can inject:

@Inject
SomeManagedBean bean;

In my case, the SomeManagedBean is an ApplicationScoped bean.

Hope this helps to anyone.

XML Schema Validation : Cannot find the declaration of element

Thanks to everyone above, but this is now fixed. For the benefit of others the most significant error was in aligning the three namespaces as suggested by Ian.

For completeness, here is the corrected XML and XSD

Here is the XML, with the typos corrected (sorry for any confusion caused by tardiness)

<?xml version="1.0" encoding="UTF-8"?>

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="urn:Test.Namespace"  
      xsi:schemaLocation="urn:Test.Namespace Test1.xsd">
    <element1 id="001">
        <element2 id="001.1">
            <element3 id="001.1" />
        </element2>
    </element1>
</Root>

and, here is the Schema

<?xml version="1.0"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="urn:Test.Namespace"
            xmlns="urn:Test.Namespace"
            elementFormDefault="qualified">
    <xsd:element name="Root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="element1" maxOccurs="unbounded" type="element1Type"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
       
    <xsd:complexType name="element1Type">
        <xsd:sequence>
            <xsd:element name="element2" maxOccurs="unbounded" type="element2Type"/>
        </xsd:sequence>
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>
       
    <xsd:complexType name="element2Type">
        <xsd:sequence>
            <xsd:element name="element3" type="element3Type"/>
        </xsd:sequence>
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>

    <xsd:complexType name="element3Type">
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>        
</xsd:schema>

Thanks again to everyone, I hope this is of use to somebody else in the future.

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.

My initial wrong XSD was alike the following:

<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="XXX" type="XXX_TYPE"/>
    </xs:sequence>
</xs:complexType>

The good XSD format for my migration to succeed was the following:

<xs:element name="Document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="XXX"/>
        </xs:sequence>
    </xs:complexType>        
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>

And so on for every similar XSD nodes.

'nuget' is not recognized but other nuget commands working

Retrieve nuget.exe from https://www.nuget.org/downloads. Copy it to a local folder and add that folder to the PATH environment variable.

This is will make nuget available globally, from any project.

How to load assemblies in PowerShell?

You could use LoadWithPartialName. However, that is deprecated as they said.

You can indeed go along with Add-Type, and in addition to the other answers, if you don't want to specify the full path of the .dll file, you could just simply do:

Add-Type -AssemblyName "Microsoft.SqlServer.Management.SMO"

To me this returned an error, because I do not have SQL Server installed (I guess), however, with this same idea I was able to load the Windows Forms assembly:

Add-Type -AssemblyName "System.Windows.Forms"

You can find out the precise assembly name belonging to the particular class on the MSDN site:

Example of finding out assembly name belonging to a particular class

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

You may get your answer here: Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

UPDATE

It might be due to various issues.I cant say which one is there in your case. It may be because:

  • DCOM is not enabled in host pc or target pc or on both
  • your firewall or even your antivirus is preventing the access
  • any WMI related service is disabled

Some WMI related services are:

  • Remote Access Auto Connection Manager
  • Remote Access Connection Manager
  • Remote Procedure Call (RPC)
  • Remote Procedure Call (RPC) Locator
  • Remote Registry

For DCOM settings refer to registry key HKLM\Software\Microsoft\OLE, value EnableDCOM. The value should be set to 'Y'.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

What is "android:allowBackup"?

Here is what backup in this sense really means:

Android's backup service allows you to copy your persistent application data to remote "cloud" storage, in order to provide a restore point for the application data and settings. If a user performs a factory reset or converts to a new Android-powered device, the system automatically restores your backup data when the application is re-installed. This way, your users don't need to reproduce their previous data or application settings.

~Taken from http://developer.android.com/guide/topics/data/backup.html

You can register for this backup service as a developer here: https://developer.android.com/google/backup/signup.html

The type of data that can be backed up are files, databases, sharedPreferences, cache, and lib. These are generally stored in your device's /data/data/[com.myapp] directory, which is read-protected and cannot be accessed unless you have root privileges.

UPDATE: You can see this flag listed on BackupManager's api doc: BackupManager

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

Powershell v3 Invoke-WebRequest HTTPS error

An alternative implementation in pure (without Add-Type of source):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

Java: using switch statement with enum under subclass

Wrong:

case AnotherClass.MyEnum.VALUE_A

Right:

case VALUE_A:

How to fix C++ error: expected unqualified-id

Get rid of the semicolon after WordGame.

You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

If you don't have httpd.conf in folder /etc/apache2, you should have apache2.conf - simply add:

ServerName localhost

Then restart the apache2 service.

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

Best way to resolve file path too long exception

this may be also possibly solution.It some times also occurs when you keep your Development project into too deep, means may be possible project directory may have too many directories so please don't make too many directories keep it in a simple folder inside the drives. For Example- I was also getting this error when my project was kept like this-

D:\Sharad\LatestWorkings\GenericSurveyApplication020120\GenericSurveyApplication\GenericSurveyApplication

then I simply Pasted my project inside

D:\Sharad\LatestWorkings\GenericSurveyApplication

And Problem was solved.

How to find the Windows version from the PowerShell command line

I am refining one of the answers

I reached this question while trying to match the output from winver.exe:

Version 1607 (OS Build 14393.351)

I was able to extract the build string with:

,((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name BuildLabEx).BuildLabEx -split '\.') | % {  $_[0..1] -join '.' }  

Result: 14393.351

Updated: Here is a slightly simplified script using regex

(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").BuildLabEx -match '^[0-9]+\.[0-9]+' |  % { $matches.Values }

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

JAXB :Need Namespace Prefix to all the elements

Solved by adding

@XmlSchema(
    namespace = "http://www.example.com/a",
    elementFormDefault = XmlNsForm.QUALIFIED,
    xmlns = {
        @XmlNs(prefix="ns1", namespaceURI="http://www.example.com/a")
    }
)  

package authenticator.beans.login;
import javax.xml.bind.annotation.*;

in package-info.java

Took help of jaxb-namespaces-missing : Answer provided by Blaise Doughan

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

Assuming you have a module file called Dummy-Name.psm1 which has a method called Function-Dumb()

Import-Module "Dummy-Name.psm1";
Get-Command -Module "Function-Dumb";
#
#
Function-Dumb;

Could not reliably determine the server's fully qualified domain name

  1. sudo nano /etc/apache2/httpd.conf
  2. search for a text ServerName in nano editor <Ctrl + W>
  3. Insert the following line at the httpd.conf: ServerName localhost
  4. Just restart the Apache: sudo /usr/sbin/apachectl restart

Java : Accessing a class within a package, which is the better way?

As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang package is automatically imported, as is everything in the current package.

The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.

By the way, if you are using lots of static methods (from Math, for example), you could also write

import static java.lang.Math.*;

and then use

sqrt(x)

directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)

How to get current page URL in MVC 3

I too was looking for this for Facebook reasons and none of the answers given so far worked as needed or are too complicated.

@Request.Url.GetLeftPart(UriPartial.Path)

Gets the full protocol, host and path "without" the querystring. Also includes the port if you are using something other than the default 80.

How to easily get network path to the file you are working on?

Here's how to get the filepath of the file in Excel 2010.

1) Right click on the Ribbon.
2) Click on "Customize the Ribbon"
3) On the right hand side, click "New Group." This will add a new tab to the Ribbon. If you want to, click on the "Rename" button the right side and name your tab. For example, I named the tab "Doc Path." This step is optional
4) Under "Choose Commands From" on the left hand side, choose "Commands Not in the Ribbon."
5) Select "Document Location" and "Add" it to your newly created group.
6) The filepath should now appear under the newly created tab on the ribbon.

How to pass boolean values to a PowerShell script from a command prompt

Running powershell scripts on linux from bash gives the same problem. Solved it almost the same as LarsWA's answer:

Working:

pwsh -f ./test.ps1 -bool:true

Not working:

pwsh -f ./test.ps1 -bool=1
pwsh -f ./test.ps1 -bool=true
pwsh -f ./test.ps1 -bool true
pwsh -f ./test.ps1 {-bool=true}
pwsh -f ./test.ps1 -bool=$true
pwsh -f ./test.ps1 -bool=\$true
pwsh -f ./test.ps1 -bool 1
pwsh -f ./test.ps1 -bool:1

How to resolve the C:\fakepath?

Use

document.getElementById("file-id").files[0].name; 

instead of

document.getElementById('file-id').value

Arithmetic operation resulted in an overflow. (Adding integers)

int.MaxValue = 2147483647
2055786000 + 93552000 = 2149338000 > int.MaxValue

So you cannot store this number into an integer. You could use Int64 type which has a maximum value of 9,223,372,036,854,775,807.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

Getting assembly name

Assembly.GetExecutingAssembly().Location

PowerShell says "execution of scripts is disabled on this system."

Open cmd instead of powershell. This helped for me...

How do you do a ‘Pause’ with PowerShell 2.0?

I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.

<1> ReadKey (System.Console)

write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Disadvantage: Does not work in PS-ISE.

<2> ReadKey (RawUI)

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Does not exclude modifier keys.

<3> cmd

cmd /c Pause | Out-Null
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Visibly launches new shell/window on first use; not noticeable on subsequent use but still has the overhead

<4> Read-Host

Read-Host -Prompt "Press Enter to continue"
  • Advantage: Works in PS-ISE.
  • Disadvantage: Accepts only Enter key.

<5> ReadKey composite

This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.

Function Pause ($Message = "Press any key to continue . . . ") {
    if ((Test-Path variable:psISE) -and $psISE) {
        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
    }
    else {     
        Write-Host -NoNewline $Message
        [void][System.Console]::ReadKey($true)
        Write-Host
    }
}
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE (though only with Enter or mouse click)
  • Disadvantage: Not a one-liner!

Simple conversion between java.util.Date and XMLGregorianCalendar

I too had this kind of headache. Got rid of of it by simply representing time fields as primitive long in my POJO. Now the generation of my WS client code handle everything correctly and no more XML-to-Java crap. And of course dealing with millis on the Java side is simple and painless. KISS principle rocks!

Cleaning up old remote git branches

Deletion is always a challenging task and can be dangerous!!! Therefore, first execute the following command to see what will happen:

git push --all --prune --dry-run

By doing so like the above, git will provide you with a list of what would happen if the below command is executed.

Then run the following command to remove all branches from the remote repo that are not in your local repo:

git push --all --prune

Flash CS4 refuses to let go

I have found one related behaviour that may help (sounds like your specific problem runs deeper though):

Flash checks whether a source file needs recompiling by looking at timestamps. If its compiled version is older than the source file, it will recompile. But it doesn't check whether the compiled version was generated from the same source file or not.

Specifically, if you have your actionscript files under version control, and you Revert a change, the reverted file will usually have an older timestamp, and Flash will ignore it.

Importing two classes with same name. How to handle?

You can import one of them using import. For all other similar class , you need to specify Fully qualified class names. Otherwise you will get compilation error.

Eg:

import java.util.Date;

class Test{

  public static void main(String [] args){

    // your own date
    my.own.Date myOwndate ;

    // util.Date
    Date utilDate;
  }
}

What does elementFormDefault do in XSD?

I have noticed that XMLSpy(at least 2011 version)needs a targetNameSpace defined if elementFormDefault="qualified" is used. Otherwise won't validate. And also won't generate xmls with namespace prefixes

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Send mail via Gmail with PowerShell V2's Send-MailMessage

I used Christian's Feb 12 solution and I'm also just beginning to learn PowerShell. As far as attachments, I was poking around with Get-Member learning how it works and noticed that Send() has two definitions... the second definition takes a System.Net.Mail.MailMessage object which allows for Attachments and many more powerful and useful features like Cc and Bcc. Here's an example that has attachments (to be mixed with his above example):

# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)

Enjoy!

Try/catch does not seem to have an effect

I was able to duplicate your result when trying to run a remote WMI query. The exception thrown is not caught by the Try/Catch, nor will a Trap catch it, since it is not a "terminating error". In PowerShell, there are terminating errors and non-terminating errors . It appears that Try/Catch/Finally and Trap only works with terminating errors.

It is logged to the $error automatic variable and you can test for these type of non-terminating errors by looking at the $? automatic variable, which will let you know if the last operation succeeded ($true) or failed ($false).

From the appearance of the error generated, it appears that the error is returned and not wrapped in a catchable exception. Below is a trace of the error generated.

PS C:\scripts\PowerShell> Trace-Command -Name errorrecord  -Expression {Get-WmiObject win32_bios -ComputerName HostThatIsNotThere}  -PSHost
DEBUG: InternalCommand Information: 0 :  Constructor Enter Ctor
Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
DEBUG: InternalCommand Information: 0 :  Constructor Leave Ctor
Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
DEBUG: ErrorRecord Information: 0 :  Constructor Enter Ctor
System.Management.Automation.ErrorRecord: 19621801 exception =
System.Runtime.InteropServices.COMException (0x800706BA): The RPC
server is unavailable. (Exception from HRESULT: 0x800706BA)
   at
System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementScope.InitializeGuts(Object o)
   at System.Management.ManagementScope.Initialize()
   at System.Management.ManagementObjectSearcher.Initialize()
   at System.Management.ManagementObjectSearcher.Get()
   at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
errorId = GetWMICOMException errorCategory = InvalidOperation
targetObject =
DEBUG: ErrorRecord Information: 0 :  Constructor Leave Ctor
System.Management.Automation.ErrorRecord: 19621801

A work around for your code could be:

try
{
    $colItems = get-wmiobject -class "Win32_PhysicalMemory" -namespace "root\CIMV2" -computername $strComputerName -Credential $credentials
    if ($?)
    {
      foreach ($objItem in $colItems) 
      {
          write-host "Bank Label: " $objItem.BankLabel
          write-host "Capacity: " ($objItem.Capacity / 1024 / 1024)
          write-host "Caption: " $objItem.Caption
          write-host "Creation Class Name: " $objItem.CreationClassName      
          write-host
      }
    }
    else
    {
       throw $error[0].Exception
    }

Help with packages in java - import does not work

Just add classpath entry ( I mean your parent directory location) under System Variables and User Variables menu ... Follow : Right Click My Computer>Properties>Advanced>Environment Variables

How do I find the current machine's full hostname in C (hostname and domain information)?

I believe you are looking for:

gethostbyaddress

Just pass it the localhost IP.

There is also a gethostbyname function, that is also usefull.

Windows could not start the Apache2 on Local Computer - problem

if you are using windows os and believe that skype is not the suspect, then you might want to check the task manager and check the "Show processes from all users" and make sure that there is NO entry for httpd.exe. Otherwise, end its process. That solves my problem.

Regex for parsing directory and filename

In languages that support regular expressions with non-capturing groups:

((?:[^/]*/)*)(.*)

I'll explain the gnarly regex by exploding it...

(
  (?:
    [^/]*
    /
  )
  *
)
(.*)

What the parts mean:

(  -- capture group 1 starts
  (?:  -- non-capturing group starts
    [^/]*  -- greedily match as many non-directory separators as possible
    /  -- match a single directory-separator character
  )  -- non-capturing group ends
  *  -- repeat the non-capturing group zero-or-more times
)  -- capture group 1 ends
(.*)  -- capture all remaining characters in group 2

Example

To test the regular expression, I used the following Perl script...

#!/usr/bin/perl -w

use strict;
use warnings;

sub test {
  my $str = shift;
  my $testname = shift;

  $str =~ m#((?:[^/]*/)*)(.*)#;

  print "$str -- $testname\n";
  print "  1: $1\n";
  print "  2: $2\n\n";
}

test('/var/log/xyz/10032008.log', 'absolute path');
test('var/log/xyz/10032008.log', 'relative path');
test('10032008.log', 'filename-only');
test('/10032008.log', 'file directly under root');

The output of the script...

/var/log/xyz/10032008.log -- absolute path
  1: /var/log/xyz/
  2: 10032008.log

var/log/xyz/10032008.log -- relative path
  1: var/log/xyz/
  2: 10032008.log

10032008.log -- filename-only
  1:
  2: 10032008.log

/10032008.log -- file directly under root
  1: /
  2: 10032008.log

Elevating process privilege programmatically?

This code puts the above all together and restarts the current wpf app with admin privs:

if (IsAdministrator() == false)
{
    // Restart program and run as admin
    var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
    startInfo.Verb = "runas";
    System.Diagnostics.Process.Start(startInfo);
    Application.Current.Shutdown();
    return;
}

private static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}


// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)

Update: The app manifest way is preferred:

Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.

A problem with the original way: If you put the restart code in app.xaml.cs OnStartup, it still may start the main window briefly even though Shutdown was called. My main window blew up if app.xaml.cs init was not run and in certain race conditions it would do this.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

An old thread, but since I didn't find it elsewhere, here is one more possibility:

If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true" attribute

enter image description here

This tells tomcat to map the servlets using data given in web.xml instead of using the @WebServlet annotation.

CSS list item width/height does not work

Declare the a element as display: inline-block and drop the width and height from the li element.

Alternatively, apply a float: left to the li element and use display: block on the a element. This is a bit more cross browser compatible, as display: inline-block is not supported in Firefox <= 2 for example.

The first method allows you to have a dynamically centered list if you give the ul element a width of 100% (so that it spans from left to right edge) and then apply text-align: center.

Use line-height to control the text's Y-position inside the element.

Line break in SSRS expression

I've always had luck with the Chr(10) & Chr(13) - I have provided a sample below. This is an expression for an address text box I have in a report.

=Iif(Fields!GUAR_STREET_2.Value <> "",Fields!GUAR_STREET.Value & Chr(10) & Chr(13) & LTrim(Fields!GUAR_STREET_2.Value),Fields!GUAR_STREET.Value)

Also, if you are building a string you need to concatenate stuff together with an & not a + Here is what I think your example should look like

    =IIF(First(Fields!VCHTYPE.Value, "Dataset1")="C","This is a huge paragrpah of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) &  Chr(10) & Chr(13) & "Its not working though."
, "This is the second huge paragraph of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "Its not working though." )

Serialize an object to XML

Or you can add this method to your object:

    public void Save(string filename)
    {
        var ser = new XmlSerializer(this.GetType());
        using (var stream = new FileStream(filename, FileMode.Create))
            ser.Serialize(stream, this);
    }

How to put text over images in html?

The <img> element is empty — it doesn't have an end tag.

If the image is a background image, use CSS. If it is a content image, then set position: relative on a container, then absolutely position the image and/or text within it.

Number of elements in a javascript object

To do this in any ES5-compatible environment

Object.keys(obj).length

(Browser support from here)
(Doc on Object.keys here, includes method you can add to non-ECMA5 browsers)

Singleton in Android

EDIT :

The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.


Could you post an example from your code ?

Take a look at this gist : https://gist.github.com/Akayh/5566992

it works but it was done very quickly :

MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")

Set new value to mString : "Singleton"

Launch activityB and show the mString value. "Singleton" appears...

How to define Singleton in TypeScript

This is the simplest way

class YourSingletoneClass {
  private static instance: YourSingletoneClass;

  private constructor(public ifYouHaveAnyParams: string) {

  }
  static getInstance() {
    if(!YourSingletoneClass.instance) {
      YourSingletoneClass.instance = new YourSingletoneClass('If you have any params');
    }
    return YourSingletoneClass.instance;
  }
}

mysql: SOURCE error 2?

I was having this issue and it turns out if you are using wamp server to run mysql, you have to use the file path within the wamp64 folder. So when the absolute path is: C:/wamp64/www/foldername/filename.sql The path you have to use is: www/foldername/filename.sql

How to close existing connections to a DB

In more recent versions of SQL Server Management studio, you can now right click on a database and 'Take Database Offline'. This gives you the option to Drop All Active Connections to the database.

List vs tuple, when to use each?

But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?

For input parameters it's best to accept the most generic interface that does what you need. It is seldom just a tuple or list - more often it's sequence, sliceable or even iterable. Python's duck typing usually gets it for free, unless you explicitly check input types. Don't do that unless absolutely unavoidable.

For the data that you produce (output parameters) just return what's most convenient for you, e.g. return whatever datatype you keep or whatever your helper function returns.

One thing to keep in mind is to avoid returning a list (or any other mutable) that's part of your state, e.g.

class ThingsKeeper
    def __init__(self):
        self.__things = []

    def things(self):
        return self.__things  #outside objects can now modify your state

    def safer(self):
        return self.__things[:]  #it's copy-on-write, shouldn't hurt performance

Find and replace in file and overwrite file doesn't work, it empties the file

You can use Vim in Ex mode:

ex -sc '%s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g|x' index.html
  1. % select all lines

  2. x save and close

Git - deleted some files locally, how do I get them from a remote repository

Also, I add to do the following steps so that the git repo would be correctly linked with the IDE:

 $ git reset <commit #>

 $ git checkout <file/path>

I hope this was helpful!!

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

How do I make a Mac Terminal pop-up/alert? Applescript?

And my 15 cent. A one liner for the mac terminal etc just set the MIN= to whatever and a message

MIN=15 && for i in $(seq $(($MIN*60)) -1 1); do echo "$i, "; sleep 1; done; echo -e "\n\nMac Finder should show a popup" afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Look away. Rest your eyes"'

A bonus example for inspiration to combine more commands; this will put a mac put to standby sleep upon the message too :) the sudo login is needed then, a multiplication as the 60*2 for two hours goes aswell

sudo su
clear; echo "\n\nPreparing for a sleep when timers done \n"; MIN=60*2 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done; echo "\n\n Time to sleep  zzZZ";  afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Time to sleep zzZZ"'; shutdown -h +1 -s

Get div height with plain JavaScript

The other answers weren't working for me. Here's what I found at w3schools, assuming the div has a height and/or width set.

All you need is height and width to exclude padding.

    var height = document.getElementById('myDiv').style.height;
    var width = document.getElementById('myDiv').style.width;

You downvoters: This answer has helped at least 5 people, judging by the upvotes I've received. If you don't like it, tell me why so I can fix it. That's my biggest pet peeve with downvotes; you rarely tell me why you downvote it.

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

The model backing the <Database> context has changed since the database was created

After some research on this topic, I found that the error is occured basically if you have an instance of db created previously on your local sql server express. So whenever you have updates on db and try to update the db/run some code on db without running Update Database command using Package Manager Console; first of all, you have to delete previous db on our local sql express manually.

Also, this solution works unless you have AutomaticMigrationsEnabled = false;in your Configuration.

If you work with a version control system (git,svn,etc.) and some other developers update db objects in production phase then this error rises whenever you update your code base and run the application.

As stated above, there are some solutions for this on code base. However, this is the most practical one for some cases.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

For me the fix was to right click on my webapp module > Maven > Update Project

adb command not found in linux environment

updating the $PATH did not work for me, therefore I added a symbolic link to adb to make it work, as follows:

ln -s <android-sdk-folder>/platform-tools/adb <android-sdk-folder>/tools/adb

What is the purpose of the return statement?

return means, "output this value from this function".

print means, "send this value to (generally) stdout"

In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).

This is an example of print:

>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

This is an example of return:

>>> def getN():
...    return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I solved the error by modifying the following property in hibernate.cfg.xml

  <property name="hibernate.hbm2ddl.auto">validate</property>

Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.

Matplotlib tight_layout() doesn't take into account figure suptitle

An alternative and simple to use solution is to adjust the coordinates of the suptitle text in the figure using the y argument in the call of suptitle (see the docs):

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', y=1.05, fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.show()

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

When to use StringBuilder in Java

As a general rule, always use the more readable code and only refactor if performance is an issue. In this specific case, most recent JDK's will actually optimize the code into the StringBuilder version in any case.

You usually only really need to do it manually if you are doing string concatenation in a loop or in some complex code that the compiler can't easily optimize.

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

Well in my case, I just rename the Bundle Name and Executable file values in info.plist same as project name. It worked for me.

nano error: Error opening terminal: xterm-256color

After upgrading to OSX Lion, I started getting this error on certain (Debian/Ubuntu) servers. The fix is simply to install the “ncurses-term” package which provides the file /usr/share/terminfo/x/xterm-256color.

This worked for me on a Ubuntu server, via Erik Osterman.

How do you implement a circular buffer in C?

The simplest solution would be to keep track of the item size and the number of items, and then create a buffer of the appropriate number of bytes:

typedef struct circular_buffer
{
    void *buffer;     // data buffer
    void *buffer_end; // end of data buffer
    size_t capacity;  // maximum number of items in the buffer
    size_t count;     // number of items in the buffer
    size_t sz;        // size of each item in the buffer
    void *head;       // pointer to head
    void *tail;       // pointer to tail
} circular_buffer;

void cb_init(circular_buffer *cb, size_t capacity, size_t sz)
{
    cb->buffer = malloc(capacity * sz);
    if(cb->buffer == NULL)
        // handle error
    cb->buffer_end = (char *)cb->buffer + capacity * sz;
    cb->capacity = capacity;
    cb->count = 0;
    cb->sz = sz;
    cb->head = cb->buffer;
    cb->tail = cb->buffer;
}

void cb_free(circular_buffer *cb)
{
    free(cb->buffer);
    // clear out other fields too, just to be safe
}

void cb_push_back(circular_buffer *cb, const void *item)
{
    if(cb->count == cb->capacity){
        // handle error
    }
    memcpy(cb->head, item, cb->sz);
    cb->head = (char*)cb->head + cb->sz;
    if(cb->head == cb->buffer_end)
        cb->head = cb->buffer;
    cb->count++;
}

void cb_pop_front(circular_buffer *cb, void *item)
{
    if(cb->count == 0){
        // handle error
    }
    memcpy(item, cb->tail, cb->sz);
    cb->tail = (char*)cb->tail + cb->sz;
    if(cb->tail == cb->buffer_end)
        cb->tail = cb->buffer;
    cb->count--;
}

error: cast from 'void*' to 'int' loses precision

You can cast it to an intptr_t type. It's an int type guaranteed to be big enough to contain a pointer. Use #include <cstdint> to define it.

How to directly execute SQL query in C#?

IMPORTANT NOTE: You should not concatenate SQL queries unless you trust the user completely. Query concatenation involves risk of SQL Injection being used to take over the world, ...khem, your database.

If you don't want to go into details how to execute query using SqlCommand then you could call the same command line like this:

string userInput = "Brian";
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS  
     -s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
     tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);

process.StartInfo = startInfo;
process.Start();

Just ensure that you escape each double quote " with ""

How to map with index in Ruby?

module Enumerable
  def map_with_index(&block)
    i = 0
    self.map { |val|
      val = block.call(val, i)
      i += 1
      val
    }
  end
end

["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]

How to get a MemoryStream from a Stream in .NET?

You will have to read in all the data from the Stream object into a byte[] buffer and then pass that into the MemoryStream via its constructor. It may be better to be more specific about the type of stream object you are using. Stream is very generic and may not implement the Length attribute, which is rather useful when reading in data.

Here's some code for you:

public MyClass(Stream inputStream) {
    byte[] inputBuffer = new byte[inputStream.Length];
    inputStream.Read(inputBuffer, 0, inputBuffer.Length);

    _ms = new MemoryStream(inputBuffer);
}

If the Stream object doesn't implement the Length attribute, you will have to implement something like this:

public MyClass(Stream inputStream) {
    MemoryStream outputStream = new MemoryStream();

    byte[] inputBuffer = new byte[65535];
    int readAmount;
    while((readAmount = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
        outputStream.Write(inputBuffer, 0, readAmount);

    _ms = outputStream;
}

Unable to read repository at http://download.eclipse.org/releases/indigo

I spent whole my day figuring out this and found the following. And it works great now.

This is basically an issue with your gateway or proxy, If you are under proxy network, Please go to the network settings and set the proxy server settings(server, port , user name and password). If you are under direct gateway network, your firewall may be blocking the http get request from your eclipse.

How do I add 1 day to an NSDate?

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSLog(@"StartDate = %@", startDate);

components.day += 1;
NSDate *endDate = [calendar dateFromComponents:components];
NSLog(@"EndDate = %@", endDate);

document.getElementById().value doesn't set the value

The problem is clearly not with the javascript. Here's a quick snippet to show you the working of the code.

document.getElementById('points').value = 100;

http://jsfiddle.net/eqTm2/1/

As you can see, the javascript perfectly assigns the new value to the input element. It would be helpful if you could elaborate more on the issue.

What is the parameter "next" used for in Express?

I also had problem understanding next() , but this helped

var app = require("express")();

app.get("/", function(httpRequest, httpResponse, next){
    httpResponse.write("Hello");
    next(); //remove this and see what happens 
});

app.get("/", function(httpRequest, httpResponse, next){
    httpResponse.write(" World !!!");
    httpResponse.end();
});

app.listen(8080);

How to specify a port number in SQL Server connection string?

For JDBC the proper format is slightly different and as follows:

jdbc:microsoft:sqlserver://mycomputer.test.xxx.com:49843

Note the colon instead of the comma.

Where do I find old versions of Android NDK?

Looks like you can construct the link to the NDK that you want and download it from dl.google.com:

Linux example:
http://dl.google.com/android/ndk/android-ndk-r9b-linux-x86.tar.bz2 http://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64.tar.bz2

OS X example:
http://dl.google.com/android/ndk/android-ndk-r9b-darwin-x86.tar.bz2 http://dl.google.com/android/ndk/android-ndk-r9b-darwin-x86_64.tar.bz2

Windows example:
http://dl.google.com/android/ndk/android-ndk-r9b-windows.zip

Extensions up to r10b:
.tar.bz2 for linux / os x and .zip for windows.

Since r10c the extensions have changed to:
.bin for linux / os x and .exe for windows

Since r11:

.zip for linux and OS X as well, a new URL base, and no 32 bit versions for OS X and linux.

https://dl.google.com/android/repository/android-ndk-r11-linux-x86_64.zip

Parenthesis/Brackets Matching using Stack algorithm

//basic code non strack algorithm just started learning java ignore space and time.
/// {[()]}[][]{}
// {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))-> 
//Split string to substring {[()]}, next [], next [], next{}

public class testbrackets {
    static String stringfirst;
    static String stringsecond;
    static int open = 0;
    public static void main(String[] args) {
        splitstring("(()){}()");
    }
static void splitstring(String str){

    int len = str.length();
    for(int i=0;i<=len-1;i++){
        stringfirst="";
        stringsecond="";
        System.out.println("loop starttttttt");
        char a = str.charAt(i);
    if(a=='{'||a=='['||a=='(')
    {
        open = open+1;
        continue;
    }
    if(a=='}'||a==']'||a==')'){
        if(open==0){
            System.out.println(open+"started with closing brace");
            return;
        }
        String stringfirst=str.substring(i-open, i);
        System.out.println("stringfirst"+stringfirst);
        String stringsecond=str.substring(i, i+open);
        System.out.println("stringsecond"+stringsecond);
        replace(stringfirst, stringsecond);

        }
    i=(i+open)-1;
    open=0;
    System.out.println(i);
    }
    }
    static void replace(String stringfirst, String stringsecond){
        stringfirst = stringfirst.replace('{', '}');
        stringfirst = stringfirst.replace('(', ')');
        stringfirst = stringfirst.replace('[', ']');
        StringBuilder stringfirst1 = new StringBuilder(stringfirst);
        stringfirst = stringfirst1.reverse().toString();
    System.out.println("stringfirst"+stringfirst);
    System.out.println("stringsecond"+stringsecond);
if(stringfirst.equals(stringsecond)){
    System.out.println("pass");
}
    else{
        System.out.println("fail");
        System.exit(0);
        }
    }
}

Query to check index on a table

First you check your table id (aka object_id)

SELECT * FROM sys.objects WHERE type = 'U' ORDER BY name

then you can get the column's names. For example assuming you obtained from previous query the number 4 as object_id

SELECT c.name
FROM sys.index_columns ic
INNER JOIN sys.columns c ON  c.column_id = ic.column_id
WHERE ic.object_id = 4 
AND c.object_id = 4

AttributeError: Can only use .dt accessor with datetimelike values

When you write

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')

It can fixed

Of Countries and their Cities

Check this out:

Cities of the world database donated by MaxMind.com

The company MaxMind.com1 has agreed to release their cities of the world database under the GPL. The database contains locations by country, city, latitude and longitude. There are over 3,047,000 records in the database. For those of you who have tried the location.module with the zipcodes database from CivicSpace, you will recognize how cool it is and how well this fits with that project and therefore Drupal.

Here's another free one that might help you get started.

Creating and maintaining such a database is quite a bit of work - so anyone who's done it is likely keeping it to themselves, or offering it for a fee.

How to vertically center a "div" element for all browsers using CSS?

Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and working for recent versions of Firefox, Opera, Chrome, and Safari.

_x000D_
_x000D_
.outer {_x000D_
  display: table;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.middle {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  width: 400px;_x000D_
  /*whatever width you want*/_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="middle">_x000D_
    <div class="inner">_x000D_
      <h1>The Content</h1>_x000D_
      <p>Once upon a midnight dreary...</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View A Working Example With Dynamic Content

I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also -- lightbox, pop-up, etc.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I don't have enough context to give you a correct answer, but I'll suggest you to make you code immutable as much as possible. Use public final fields. No more getters or setters : every field has to be defined by the constructor. Your code is shorter, more readable and prevents you from writing code with side effects.

It doesn't prevent you from passing null arguments to your constructor though... You can still check every argument as suggested by @cletus, but I'll suggest you to throw IllegalArgumentException instead of NullPointerException that doesn't give no new hint about what you've done.

Anyway, that's what I do as much as I can and it improved my code (readability, stability) to a great extend. Everyone in my team does so and we are very happy with that. We learned that when we try to write some erlang code where everything is immutable.

Hope this helps.

Sieve of Eratosthenes - Finding Primes Python

A simple speed hack: when you define the variable "primes," set the step to 2 to skip all even numbers automatically, and set the starting point to 1.

Then you can further optimize by instead of for i in primes, use for i in primes[:round(len(primes) ** 0.5)]. That will dramatically increase performance. In addition, you can eliminate numbers ending with 5 to further increase speed.

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

could not extract ResultSet in hibernate

Another potential cause, for other people coming across the same error message is that this error will occur if you are accessing a table in a different schema from the one you have authenticated with.

In this case you would need to add the schema name to your entity entry:

@Table(name= "catalog", schema = "targetSchemaName")

Move branch pointer to different commit without checkout

For the checked out branch, in the case the commit you want to point to is ahead of the current branch (which should be the case unless you want to undo the last commits of the current branch), you can simply do:

git merge --ff-only <commit>

This makes a softer alternative to git reset --hard, and will fail if you are not in the case described above.

To do the same thing for a non checked out branch, the equivalent would be:

git push . <commit>:<branch>

Using current time in UTC as default value in PostgreSQL

Wrap it in a function:

create function now_utc() returns timestamp as $$
  select now() at time zone 'utc';
$$ language sql;

create temporary table test(
  id int,
  ts timestamp without time zone default now_utc()
);

What's the difference between an Angular component and module

A module in Angular 2 is something which is made from components, directives, services etc. One or many modules combine to make an Application. Modules breakup application into logical pieces of code. Each module performs a single task.

Components in Angular 2 are classes where you write your logic for the page you want to display. Components control the view (html). Components communicate with other components and services.

How to set a binding in Code?

You need to change source to viewmodel object:

myBinding.Source = viewModelObject;

How can I quantify difference between two images?

Two popular and relatively simple methods are: (a) the Euclidean distance already suggested, or (b) normalized cross-correlation. Normalized cross-correlation tends to be noticeably more robust to lighting changes than simple cross-correlation. Wikipedia gives a formula for the normalized cross-correlation. More sophisticated methods exist too, but they require quite a bit more work.

Using numpy-like syntax,

dist_euclidean = sqrt(sum((i1 - i2)^2)) / i1.size

dist_manhattan = sum(abs(i1 - i2)) / i1.size

dist_ncc = sum( (i1 - mean(i1)) * (i2 - mean(i2)) ) / (
  (i1.size - 1) * stdev(i1) * stdev(i2) )

assuming that i1 and i2 are 2D grayscale image arrays.

Force the origin to start at 0

Simply add these to your ggplot:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

Example

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

enter image description here

Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge' could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.

libstdc++.so.6: cannot open shared object file: No such file or directory

/usr/local/cilk/bin/../lib32/pinbin is dynamically linked to a library libstdc++.so.6 which is not present anymore. You need to recompile Cilk

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

Do something if screen width is less than 960 px

You can also use a media query with javascript.

const mq = window.matchMedia( "(min-width: 960px)" );

if (mq.matches) {
       alert("window width >= 960px");
} else {
     alert("window width < 960px");
}

How to specify HTTP error code?

A simple one liner;

res.status(404).send("Oh uh, something went wrong");

Move column by name to front of table in pandas

The most simplist thing you can try is:

df=df[[ 'Mid',   'Upper',   'Lower', 'Net'  , 'Zsore']]

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

How to list files in an android directory?

I just discovered that:

new File("/sdcard/").listFiles() returns null if you do not have:

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

set in your AndroidManifest.xml file.

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

How to cast/convert pointer to reference in C++

Call it like this:

foo(*ob);

Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.

What is ViewModel in MVC?

MVC doesn't have a viewmodel: it has a model, view and controller. A viewmodel is part of MVVM (Model-View-Viewmodel). MVVM is derived from the Presentation Model and is popularized in WPF. There should also be a model in MVVM, but most people miss the point of that pattern completely and they will only have a view and a viewmodel. The model in MVC is similar to the model in MVVM.

In MVC the process is split into 3 different responsibilities:

  • View is responsible for presenting the data to the user
  • A controller is responsible for the page flow
  • A model is responsible for the business logic

MVC is not very suitable for web applications. It is a pattern introduced by Smalltalk for creating desktop applications. A web environment behaves completely different. It doesn't make much sense to copy a 40-year old concept from the desktop development and paste it into a web enviroment. However a lot of people think this is ok, because their application compiles and returns the correct values. That is, in my opinion, not enough to declare a certain design choice as ok.

An example of a model in a web application could be:

public class LoginModel
{
    private readonly AuthenticationService authentication;

    public LoginModel(AuthenticationService authentication)
    {
        this.authentication = authentication;
    }

    public bool Login()
    {
        return authentication.Login(Username, Password);
    }

    public string Username { get; set; }
    public string Password { get; set; }
}

The controller can use it like this:

public class LoginController
{
    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        bool success = model.Login();

        if (success)
        {
            return new RedirectResult("/dashboard");
        }
        else
        {
            TempData["message"] = "Invalid username and/or password";
            return new RedirectResult("/login");
        }
    }
}

Your controller methods and your models will be small, easily testable and to the point.

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

How to implement infinity in Java?

I'm supposing you're using integer math for a reason. If so, you can get a result that's functionally nearly the same as POSITIVE_INFINITY by using the MAX_VALUE field of the Integer class:

Integer myInf = Integer.MAX_VALUE;

(And for NEGATIVE_INFINITY you could use MIN_VALUE.) There will of course be some functional differences, e.g., when comparing myInf to a value that happens to be MAX_VALUE: clearly this number isn't less than myInf. Also, as noted in the comments below, incrementing positive infinity will wrap you back around to negative numbers (and decrementing negative infinity will wrap you back to positive).

There's also a library that actually has fields POSITIVE_INFINITY and NEGATIVE_INFINITY, but they are really just new names for MAX_VALUE and MIN_VALUE.

How to have EditText with border in Android Lollipop

You can do it using xml.

Create an xml layout and name it like my_edit_text_border.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff"/>
            <corners android:radius="5dp" />
            <stroke
                android:width="2dp"
                android:color="#949494"
                />
        </shape>
    </item>
</selector>

Add background to your Edittext

<EditText
 android:id="@+id/editText1"
 ..
 android:background="@layout/my_edit_text_border">

Send POST data via raw json with postman

Unlike jQuery in order to read raw JSON you will need to decode it in PHP.

print_r(json_decode(file_get_contents("php://input"), true));

php://input is a read-only stream that allows you to read raw data from the request body.

$_POST is form variables, you will need to switch to form radiobutton in postman then use:

foo=bar&foo2=bar2

To post raw json with jquery:

$.ajax({
    "url": "/rest/index.php",
    'data': JSON.stringify({foo:'bar'}),
    'type': 'POST',
    'contentType': 'application/json'
});

How to Rotate a UIImage 90 degrees?

Swift 4.2 version of RawMean's answer:

extension UIImage {

func rotated(byDegrees degree: Double) -> UIImage {
    let radians = CGFloat(degree * .pi) / 180.0 as CGFloat
    let rotatedSize = self.size
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(rotatedSize, false, scale)
    let bitmap = UIGraphicsGetCurrentContext()
    bitmap?.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
    bitmap?.rotate(by: radians)
    bitmap?.scaleBy(x: 1.0, y: -1.0)
    bitmap?.draw(
        self.cgImage!,
        in: CGRect.init(x: -self.size.width / 2, y: -self.size.height / 2 , width: self.size.width, height: self.size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext() // this is needed
    return newImage!
}

}

Monad in plain English? (For the OOP programmer with no FP background)

If you've ever used Powershell, the patterns Eric described should sound familiar. Powershell cmdlets are monads; functional composition is represented by a pipeline.

Jeffrey Snover's interview with Erik Meijer goes into more detail.

javascript - match string against the array of regular expressions

http://jsfiddle.net/9nyhh/1/

var thisExpressions = [/something/, /something_else/, /and_something_else/];
var thisExpressions2 = [/else/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray(string, expressions) {

    var len = expressions.length,
        i = 0;

    for (; i < len; i++) {
        if (string.match(expressions[i])) {
            return true;
        }
    }

    return false;

};

setTimeout(function() {
    console.log(matchInArray(thisString, thisExpressions));
    console.log(matchInArray(thisString, thisExpressions2));
}, 200)?

Django 1.7 - makemigrations not detecting changes

My solution was not covered here so I'm posting it. I had been using syncdb for a project–just to get it up and running. Then when I tried to start using Django migrations, it faked them at first then would say it was 'OK' but nothing was happening to the database.

My solution was to just delete all the migration files for my app, as well as the database records for the app migrations in the django_migrations table.

Then I just did an initial migration with:

./manage.py makemigrations my_app

followed by:

./manage.py migrate my_app

Now I can make migrations without a problem.

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

There are certain common things between lock_guard and unique_lock and certain differences.

But in the context of the question asked, the compiler does not allow using a lock_guard in combination with a condition variable, because when a thread calls wait on a condition variable, the mutex gets unlocked automatically and when other thread/threads notify and the current thread is invoked (comes out of wait), the lock is re-acquired.

This phenomenon is against the principle of lock_guard. lock_guard can be constructed only once and destructed only once.

Hence lock_guard cannot be used in combination with a condition variable, but a unique_lock can be (because unique_lock can be locked and unlocked several times).

What are some great online database modeling tools?

S.Lott inserted a comment, but it should be an answer: see the same question.

EDIT

Since it wasn't as obvious as I intended it to be, here follows a verbatim copy of S.Lott's answer in the other question:

I'm a big fan of ARGO UML from Tigris.org. Draws nice pictures using standard UML notation. It does some code generation, but mostly Java classes, which isn't SQL DDL, so that may not be close enough to what you want to do.

You can look at the Data Modelling Tools list and see if anything there is better than Argo UML. Many of the items on this list are free or cheap.

Also, if you're using Eclipse or NetBeans, there are many design plug-ins, some of which may have the features you're looking for.

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The solution can be found here https://github.com/spring-projects/spring-framework/issues/22734

you can create two separate post request mappings. For example.

@PostMapping(path = "/test", consumes = "application/json")
public String test(@RequestBody User user) {
  return user.toString();
}

@PostMapping(path = "/test", consumes = "application/x-www-form-urlencoded")
public String test(User user) {
  return user.toString();
}

LDAP filter for blank (empty) attribute

This article http://technet.microsoft.com/en-us/library/ee198810.aspx led me to the solution. The only change is the placement of the exclamation mark.

(!manager=*)

It seems to be working just as wanted.

How to kill a thread instantly in C#?

You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.

Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.

In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.

The code that tries to stop the thread should do the following:

running_ = false;
threadInstance_.Interrupt();
if(!threadInstance_.Join(2000)) { // or an agreed resonable time
   threadInstance_.Abort();
}

Responsive css background images

background:url("img/content-bg.jpg") no-repeat;
background-position:center; 
background-size:cover;

or

background-size:100%;

Laravel PHP Command Not Found

Late answer...

Composer 1.10.1 2020-03-13 20:34:27 laravel --version Laravel Installer 3.0.1

Put export PATH=$PATH:~/.config/composer/vendor/bin:$PATH in your ~/.zshrc or ~/.bashrc source ~/.zshrc or ~/.bashrc This works

Fastest way to convert JavaScript NodeList to Array?

Here's a new cool way to do it using the ES6 spread operator:

let arr = [...nl];

LEFT OUTER JOIN in LINQ

Now as an extension method:

public static class LinqExt
{
    public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TKey> leftKey, Func<TRight, TKey> rightKey,
        Func<TLeft, TRight, TResult> result)
    {
        return left.GroupJoin(right, leftKey, rightKey, (l, r) => new { l, r })
             .SelectMany(
                 o => o.r.DefaultIfEmpty(),
                 (l, r) => new { lft= l.l, rght = r })
             .Select(o => result.Invoke(o.lft, o.rght));
    }
}

Use like you would normally use join:

var contents = list.LeftOuterJoin(list2, 
             l => l.country, 
             r => r.name,
            (l, r) => new { count = l.Count(), l.country, l.reason, r.people })

Hope this saves you some time.

How to position the Button exactly in CSS

I'd use absolute positioning:

#play_button {
    position:absolute;
transition: .5s ease;
    left: 202px;
    top: 198px;

}

CURL Command Line URL Parameters

Felipsmartins is correct.

It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.

Which means you can do this:

curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'

Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.

I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.

curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros

This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)

Hope it helps.

How to apply a CSS filter to a background image

The following is a simple solution for modern browsers in pure CSS with a 'before' pseudo element, like the solution from Matthew Wilcoxson.

To avoid the need of accessing the pseudo element for changing the image and other attributes in JavaScript, simply use inherit as the value and access them via the parent element (here body).

body::before {
    content: ""; /* Important */
    z-index: -1; /* Important */
    position: inherit;
    left: inherit;
    top: inherit;
    width: inherit;
    height: inherit;
    background-image: inherit;
    background-size: cover;
    filter: blur(8px);
}

body {
  background-image: url("xyz.jpg");
  background-size: 0 0;  /* Image should not be drawn here */
  width: 100%;
  height: 100%;
  position: fixed; /* Or absolute for scrollable backgrounds */
}

sql delete statement where date is greater than 30 days

To delete records from a table that have a datetime value in Date_column older than 30 days use this query:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < GETDATE() - 30

...or this:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(dd,-30,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 12 hours:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(hh,-12,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 15 minutes:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(mi,-15,GETDATE())

From: http://zarez.net/?p=542

How can I check if a view is visible or not in Android?

Or you could simply use

View.isShown()

What is the correct way to represent null XML elements?

It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null values is with the xsi:nil attribute.

[Source]

Convert a string to a double - is this possible?

Just use floatval().

E.g.:

$var = '122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343

And in case you wonder doubleval() is just an alias for floatval().

And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001 and this error could propagate.

pass **kwargs argument to another function with **kwargs

Because a dictionary is a single value. You need to use keyword expansion if you want to pass it as a group of keyword arguments.

How to format Joda-Time DateTime to only mm/dd/yyyy?

Note that in JAVA SE 8 a new java.time (JSR-310) package was introduced. This replaces Joda time, Joda users are advised to migrate. For the JAVA SE = 8 way of formatting date and time, see below.

Joda time

Create a DateTimeFormatter using DateTimeFormat.forPattern(String)

Using Joda time you would do it like this:

String dateTime = "11/15/2013 08:00:00";
// Format for input
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
DateTime jodatime = dtf.parseDateTime(dateTime);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("MM/dd/yyyy");
// Printing the date
System.out.println(dtfOut.print(jodatime));

Standard Java = 8

Java 8 introduced a new Date and Time library, making it easier to deal with dates and times. If you want to use standard Java version 8 or beyond, you would use a DateTimeFormatter. Since you don't have a time zone in your String, a java.time.LocalDateTime or a LocalDate, otherwise the time zoned varieties ZonedDateTime and ZonedDate could be used.

// Format for input
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
LocalDate date = LocalDate.parse(dateTime, inputFormat);
// Format for output
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
// Printing the date
System.out.println(date.format(outputFormat));

Standard Java < 8

Before Java 8, you would use the a SimpleDateFormat and java.util.Date

String dateTime = "11/15/2013 08:00:00";
// Format for input
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// Parsing the date
Date date7 = dateParser.parse(dateTime);
// Format for output
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
// Printing the date
System.out.println(dateFormatter.format(date7));

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

use mysql_real_escape_string() instead of mysqli_real_escape_string()

like so:

$username = mysql_real_escape_string($_POST['username']);

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

Change the image source on rollover using jQuery

$('img.over').each(function(){
    var t=$(this);
    var src1= t.attr('src'); // initial src
    var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
    t.hover(function(){
        $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension   
    }, function(){
        $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
    });
});

You may want to change the class of images from first line. If you need more image classes (or different path) you may use

$('img.over, #container img, img.anotherOver').each(function(){

and so on.

It should work, I didn't test it :)

Get total size of file in bytes

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How can I force browsers to print background images in CSS?

it is working in google chrome when you add !important attribute to background image make sure you add attribute first and try again, you can do it like that

    .inputbg {
background: url('inputbg.png') !important;  

}

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Django download a file

Reference:

In view.py Implement function like,

def download(request, id):
    obj = your_model_name.objects.get(id=id)
    filename = obj.model_attribute_name.path
    response = FileResponse(open(filename, 'rb'))
    return response

Scraping data from website using vba

you can use winhttprequest object instead of internet explorer as it's good to load data excluding pictures n advertisement instead of downloading full webpage including advertisement n pictures those make internet explorer object heavy compare to winhttpRequest object.

how to remove untracked files in Git?

Those are untracked files. This means git isn't tracking them. It's only listing them because they're not in the git ignore file. Since they're not being tracked by git, git reset won't touch them.

If you want to blow away all untracked files, the simplest way is git clean -f (use git clean -n instead if you want to see what it would destroy without actually deleting anything). Otherwise, you can just delete the files you don't want by hand.

Cast Int to enum in Java

Here's the solution I plan to go with. Not only does this work with non-sequential integers, but it should work with any other data type you may want to use as the underlying id for your enum values.

public Enum MyEnum {
    THIS(5),
    THAT(16),
    THE_OTHER(35);

    private int id; // Could be other data type besides int
    private MyEnum(int id) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public static Map<Integer, MyEnum> buildMap() {
        Map<Integer, MyEnum> map = new HashMap<Integer, MyEnum>();
        MyEnum[] values = MyEnum.values();
        for (MyEnum value : values) {
            map.put(value.getId(), value);
        }

        return map;
    }
}

I only need to convert id's to enums at specific times (when loading data from a file), so there's no reason for me to keep the Map in memory at all times. If you do need the map to be accessible at all times, you can always cache it as a static member of your Enum class.

Ignore .classpath and .project from Git

If the .project and .classpath are already committed, then they need to be removed from the index (but not the disk)

git rm --cached .project
git rm --cached .classpath

Then the .gitignore would work (and that file can be added and shared through clones).
For instance, this gitignore.io/api/eclipse file will then work, which does include:

# Eclipse Core      
.project

# JDT-specific (Eclipse Java Development Tools)     
.classpath

Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR set to a shared folder accessible by all).
That template folder can contain an info/exclude file, with ignore rules that you want enforced for all repos, including the new ones (git init) that any user would use.


As commented by Abdollah

When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files .classpath and .project from the repo.

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

Having issues with a MySQL Join that needs to meet multiple conditions

You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR. For example WHERE a='1' AND (b='123' OR b='234').

SELECT u.*
FROM rooms AS u
JOIN facilities_r AS fu
ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
WHERE vizibility='1'
GROUP BY id_uc
ORDER BY u_premium desc, id_uc desc

What's the purpose of SQL keyword "AS"?

Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.

Example 1

SELECT P.ProductName,
       P.ProductGroup,
       P.ProductRetailPrice
FROM   Products AS P

Example 2

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products AS P
LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.

Example 4

SELECT P.ProductName AS "Product",
       P.ProductRetailPrice AS "Retail Price",
       O.Quantity AS "Quantity Ordered"
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Output of Example 4

Product             Retail Price     Quantity Ordered
Blue Raspberry Gum  $10 pk/$50 Case  2 Cases
Twizzler            $5 pk/$25 Case   10 Cases

Auto-redirect to another HTML page

Its a late answer, but as I can see most of the people mentioned about "refresh" method to redirect a webpage. As per W3C, we should not use "refresh" to redirect. Because it could break the "back" button. Imagine that the user presses the "back" button, the refresh would work again, and the user would bounce forward. The user will most likely get very annoyed, and close the window, which is probably not what you, as the author of this page, want.

Use HTTP redirects instead. One can refer the complete documentation here: W3C document

Link entire table row?

I feel like the simplest solution is sans javascript and simply putting the link in each cell (provided you don't have massive gullies between your cells or really think border lines). Have your css:

.tableClass td a{
   display: block;
}

and then add a link per cell:

<table class="tableClass">
    <tr>
        <td><a href="#link">Link name</a></td>
        <td><a href="#link">Link description</a></td>
        <td><a href="#link">Link somthing else</a></td>
    </tr>
</table>

boring but clean.

Laravel Pagination links not including other GET parameters

Include This In Your View Page

 $users->appends(Input::except('page'))

best way to create object

There's not really a best way. Both are quite the same, unless you want to do some additional processing using the parameters passed to the constructor during initialization or if you want to ensure a coherent state just after calling the constructor. If it is the case, prefer the first one.

But for readability/maintainability reasons, avoid creating constructors with too many parameters.

In this case, both will do.

How to keep indent for second line in ordered lists via CSS?

I believe you just need to put the list 'bullet' outside of the padding.

li {
    list-style-position: outside;
    padding-left: 1em;
}

In-place edits with sed on OS X

You can use:

sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>

Example:

sed -i -e 's/Hello/Bye/' file.txt

This works flawless in Mac.

C++: How to round a double to an int?

Casting to an int truncates the value. Adding 0.5 causes it to do proper rounding.

int y = (int)(x + 0.5);

ng-repeat finish event

If you simply want to execute some code at the end of the loop, here's a slightly simpler variation that doesn't require extra event handling:

<div ng-controller="Ctrl">
  <div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
    thing {{thing}}
  </div>
</div>
function Ctrl($scope) {
  $scope.things = [
    'A', 'B', 'C'  
  ];
}

angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
      // iteration is complete, do whatever post-processing
      // is necessary
      element.parent().css('border', '1px solid black');
    }
  };
});

See a live demo.

Generate unique random numbers between 1 and 100

Shuffling the numbers from 1 to 100 is the right basic strategy, but if you need only 8 shuffled numbers, there's no need to shuffle all 100 numbers.

I don't know Javascript very well, but I believe it's easy to create an array of 100 nulls quickly. Then, for 8 rounds, you swap the n'th element of the array (n starting at 0) with a randomly selected element from n+1 through 99. Of course, any elements not populated yet mean that the element would really have been the original index plus 1, so that's trivial to factor in. When you're done with the 8 rounds, the first 8 elements of your array will have your 8 shuffled numbers.

Cannot run the macro... the macro may not be available in this workbook

I had the same problem as OP and found was due to the options declaration being misspelled:

' Comment comment  

Options Explicit  

Sub someMacroMakechart()

in a sub module, instead of correct;

' Comment comment  

Option Explicit  

Sub someMacroMakechart()

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Other type of format :

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Create a Cumulative Sum Column in MySQL

Using a correlated query:


  SELECT t.id,
         t.count,
         (SELECT SUM(x.count)
            FROM TABLE x
           WHERE x.id <= t.id) AS cumulative_sum
    FROM TABLE t
ORDER BY t.id

Using MySQL variables:


  SELECT t.id,
         t.count,
         @running_total := @running_total + t.count AS cumulative_sum
    FROM TABLE t
    JOIN (SELECT @running_total := 0) r
ORDER BY t.id

Note:

  • The JOIN (SELECT @running_total := 0) r is a cross join, and allows for variable declaration without requiring a separate SET command.
  • The table alias, r, is required by MySQL for any subquery/derived table/inline view

Caveats:

  • MySQL specific; not portable to other databases
  • The ORDER BY is important; it ensures the order matches the OP and can have larger implications for more complicated variable usage (IE: psuedo ROW_NUMBER/RANK functionality, which MySQL lacks)

How to click a link whose href has a certain substring in Selenium?

You can do this:

//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));

//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
    if(linkList.get(i).getAttribute("href").contains("long"))
    {
        linkList.get(i).click();
        break;
    }
}

in this what we r doing is first we are finding all the <a> tags and storing them in a list.After that we are iterating the list one by one to find <a> tag whose href attribute contains long string. And then we click on that particular <a> tag and comes out of the loop.

Does a TCP socket connection have a "keep alive"?

In JAVA Socket – TCP connections are managed on the OS level, java.net.Socket does not provide any in-built function to set timeouts for keepalive packet on a per-socket level. But we can enable keepalive option for java socket but it takes 2 hours 11 minutes (7200 sec) by default to process after a stale tcp connections. This cause connection will be availabe for very long time before purge. So we found some solution to use Java Native Interface (JNI) that call native code(c++) to configure these options.

****Windows OS****

In windows operating system keepalive_time & keepalive_intvl can be configurable but tcp_keepalive_probes cannot be change.By default, when a TCP socket is initialized sets the keep-alive timeout to 2 hours and the keep-alive interval to 1 second. The default system-wide value of the keep-alive timeout is controllable through the KeepAliveTime registry setting which takes a value in milliseconds.

On Windows Vista and later, the number of keep-alive probes (data retransmissions) is set to 10 and cannot be changed.

On Windows Server 2003, Windows XP, and Windows 2000, the default setting for number of keep-alive probes is 5. The number of keep-alive probes is controllable. For windows Winsock IOCTLs library is used to configure the tcp-keepalive parameters.

int WSAIoctl( SocketFD, // descriptor identifying a socket SIO_KEEPALIVE_VALS, // dwIoControlCode (LPVOID) lpvInBuffer, // pointer to tcp_keepalive struct (DWORD) cbInBuffer, // length of input buffer NULL, // output buffer 0, // size of output buffer (LPDWORD) lpcbBytesReturned, // number of bytes returned NULL, // OVERLAPPED structure NULL // completion routine );

Linux OS

Linux has built-in support for keepalive which is need to be enabling TCP/IP networking in order to use it. Programs must request keepalive control for their sockets using the setsockopt interface.

int setsockopt(int socket, int level, int optname, const void *optval, socklen_t optlen)

Each client socket will be created using java.net.Socket. File descriptor ID for each socket will retrieve using java reflection.

DynamoDB vs MongoDB NoSQL

I know this is old, but it still comes up when you search for the comparison. We were using Mongo, have moved almost entirely to Dynamo, which is our first choice now. Not because it has more features, it doesn't. Mongo has a better query language, you can index within a structure, there's lots of little things. The superiority of Dynamo is in what the OP stated in his comment: it's easy. You don't have to take care of any servers. When you start to set up a Mongo sharded solution, it gets complicated. You can go to one of the hosting companies, but that's not cheap either. With Dynamo, if you need more throughput, you just click a button. You can write scripts to scale automatically. When it's time to upgrade Dynamo, it's done for you. That is all a lot of precious stress and time not spent. If you don't have dedicated ops people, Dynamo is excellent.

So we are now going on Dynamo by default. Mongo maybe, if the data structure is complicated enough to warrant it, but then we'd probably go back to a SQL database. Dynamo is obtuse, you really need to think about how you're going to build it, and likely you'll use Redis in Elasticcache to make it work for complex stuff. But it sure is nice to not have to take care of it. You code. That's it.

How to print the ld(linker) search path

I'm not sure that there is any option for simply printing the full effective search path.

But: the search path consists of directories specified by -L options on the command line, followed by directories added to the search path by SEARCH_DIR("...") directives in the linker script(s). So you can work it out if you can see both of those, which you can do as follows:

If you're invoking ld directly:

  • The -L options are whatever you've said they are.
  • To see the linker script, add the --verbose option. Look for the SEARCH_DIR("...") directives, usually near the top of the output. (Note that these are not necessarily the same for every invocation of ld -- the linker has a number of different built-in default linker scripts, and chooses between them based on various other linker options.)

If you're linking via gcc:

  • You can pass the -v option to gcc so that it shows you how it invokes the linker. In fact, it normally does not invoke ld directly, but indirectly via a tool called collect2 (which lives in one of its internal directories), which in turn invokes ld. That will show you what -L options are being used.
  • You can add -Wl,--verbose to the gcc options to make it pass --verbose through to the linker, to see the linker script as described above.

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

Regex match text between tags

var root = document.createElement("div");

root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var texts = [].map.call( root.querySelectorAll("b"), function(v){
    return v.textContent || v.innerText || "";
});

//["Bob", "20", "programming"]

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

In my case, at some point I set my global config to use a cert that was meant for a project.

npm config list

/path/to/global/.npmrc
NODE_EXTRA_CA_CERTS = "./certs/chain.pem"

I opened the file, removed the line and npm install worked again.

How to convert any date format to yyyy-MM-dd

if (DateTime.TryParse(datetoparser, out dateValue))
{
   string formatedDate = dateValue.ToString("yyyy-MM-dd");
}

Calculate cosine similarity given 2 sentence strings

Try this. Download the file 'numberbatch-en-17.06.txt' from https://conceptnet.s3.amazonaws.com/downloads/2017/numberbatch/numberbatch-en-17.06.txt.gz and extract it. The function 'get_sentence_vector' uses a simple sum of word vectors. However it can be improved by using weighted sum where weights are proportional to Tf-Idf of each word.

import math
import numpy as np

std_embeddings_index = {}
with open('path/to/numberbatch-en-17.06.txt') as f:
    for line in f:
        values = line.split(' ')
        word = values[0]
        embedding = np.asarray(values[1:], dtype='float32')
        std_embeddings_index[word] = embedding

def cosineValue(v1,v2):
    "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)


def get_sentence_vector(sentence, std_embeddings_index = std_embeddings_index ):
    sent_vector = 0
    for word in sentence.lower().split():
        if word not in std_embeddings_index :
            word_vector = np.array(np.random.uniform(-1.0, 1.0, 300))
            std_embeddings_index[word] = word_vector
        else:
            word_vector = std_embeddings_index[word]
        sent_vector = sent_vector + word_vector

    return sent_vector

def cosine_sim(sent1, sent2):
    return cosineValue(get_sentence_vector(sent1), get_sentence_vector(sent2))

I did run for the given sentences and found the following results

s1 = "This is a foo bar sentence ."
s2 = "This sentence is similar to a foo bar sentence ."
s3 = "What is this string ? Totally not related to the other two lines ."

print cosine_sim(s1, s2) # Should give high cosine similarity
print cosine_sim(s1, s3) # Shouldn't give high cosine similarity value
print cosine_sim(s2, s3) # Shouldn't give high cosine similarity value

0.9851735249068168
0.6570885718962608
0.6589335425458225

Determine what attributes were changed in Rails after_save callback?

For those who want to know the changes just made in an after_save callback:

Rails 5.1 and greater

model.saved_changes

Rails < 5.1

model.previous_changes

Also see: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-previous_changes

Converting map to struct

  • the simplest way to do that is using encoding/json package

just for example:

package main
import (
    "fmt"
    "encoding/json"
)

type MyAddress struct {
    House string
    School string
}
type Student struct {
    Id int64
    Name string
    Scores float32
    Address MyAddress
    Labels []string
}

func Test() {

    dict := make(map[string]interface{})
    dict["id"] = 201902181425       // int
    dict["name"] = "jackytse"       // string
    dict["scores"] = 123.456        // float
    dict["address"] = map[string]string{"house":"my house", "school":"my school"}   // map
    dict["labels"] = []string{"aries", "warmhearted", "frank"}      // slice

    jsonbody, err := json.Marshal(dict)
    if err != nil {
        // do error check
        fmt.Println(err)
        return
    }

    student := Student{}
    if err := json.Unmarshal(jsonbody, &student); err != nil {
        // do error check
        fmt.Println(err)
        return
    }

    fmt.Printf("%#v\n", student)
}

func main() {
    Test()
}

How to show a GUI message box from a bash script in linux?

Example bash script for using Gambas GTK/QT Controls(GUI Objects): The Gambas IDE can be used to design even large GUIs and act as a GUI server. Example expplications can be downloaded from the Gambas App store.
https://gambas.one/gambasfarm/?id=823&action=search

enter image description here

Hex to ascii string conversion

you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...

char d = (char)intValue;

do this for every 2chars in the hex string

this works if the string chars are only 0-9A-F:

#include <stdio.h>
#include <string.h>

int hex_to_int(char c){
        int first = c / 16 - 3;
        int second = c % 16;
        int result = first*10 + second;
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

ADB error: cannot connect to daemon

I've finally solved a very similar issue!

In my case, the problem was that I had two different SDKs (one from Eclipse and the other from Android Studio), so I was trying to execute the ADB commands in the wrong one.

So it is important that you check the path you are using in your IDE and execute the commands on the same.

How to trigger an event after using event.preventDefault()

A more recent answer skillfully uses jQuery.one()

$('form').one('submit', function(e) {
    e.preventDefault();
    // do your things ...

    // and when you done:
    $(this).submit();
});

https://stackoverflow.com/a/41440902/510905

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Does Hibernate create tables in the database automatically

For me it wasn't working even with hibernate.hbm2ddl.auto set to update. It turned out that the generated creation SQL was invalid, because one of my column names (user) was an SQL keyword. This failed softly, and it wasn't obvious what was going on until I inspected the logs.

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

java.util.regex - importance of Pattern.compile()?

When you compile the Pattern Java does some computation to make finding matches in Strings faster. (Builds an in-memory representation of the regex)

If you are going to reuse the Pattern multiple times you would see a vast performance increase over creating a new Pattern every time.

In the case of only using the Pattern once, the compiling step just seems like an extra line of code, but, in fact, it can be very helpful in the general case.

Detect Browser Language in PHP

The existing answers are a little too verbose so I created this smaller, auto-matching version.

function prefered_language(array $available_languages, $http_accept_language) {

    $available_languages = array_flip($available_languages);

    $langs;
    preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER);
    foreach($matches as $match) {

        list($a, $b) = explode('-', $match[1]) + array('', '');
        $value = isset($match[2]) ? (float) $match[2] : 1.0;

        if(isset($available_languages[$match[1]])) {
            $langs[$match[1]] = $value;
            continue;
        }

        if(isset($available_languages[$a])) {
            $langs[$a] = $value - 0.1;
        }

    }
    arsort($langs);

    return $langs;
}

And the sample usage:

//$_SERVER["HTTP_ACCEPT_LANGUAGE"] = 'en-us,en;q=0.8,es-cl;q=0.5,zh-cn;q=0.3';

// Languages we support
$available_languages = array("en", "zh-cn", "es");

$langs = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]);

/* Result
Array
(
    [en] => 0.8
    [es] => 0.4
    [zh-cn] => 0.3
)*/

Full gist source here

How to turn off caching on Firefox?

I know I'm resurrecting an ancient question, but I was trying to solve this problem today and have an alternate solution. Toggling caching when I want to test was not really acceptable for me, and as others mentioned, hard refreshing (ctrl+shift+r) doesn't always work.

Instead, I opted to put the following in my vhost.conf file (can also be done in .htaccess) on my dev environment:

<FilesMatch "\.(js|css)$">
FileETag None
<IfModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</IfModule>
</FilesMatch>

On my dev environment, this ensures that js and css are always retrieved. Additionally it doesn't affect the rest of my browsing, and it also works for all browsers, so testing in chrome / ie etc is also easy.

Found the snippet here, some other handy apache tricks as well: http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html#prevent-caching-with-htaccess

To make sure that my clients always see the latest version on production, we increment the query string on the js include on each update, ie

jquery.somefile.js?v=0.5

This forces my clients' browsers to update their local cache when they see a new querystring, but then caches the new copy until the file is updated again

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

Could not locate Gemfile

Here is something you could try.

Add this to any config files you use to run your app.

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
Bundler.require(:default)

Rails and other Rack based apps use this scheme. It happens sometimes that you are trying to run things which are some directories deeper than your root where your Gemfile normally is located. Of course you solved this problem for now but occasionally we all get into trouble with this finding the Gemfile. I sometimes like when you can have all you gems in the .bundle directory also. It never hurts to keep this site address under your pillow. http://bundler.io/

Java - remove last known item from ArrayList

clients.get will return a ClientThread and not a String, and it will bomb with an IndexOutOfBoundsException if it would compile as Java is zero based for indexing.

Similarly I think you should call remove on the clients list.

ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());

I would use the stack functions of a LinkedList in this case though.

ClientThread hey = clients.removeLast()

Set select option 'selected', by value

There's no reason to overthink this, all you are doing is accessing and setting a property. That's it.

Okay, so some basic dom: If you were doing this in straight JavaScript, it you would this:

window.document.getElementById('my_stuff').selectedIndex = 4;

But you're not doing it with straight JavaScript, you're doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:

$("#my_stuff").prop('selectedIndex', 4);

Anyway, just make sure your id is unique. Otherwise, you'll be banging your head on the wall wondering why this didn't work.

How can I verify if an AD account is locked?

If you want to check via command line , then use command "net user username /DOMAIN"

enter image description here

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I was able to get mine working using the following Client Credentials:

Authorized JavaScript origins

http://localhost

Authorized redirect URIs

http://localhost:8090/oauth2callback

Note: I used port 8090 instead of 8080, but that doesn't matter as long as your python script uses the same port as your client_secret.json file.

Reference: Python Quickstart

What exactly is node.js used for?

Directly from the tag wiki, make sure watch some of the talk videos linked there to get a better idea.


Node.js is an event based, asynchronous I/O framework that uses Google's V8 JavaScript Engine.

Node.js - or just Node as it's commonly called - is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.

It's also possible to use matured JavaScript frameworks like YUI and jQuery for server side DOM manipulation.

To ease the development of complex JavaScript further, Node.js supports the CommonJS standard that allows for modularized development and the distribution of software in packages via the Node Package Manager.

Applications that can be written using Node.js include, but are not limited to:

  • Static file servers
  • Web Application frameworks
  • Messaging middle ware
  • Servers for HTML5 multi player games

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

Another solution:

public class CountryInfoResponse {
  private List<Object> geonames;
}

Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.

Freemarker iterating over hashmap keys

FYI, it looks like the syntax for retrieving the values has changed according to:

http://freemarker.sourceforge.net/docs/ref_builtins_hash.html

<#assign h = {"name":"mouse", "price":50}>
<#assign keys = h?keys>
<#list keys as key>${key} = ${h[key]}; </#list>

How do you use the ? : (conditional) operator in JavaScript?

If you have one condition check instance function in javascript. it's easy to use ternary operator. which will only need one single line to implement. Ex:

    private module : string ='';
    private page:boolean = false;
    async mounted(){
     if(this.module=== 'Main')
    {
    this.page = true;}
    else{
    this.page = false;
    }
}

a function like this with one condition can be written as follow.

this.page = this.module=== 'Main' ?true:false;

condition ? if True : if False

Add animated Gif image in Iphone UIImageView

SWIFT 3

Here is the update for those who need the Swift version!.

A few days ago i needed to do something like this. I load some data from a server according specific parameters and in the meanwhile i wanted to show a different gif image of "loading". I was looking for an option to do it with an UIImageView but unfortunately i didn't find something to do it without splitting the .gif images. So i decided to implement a solution using a UIWebView and i want to shared it:

extension UIView{
    func animateWithGIF(name: String){
        let htmlString: String =    "<!DOCTYPE html><html><head><title></title></head>" +
                                        "<body style=\"background-color: transparent;\">" +
                                            "<img src=\""+name+"\" align=\"middle\" style=\"width:100%;height:100%;\">" +
                                        "</body>" +
                                    "</html>"

        let path: NSString = Bundle.main.bundlePath as NSString
        let baseURL: URL = URL(fileURLWithPath: path as String) // to load images just specifying its name without full path

        let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        let gifView = UIWebView(frame: frame)

        gifView.isOpaque = false // The drawing system composites the view normally with other content.
        gifView.backgroundColor = UIColor.clear
        gifView.loadHTMLString(htmlString, baseURL: baseURL)

        var s: [UIView] = self.subviews 
        for i in 0 ..< s.count {
            if s[i].isKind(of: UIWebView.self) { s[i].removeFromSuperview() }
        }

        self.addSubview(gifView)
    }

    func animateWithGIF(url: String){
        self.animateWithGIF(name: url)
    }
} 

I made an extension for UIView which adds a UIWebView as subview and displays the .gif images just passing its name.

Now in my UIViewController i have a UIView named 'loadingView' which is my 'loading' indicator and whenever i wanted to show the .gif image, i did something like this:

class ViewController: UIViewController {
    @IBOutlet var loadingView: UIView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        configureLoadingView(name: "loading.gif")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // .... some code
        // show "loading" image
        showLoadingView()
    }

    func showLoadingView(){
        loadingView.isHidden = false
    }
    func hideLoadingView(){
        loadingView.isHidden = true
    }
    func configureLoadingView(name: String){
        loadingView.animateWithGIF(name: "name")// change the image
    }
}

when I wanted to change the gif image, simply called the function configureLoadingView() with the name of my new .gif image and calling showLoadingView(), hideLoadingView() properly everything works fine!.

BUT...

... if you have the image splitted then you can animate it in a single line with a UIImage static method called UIImage.animatedImageNamed like this:

imageView.image = UIImage.animatedImageNamed("imageName", duration: 1.0)

From the docs:

This method loads a series of files by appending a series of numbers to the base file name provided in the name parameter. All images included in the animated image should share the same size and scale.

Or you can make it with the UIImage.animatedImageWithImages method like this:

let images: [UIImage] = [UIImage(named: "imageName1")!,
                                            UIImage(named: "imageName2")!,
                                            ...,
                                            UIImage(named: "imageNameN")!]
imageView.image = UIImage.animatedImage(with: images, duration: 1.0)

From the docs:

Creates and returns an animated image from an existing set of images. All images included in the animated image should share the same size and scale.

Add list to set?

I found I needed to do something similar today. The algorithm knew when it was creating a new list that needed to added to the set, but not when it would have finished operating on the list.

Anyway, the behaviour I wanted was for set to use id rather than hash. As such I found mydict[id(mylist)] = mylist instead of myset.add(mylist) to offer the behaviour I wanted.

How to manually force a commit in a @Transactional method?

I had a similar use case during testing hibernate event listeners which are only called on commit.

The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.

Tx prop REQUIRES_NEW

Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.

CASCADE DELETE just once

If I understand correctly, you should be able to do what you want by dropping the foreign key constraint, adding a new one (which will cascade), doing your stuff, and recreating the restricting foreign key constraint.

For example:

testing=# create table a (id integer primary key);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "a_pkey" for table "a"
CREATE TABLE
testing=# create table b (id integer references a);
CREATE TABLE

-- put some data in the table
testing=# insert into a values(1);
INSERT 0 1
testing=# insert into a values(2);
INSERT 0 1
testing=# insert into b values(2);
INSERT 0 1
testing=# insert into b values(1);
INSERT 0 1

-- restricting works
testing=# delete from a where id=1;
ERROR:  update or delete on table "a" violates foreign key constraint "b_id_fkey" on table "b"
DETAIL:  Key (id)=(1) is still referenced from table "b".

-- find the name of the constraint
testing=# \d b;
       Table "public.b"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 
Foreign-key constraints:
    "b_id_fkey" FOREIGN KEY (id) REFERENCES a(id)

-- drop the constraint
testing=# alter table b drop constraint b_a_id_fkey;
ALTER TABLE

-- create a cascading one
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete cascade; 
ALTER TABLE

testing=# delete from a where id=1;
DELETE 1
testing=# select * from a;
 id 
----
  2
(1 row)

testing=# select * from b;
 id 
----
  2
(1 row)

-- it works, do your stuff.
-- [stuff]

-- recreate the previous state
testing=# \d b;
       Table "public.b"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 
Foreign-key constraints:
    "b_id_fkey" FOREIGN KEY (id) REFERENCES a(id) ON DELETE CASCADE

testing=# alter table b drop constraint b_id_fkey;
ALTER TABLE
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete restrict; 
ALTER TABLE

Of course, you should abstract stuff like that into a procedure, for the sake of your mental health.

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();

String replacement in java, similar to a velocity template

There are a couple of Expression Language implementations out there that does this for you, could be preferable to using your own implementation as or if your requirments grow, see for example JUEL and MVEL

I like and have successfully used MVEL in at least one project.

Also see the Stackflow post JSTL/JSP EL (Expression Language) in a non JSP (standalone) context

Can Windows' built-in ZIP compression be scripted?

Just for clarity: GZip is not an MS-only algorithm as suggested by Guy Starbuck in his comment from August. The GZipStream in System.IO.Compression uses the Deflate algorithm, just the same as the zlib library, and many other zip tools. That class is fully interoperable with unix utilities like gzip.

The GZipStream class is not scriptable from the commandline or VBScript, to produce ZIP files, so it alone would not be an answer the original poster's request.

The free DotNetZip library does read and produce zip files, and can be scripted from VBScript or Powershell. It also includes command-line tools to produce and read/extract zip files.

Here's some code for VBScript:

dim filename 
filename = "C:\temp\ZipFile-created-from-VBScript.zip"

WScript.echo("Instantiating a ZipFile object...")
dim zip 
set zip = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("using AES256 encryption...")
zip.Encryption = 3

WScript.echo("setting the password...")
zip.Password = "Very.Secret.Password!"

WScript.echo("adding a selection of files...")
zip.AddSelectedFiles("*.js")
zip.AddSelectedFiles("*.vbs")

WScript.echo("setting the save name...")
zip.Name = filename

WScript.echo("Saving...")
zip.Save()

WScript.echo("Disposing...")
zip.Dispose()

WScript.echo("Done.")

Here's some code for Powershell:

[System.Reflection.Assembly]::LoadFrom("c:\\dinoch\\bin\\Ionic.Zip.dll");

$directoryToZip = "c:\\temp";
$zipfile =  new-object Ionic.Zip.ZipFile;
$e= $zipfile.AddEntry("Readme.txt", "This is a zipfile created from within powershell.")
$e= $zipfile.AddDirectory($directoryToZip, "home")
$zipfile.Save("ZipFiles.ps1.out.zip");

In a .bat or .cmd file, you can use the zipit.exe or unzip.exe tools. Eg:

zipit NewZip.zip  -s "This is string content for an entry"  Readme.txt  src 

"Android library projects cannot be launched"?

Through the following steps you can do it .

In Eclipse window , Right Click on your Project from Package Explorer. 1. Select Properties, 2. Select Android from Properties, 3. Check "Is Library" check box, 4. If it is checked then Unchecked "Is Library" check box. 5. Click Apply and than OK.

How to convert number to words in java

In this post i have just update Yanick Rochon's code. I have make it workable with lower version of java 1.6 and i was getting the output for 1.00 = one and  hundredth. So i have update the code. New i get the output for 1.00 = one and zero hundredth.

I don't not what should i do. Add a new answer or edit that post. As the answer is highly ranked so i have made a new post with updating the code. I have just change this two things have mention above.

/**
 * This class will convert numeric values into an english representation
 * 
 * For units, see : http://www.jimloy.com/math/billion.htm
 * 
 * @author [email protected]
 */
public class NumberToWords {

    static public class ScaleUnit {
        private int exponent;
        private String[] names;

        private ScaleUnit(int exponent, String... names) {
            this.exponent = exponent;
            this.names = names;
        }

        public int getExponent() {
            return exponent;
        }

        public String getName(int index) {
            return names[index];
        }
    }

    /**
     * See http://www.wordiq.com/definition/Names_of_large_numbers
     */
    static private ScaleUnit[] SCALE_UNITS = new ScaleUnit[] {
            new ScaleUnit(63, "vigintillion", "decilliard"),
            new ScaleUnit(60, "novemdecillion", "decillion"),
            new ScaleUnit(57, "octodecillion", "nonilliard"),
            new ScaleUnit(54, "septendecillion", "nonillion"),
            new ScaleUnit(51, "sexdecillion", "octilliard"),
            new ScaleUnit(48, "quindecillion", "octillion"),
            new ScaleUnit(45, "quattuordecillion", "septilliard"),
            new ScaleUnit(42, "tredecillion", "septillion"),
            new ScaleUnit(39, "duodecillion", "sextilliard"),
            new ScaleUnit(36, "undecillion", "sextillion"),
            new ScaleUnit(33, "decillion", "quintilliard"),
            new ScaleUnit(30, "nonillion", "quintillion"),
            new ScaleUnit(27, "octillion", "quadrilliard"),
            new ScaleUnit(24, "septillion", "quadrillion"),
            new ScaleUnit(21, "sextillion", "trilliard"),
            new ScaleUnit(18, "quintillion", "trillion"),
            new ScaleUnit(15, "quadrillion", "billiard"),
            new ScaleUnit(12, "trillion", "billion"),
            new ScaleUnit(9, "billion", "milliard"),
            new ScaleUnit(6, "million", "million"),
            new ScaleUnit(3, "thousand", "thousand"),
            new ScaleUnit(2, "hundred", "hundred"),
            // new ScaleUnit(1, "ten", "ten"),
            // new ScaleUnit(0, "one", "one"),
            new ScaleUnit(-1, "tenth", "tenth"), new ScaleUnit(-2, "hundredth", "hundredth"),
            new ScaleUnit(-3, "thousandth", "thousandth"),
            new ScaleUnit(-4, "ten-thousandth", "ten-thousandth"),
            new ScaleUnit(-5, "hundred-thousandth", "hundred-thousandth"),
            new ScaleUnit(-6, "millionth", "millionth"),
            new ScaleUnit(-7, "ten-millionth", "ten-millionth"),
            new ScaleUnit(-8, "hundred-millionth", "hundred-millionth"),
            new ScaleUnit(-9, "billionth", "milliardth"),
            new ScaleUnit(-10, "ten-billionth", "ten-milliardth"),
            new ScaleUnit(-11, "hundred-billionth", "hundred-milliardth"),
            new ScaleUnit(-12, "trillionth", "billionth"),
            new ScaleUnit(-13, "ten-trillionth", "ten-billionth"),
            new ScaleUnit(-14, "hundred-trillionth", "hundred-billionth"),
            new ScaleUnit(-15, "quadrillionth", "billiardth"),
            new ScaleUnit(-16, "ten-quadrillionth", "ten-billiardth"),
            new ScaleUnit(-17, "hundred-quadrillionth", "hundred-billiardth"),
            new ScaleUnit(-18, "quintillionth", "trillionth"),
            new ScaleUnit(-19, "ten-quintillionth", "ten-trillionth"),
            new ScaleUnit(-20, "hundred-quintillionth", "hundred-trillionth"),
            new ScaleUnit(-21, "sextillionth", "trilliardth"),
            new ScaleUnit(-22, "ten-sextillionth", "ten-trilliardth"),
            new ScaleUnit(-23, "hundred-sextillionth", "hundred-trilliardth"),
            new ScaleUnit(-24, "septillionth", "quadrillionth"),
            new ScaleUnit(-25, "ten-septillionth", "ten-quadrillionth"),
            new ScaleUnit(-26, "hundred-septillionth", "hundred-quadrillionth"), };

    static public enum Scale {
        SHORT, LONG;

        public String getName(int exponent) {
            for (ScaleUnit unit : SCALE_UNITS) {
                if (unit.getExponent() == exponent) {
                    return unit.getName(this.ordinal());
                }
            }
            return "";
        }
    }

    /**
     * Change this scale to support American and modern British value (short scale) or Traditional
     * British value (long scale)
     */
    static public Scale SCALE = Scale.SHORT;

    static abstract public class AbstractProcessor {

        static protected final String SEPARATOR = " ";
        static protected final int NO_VALUE = -1;

        protected List<Integer> getDigits(long value) {
            ArrayList<Integer> digits = new ArrayList<Integer>();
            if (value == 0) {
                digits.add(0);
            } else {
                while (value > 0) {
                    digits.add(0, (int) value % 10);
                    value /= 10;
                }
            }
            return digits;
        }

        public String getName(long value) {
            return getName(Long.toString(value));
        }

        public String getName(double value) {
            return getName(Double.toString(value));
        }

        abstract public String getName(String value);
    }

    static public class UnitProcessor extends AbstractProcessor {

        static private final String[] TOKENS = new String[] { "one", "two", "three", "four",
                "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();

            int offset = NO_VALUE;
            int number;
            if (value.length() > 3) {
                number = Integer.valueOf(value.substring(value.length() - 3), 10);
            } else {
                number = Integer.valueOf(value, 10);
            }
            number %= 100;
            if (number < 10) {
                offset = (number % 10) - 1;
                // number /= 10;
            } else if (number < 20) {
                offset = (number % 20) - 1;
                // number /= 100;
            }

            if (offset != NO_VALUE && offset < TOKENS.length) {
                buffer.append(TOKENS[offset]);
            }

            return buffer.toString();
        }

    }

    static public class TensProcessor extends AbstractProcessor {

        static private final String[] TOKENS = new String[] { "twenty", "thirty", "fourty",
                "fifty", "sixty", "seventy", "eighty", "ninety" };

        static private final String UNION_SEPARATOR = "-";

        private UnitProcessor unitProcessor = new UnitProcessor();

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();
            boolean tensFound = false;

            int number;
            if (value.length() > 3) {
                number = Integer.valueOf(value.substring(value.length() - 3), 10);
            } else {
                number = Integer.valueOf(value, 10);
            }
            number %= 100; // keep only two digits
            if (number >= 20) {
                buffer.append(TOKENS[(number / 10) - 2]);
                number %= 10;
                tensFound = true;
            } else {
                number %= 20;
            }

            if (number != 0) {
                if (tensFound) {
                    buffer.append(UNION_SEPARATOR);
                }
                buffer.append(unitProcessor.getName(number));
            }

            return buffer.toString();
        }
    }

    static public class HundredProcessor extends AbstractProcessor {

        private int EXPONENT = 2;

        private UnitProcessor unitProcessor = new UnitProcessor();
        private TensProcessor tensProcessor = new TensProcessor();

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();

            int number;
            if ("".equals(value)) {
                number = 0;
            } else if (value.length() > 4) {
                number = Integer.valueOf(value.substring(value.length() - 4), 10);
            } else {
                number = Integer.valueOf(value, 10);
            }
            number %= 1000; // keep at least three digits

            if (number >= 100) {
                buffer.append(unitProcessor.getName(number / 100));
                buffer.append(SEPARATOR);
                buffer.append(SCALE.getName(EXPONENT));
            }

            String tensName = tensProcessor.getName(number % 100);

            if (!"".equals(tensName) && (number >= 100)) {
                buffer.append(SEPARATOR);
            }
            buffer.append(tensName);

            return buffer.toString();
        }
    }

    static public class CompositeBigProcessor extends AbstractProcessor {

        private HundredProcessor hundredProcessor = new HundredProcessor();
        private AbstractProcessor lowProcessor;
        private int exponent;

        public CompositeBigProcessor(int exponent) {
            if (exponent <= 3) {
                lowProcessor = hundredProcessor;
            } else {
                lowProcessor = new CompositeBigProcessor(exponent - 3);
            }
            this.exponent = exponent;
        }

        public String getToken() {
            return SCALE.getName(getPartDivider());
        }

        protected AbstractProcessor getHighProcessor() {
            return hundredProcessor;
        }

        protected AbstractProcessor getLowProcessor() {
            return lowProcessor;
        }

        public int getPartDivider() {
            return exponent;
        }

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();

            String high, low;
            if (value.length() < getPartDivider()) {
                high = "";
                low = value;
            } else {
                int index = value.length() - getPartDivider();
                high = value.substring(0, index);
                low = value.substring(index);
            }

            String highName = getHighProcessor().getName(high);
            String lowName = getLowProcessor().getName(low);

            if (!"".equals(highName)) {
                buffer.append(highName);
                buffer.append(SEPARATOR);
                buffer.append(getToken());

                if (!"".equals(lowName)) {
                    buffer.append(SEPARATOR);
                }
            }

            if (!"".equals(lowName)) {
                buffer.append(lowName);
            }

            return buffer.toString();
        }
    }

    static public class DefaultProcessor extends AbstractProcessor {

        static private String MINUS = "minus";
        static private String UNION_AND = "and";

        static private String ZERO_TOKEN = "zero";

        private AbstractProcessor processor = new CompositeBigProcessor(63);

        @Override
        public String getName(String value) {
            boolean negative = false;
            if (value.startsWith("-")) {
                negative = true;
                value = value.substring(1);
            }

            int decimals = value.indexOf(".");
            String decimalValue = null;
            if (0 <= decimals) {
                decimalValue = value.substring(decimals + 1);
                value = value.substring(0, decimals);
            }

            String name = processor.getName(value);

            if ("".equals(name)) {
                name = ZERO_TOKEN;
            } else if (negative) {
                name = MINUS.concat(SEPARATOR).concat(name);
            }

            if (!(null == decimalValue || "".equals(decimalValue))) {

                String zeroDecimalValue = "";
                for (int i = 0; i < decimalValue.length(); i++) {
                    zeroDecimalValue = zeroDecimalValue + "0";
                }
                if (decimalValue.equals(zeroDecimalValue)) {
                    name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR).concat(
                            "zero").concat(SEPARATOR).concat(
                            SCALE.getName(-decimalValue.length()));
                } else {
                    name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR).concat(
                            processor.getName(decimalValue)).concat(SEPARATOR).concat(
                            SCALE.getName(-decimalValue.length()));
                }

            }

            return name;
        }

    }

    static public AbstractProcessor processor;

    public static void main(String... args) {

        processor = new DefaultProcessor();

        long[] values = new long[] { 0, 4, 10, 12, 100, 108, 299, 1000, 1003, 2040, 45213, 100000,
                100005, 100010, 202020, 202022, 999999, 1000000, 1000001, 10000000, 10000007,
                99999999, Long.MAX_VALUE, Long.MIN_VALUE };

        String[] strValues = new String[] { "0", "1.30", "0001.00", "3.141592" };

        for (long val : values) {
            System.out.println(val + " = " + processor.getName(val));
        }

        for (String strVal : strValues) {
            System.out.println(strVal + " = " + processor.getName(strVal));
        }

        // generate a very big number...
        StringBuilder bigNumber = new StringBuilder();
        for (int d = 0; d < 66; d++) {
            bigNumber.append((char) ((Math.random() * 10) + '0'));
        }
        bigNumber.append(".");
        for (int d = 0; d < 26; d++) {
            bigNumber.append((char) ((Math.random() * 10) + '0'));
        }
        System.out.println(bigNumber.toString() + " = " + processor.getName(bigNumber.toString()));
    }
}

The output is

0 = zero
4 = four
10 = ten
12 = twelve
100 = one hundred
108 = one hundred eight
299 = two hundred ninety-nine
1000 = one thousand
1003 = one thousand three
2040 = two thousand fourty
45213 = fourty-five thousand two hundred thirteen
100000 = one hundred thousand
100005 = one hundred thousand five
100010 = one hundred thousand ten
202020 = two hundred two thousand twenty
202022 = two hundred two thousand twenty-two
999999 = nine hundred ninety-nine thousand nine hundred ninety-nine
1000000 = one million
1000001 = one million one
10000000 = ten million
10000007 = ten million seven
99999999 = ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine
9223372036854775807 = nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred seven
-9223372036854775808 = minus nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred eight
0.0 = zero and zero tenth
1.30 = one and thirty hundredth
0001.00 = one and zero hundredth
3.141592 = three and one hundred fourty-one thousand five hundred ninety-two millionth
354064188376576616844741830273568537829518115677552666352927559274.76892492652888527014418647 = three hundred fifty-four vigintillion sixty-four novemdecillion one hundred eighty-eight octodecillion three hundred seventy-six septendecillion five hundred seventy-six sexdecillion six hundred sixteen quindecillion eight hundred fourty-four quattuordecillion seven hundred fourty-one tredecillion eight hundred thirty duodecillion two hundred seventy-three undecillion five hundred sixty-eight decillion five hundred thirty-seven nonillion eight hundred twenty-nine octillion five hundred eighteen septillion one hundred fifteen sextillion six hundred seventy-seven quintillion five hundred fifty-two quadrillion six hundred sixty-six trillion three hundred fifty-two billion nine hundred twenty-seven million five hundred fifty-nine thousand two hundred seventy-four and seventy-six septillion eight hundred ninety-two sextillion four hundred ninety-two quintillion six hundred fifty-two quadrillion eight hundred eighty-eight trillion five hundred twenty-seven billion fourteen million four hundred eighteen thousand six hundred fourty-seven hundred-septillionth

Set min-width in HTML table's <td>

try this one:

_x000D_
_x000D_
<table style="border:1px solid">
<tr>
    <td style="min-width:50px">one</td>
    <td style="min-width:100px">two</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

How to build a Horizontal ListView with RecyclerView?

Recycler View in Horizontal Dynamic.

Recycler View Implementation

RecyclerView musicList = findViewById(R.id.MusicList);

// RecyclerView musiclist = findViewById(R.id.MusicList1);
// RecyclerView musicLIST = findViewById(R.id.MusicList2);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
musicList.setLayoutManager(layoutManager);

String[] names = {"RAP", "CH SHB", "Faheem", "Anum", "Shoaib", "Laiba", "Zoki", "Komal", "Sultan","Mansoob Gull"};
musicList.setAdapter(new ProgrammingAdapter(names));'

Adapter class for recycler view, in which there is is a view holder for holding view of that recycler

public class ProgrammingAdapter 
     extendsRecyclerView.Adapter<ProgrammingAdapter.programmingViewHolder> {

private String[] data;

public ProgrammingAdapter(String[] data)
{
    this.data = data;
}

@Override
public programmingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.list_item_layout, parent, false);

    return new programmingViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull programmingViewHolder holder, int position) {
    String title = data[position];
    holder.textV.setText(title);
}

@Override
public int getItemCount() {
    return data.length;
}

public class programmingViewHolder extends RecyclerView.ViewHolder{
    ImageView img;
    TextView textV;
    public programmingViewHolder(View itemView) {
        super(itemView);
        img =  itemView.findViewById(R.id.img);
        textV =  itemView.findViewById(R.id.textt);
    }
}

Vertically align text to top within a UILabel

enter image description here

In Interface Builder

  • Set UILabel to size of biggest possible Text
  • Set Lines to '0' in Attributes Inspector

In your code

  • Set the text of the label
  • Call sizeToFit on your label

Code Snippet:

self.myLabel.text = @"Short Title";
[self.myLabel sizeToFit];

Remove header and footer from window.print()

1.For Chrome & IE

<script language="javascript">
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.getElementById('header').style.display = 'none';
document.getElementById('footer').style.display = 'none';
document.body.innerHTML = printContents;

window.print();


document.body.innerHTML = originalContents;
}

</script>
<div id="div_print">
<div id="header" style="background-color:White;"></div>
<div id="footer" style="background-color:White;"></div>
</div>
  1. For FireFox as l2aelba said,

Add moznomarginboxes attribute in Example :

<html moznomarginboxes mozdisallowselectionprint>

Bootstrap 3 and Youtube in Modal

Found this in another thread, and it works great on desktop and mobile - which is something that didn't seem true with some of the other solutions. Add this script to the end of your page:

<!--Script stops video from playing when modal is closed-->
<script>
    $("#myModal").on('hidden.bs.modal', function (e) {
        $("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
    });
</script>   

How to find MAC address of an Android device programmatically

private fun getMac(): String? =
        try {
            NetworkInterface.getNetworkInterfaces()
                    .toList()
                    .find { networkInterface -> networkInterface.name.equals("wlan0", ignoreCase = true) }
                    ?.hardwareAddress
                    ?.joinToString(separator = ":") { byte -> "%02X".format(byte) }
        } catch (ex: Exception) {
            ex.printStackTrace()
            null
        }

java.util.NoSuchElementException - Scanner reading user input

the reason of the exception has been explained already, however the suggested solution isn't really the best.

You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.

Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.

If you are not aware how to use Singleton Pattern, here's a example:

public class Reader {
    
    
    private Scanner reader;
    private static Reader singleton = null;
    private boolean alreadyClosed;
    
    private Reader() {
        alreadyClosed = false;
        reader = new Scanner(System.in);
    }
    
    public static Reader getInstance() {
        if(singleton == null) {
            singleton = new Reader();
        }
        return singleton;
    }
    
    public int nextInt() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextInt();
        }
        throw new AlreadyClosedException(); //Custom exception
    }
    
    public double nextDouble() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextDouble();
        }
        throw new AlreadyClosedException();
    }
    
    public String nextLine() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextLine();
        }
        throw new AlreadyClosedException();
    }
    
    public void close() {
        alreadyClosed = true;
        reader.close();
    }   
}

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

How to simulate browsing from various locations?

It depends on wether the locatoin is detected by different DNS resolution from different locations, or by IP address that you are browsing from.

If its by DNS, you could just modify your hosts file to point at the server used in europe. Get your friend to ping the address, to see if its different from the one yours resolves to.

To browse from a different IP address:

You can rent a VPS server. You can use putty / SSH to act as a proxy. I use this from time to time to brows from the US using a VPS server I rent in the US.

Having an account on a remote host may or may not be enough. Sadly, my dreamhost account, even though I have ssh access, does not allow proxying.

Java - Convert int to Byte Array of 4 Bytes?

int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
    bytes[i] = (byte)(integer >>> (i * 8));
}

Android Webview gives net::ERR_CACHE_MISS message

I ran to a similar problem and that was just because of the extra spaces:

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

which when removed works fine:

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

How to display JavaScript variables in a HTML page without document.write

If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.

?var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);??????

Cannot find or open the PDB file in Visual Studio C++ 2010

you just add the path of .pdb to work directory of VS!

How can I get table names from an MS Access Database?

To build on Ilya's answer try the following query:

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name 

(this one works without modification with an MDB)

ACCDB users may need to do something like this

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6))
        AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name 

As there is an extra table is included that appears to be a system table of some sort.

Count the frequency that a value occurs in a dataframe column

Without any libraries, you could do this instead:

def to_frequency_table(data):
    frequencytable = {}
    for key in data:
        if key in frequencytable:
            frequencytable[key] += 1
        else:
            frequencytable[key] = 1
    return frequencytable

Example:

to_frequency_table([1,1,1,1,2,3,4,4])
>>> {1: 4, 2: 1, 3: 1, 4: 2}

What is the difference between a data flow diagram and a flow chart?

Flow chart describes the program (see old fortran flow charts - surely, there are some floating around on google).

Data flow diagram determines the flow of data, for example, between subroutines, or between different programs.

E: Unable to locate package npm

Encountered this in Ubuntu for Windows, try running first

sudo apt-get update
sudo apt-get upgrade

then

sudo apt-get install npm

Boxplot show the value of mean

The Magrittr way

I know there is an accepted answer already, but I wanted to show one cool way to do it in single command with the help of magrittr package.

PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18)  %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text

This code will produce a boxplot with means printed as points and values: boxplot with means

I split the command on multiple lines so I can comment on what each part does, but it can also be entered as a oneliner. You can learn more about this in my gist.

How do I check to see if a value is an integer in MySQL?

This also works:

CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.

for example

SELECT CAST('a123' AS UNSIGNED) // returns 0
SELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0

Any way to make plot points in scatterplot more transparent in R?

When creating the colors, you may use rgb and set its alpha argument:

plot(1:10, col = rgb(red = 1, green = 0, blue = 0, alpha = 0.5),
     pch = 16, cex = 4)
points((1:10) + 0.4, col = rgb(red = 0, green = 0, blue = 1, alpha = 0.5),
       pch = 16, cex = 4)

enter image description here

Please see ?rgb for details.

How do I attach events to dynamic HTML elements with jQuery?

After jQuery 1.7 the preferred methods are .on() and .off()

Sean's answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

Default values in a C Struct

<stdarg.h> allows you to define variadic functions (which accept an indefinite number of arguments, like printf()). I would define a function which took an arbitrary number of pairs of arguments, one which specifies the property to be updated, and one which specifies the value. Use an enum or a string to specify the name of the property.

How to generate a random number in C++?

Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it's perfectly possible to get repeating numbers in a random sequence.

Try some C++11 features for better distribution:

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

See this question/answer for more info on C++11 random numbers. The above isn't the only way to do this, but is one way.

Is it better to use path() or url() in urls.py for django 2.0?

From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows

from django.contrib import admin
from django.urls import path

from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^posts/$', post_home, name='post_home'),

]

where posts is an application & post_home is a function in views.py

Exploring Docker container's file system

Here are a couple different methods...

A) Use docker exec (easiest)

Docker version 1.3 or newer supports the command exec that behave similar to nsenter. This command can run new process in already running container (container must have PID 1 process running already). You can run /bin/bash to explore container state:

docker exec -t -i mycontainer /bin/bash

see Docker command line documentation

B) Use Snapshotting

You can evaluate container filesystem this way:

# find ID of your running container:
docker ps

# create image (snapshot) from container filesystem
docker commit 12345678904b5 mysnapshot

# explore this filesystem using bash (for example)
docker run -t -i mysnapshot /bin/bash

This way, you can evaluate filesystem of the running container in the precise time moment. Container is still running, no future changes are included.

You can later delete snapshot using (filesystem of the running container is not affected!):

docker rmi mysnapshot

C) Use ssh

If you need continuous access, you can install sshd to your container and run the sshd daemon:

 docker run -d -p 22 mysnapshot /usr/sbin/sshd -D
 
 # you need to find out which port to connect:
 docker ps

This way, you can run your app using ssh (connect and execute what you want).

D) Use nsenter

Use nsenter, see Why you don't need to run SSHd in your Docker containers

The short version is: with nsenter, you can get a shell into an existing container, even if that container doesn’t run SSH or any kind of special-purpose daemon

How to display (print) vector in Matlab?

You might try this way:

fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)

I hope this helps.

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

to

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

React - How to force a function component to render?

The accepted answer is good. Just to make it easier to understand.

Example component:

export default function MyComponent(props) {

    const [updateView, setUpdateView] = useState(0);

    return (
        <>
            <span style={{ display: "none" }}>{updateView}</span>
        </>
    );
}

To force re-rendering call the code below:

setUpdateView((updateView) => ++updateView);

Python: How to create a unique file name?

I didn't think your question was very clear, but if all you need is a unique file name...

import uuid

unique_filename = str(uuid.uuid4())

Which port(s) does XMPP use?

According to Wikipedia:

5222 TCP     XMPP client connection (RFC 6120)        Official  
5223 TCP     XMPP client connection over SSL          Unofficial
5269 TCP     XMPP server connection (RFC 6120)        Official
5298 TCP UDP XMPP JEP-0174: Link-Local Messaging /    Official
             XEP-0174: Serverless Messaging
8010 TCP     XMPP File transfers                      Unofficial    

The port numbers are defined in RFC 6120 § 14.7.

SQL Greater than, Equal to AND Less Than

Somthing like this should workL

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()

Update all objects in a collection using LINQ

I assume you want to change values inside a query so you could write a function for it

void DoStuff()
{
    Func<string, Foo, bool> test = (y, x) => { x.Bar = y; return true; };
    List<Foo> mylist = new List<Foo>();
    var v = from x in mylist
            where test("value", x)
            select x;
}

class Foo
{
    string Bar { get; set; }
}

But not shure if this is what you mean.

Git diff against a stash

FWIW This may be a bit redundant to all the other answers and is very similar to the accepted answer which is spot on; but maybe it will help someone out.

git stash show --help will give you all you should need; including stash show info.

show [<stash>]

Show the changes recorded in the stash as a diff between the stashed state and its original parent. When no is given, shows the latest one. By default, the command shows the diffstat, but it will accept any format known to git diff (e.g., git stash show -p stash@{1} to view the second most recent stash in patch form). You can use stash.showStat and/or stash.showPatch config variables to change the default behavior.

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

JavaScript ternary operator example with functions

I would also like to add something from me.

Other possible syntax to call functions with the ternary operator, would be:

(condition ? fn1 : fn2)();

It can be handy if you have to pass the same list of parameters to both functions, so you have to write them only once.

(condition ? fn1 : fn2)(arg1, arg2, arg3, arg4, arg5);

You can use the ternary operator even with member function names, which I personally like very much to save space:

$('.some-element')[showThisElement ? 'addClass' : 'removeClass']('visible');

or

$('.some-element')[(showThisElement ? 'add' : 'remove') + 'Class']('visible');

Another example:

var addToEnd = true; //or false
var list = [1,2,3,4];
list[addToEnd ? 'push' : 'unshift'](5);