Programs & Examples On #Code signing

Code signing is the process of digitally signing executables and scripts to confirm the software author and guarantee that the code has not been altered or corrupted since it was signed by use of a cryptographic hash.

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

To run your app on a real device, you need to have an Apple ID, and have registered your device with that ID. That is why you are getting this error.

Here's how you do it.

  1. Go to the project Navigator. Cmd-1 if you can't find it.

  2. Click the project target dropdown and pick Target. enter image description here

  3. Click on the Team dropdown and pick add an account. enter image description here

  4. Sign in with your Apple ID that is linked to your developer account, or just your Apple if you don't have a dev account.

  5. If you haven't registered your device with that account yet, a button will appear, something like 'Register device'. Click that and Apple will register the device and do the certificates and code signing. (Oh my unicorns certificates and signing is so much easier than it used to be) enter image description here

Pick your physical device and hit run and it should load onto your device without error.

iOS 7.0 No code signing identities found

I had this ambiguous error, "Command /usr/bin/codesign failed with exit code 1", when I was setting up new Jenkins boxes for iOS builds with Xcode 7.3, OSX 10.11.4.

In my case I had several things right: 1.Yes I had added my certificates to the keychain, both Apple's root and the team's cert. 2.Yes I downloaded the correct provisioning profile via xcode preferences. 3.Yes it even built manually in xcode.

However, for jenkins, there was perhaps a caching issue on xcode. What worked was: 1.Exit the Xcode GUI. 2.Get back in, and run the build manually once. 3.Only then will Xcode prompt to allow keychain access authorization. 4.Jenkins has some settings that might be able to fix this, but my machines are secure, so I click 'always allow xcode to access the keychain'.

The executable gets signed with invalid entitlements in Xcode

No solution worked for me until I've checked and set app Tests target to same provisioning profile as main app. Or if you are using automatic singing make sure you have same team selected in Tests target.

Xcode 'CodeSign error: code signing is required'

Maybe your mac's date and time are incorrect. Just correct them.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

One possible solution which works for me:

  1. Search "code sign" in Build settings
  2. Change everything in code signing identity to "iOS developer", which are "Don't code sign" originally.

Bravo!

/usr/bin/codesign failed with exit code 1

after hours of googling and trying out different things, this is what fixed it for me:

  1. Make sure there are no certificates in the System > Certificates tab on Keychain Access. Remove all duplicate certificates from there.

  2. Install the WWDR intermediate certificate under certificates from the provisioning portal, in addition to the developers certificates and make sure you see it in the Login > Certificates tab on Keychain Access.

hope this helps some of you!

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

“Unable to find manifest signing certificate in the certificate store” - even when add new key

Try this: Right click on your project -> Go to properties -> Click signing which is left side of the screen -> Uncheck the Sign the click once manifests -> Save & Build

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

All answers looks fine but i found still issue so i changed settings in Build like this in XCode 9.0 - Sharing it so it could help someone.

enter image description here

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

The below process will solve the problem,

1: Open KeyChain access, and Delete "Apple world wide Developer relations certification authority" (Which expires on 14th Feb 2016) from both "Login" and "System" sections. If you can't find it, use “Show Expired Certificates” in the 'View' menu.

enter image description here

2: Now download https://developer.apple.com/certificationauthority/AppleWWDRCA.cer and double click the certificate to add it to Keychain access > certificates (which expires on 8th Feb 2023). Now the valid status of the certificates should turn green like below.

enter image description here

Once check the status.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

I finally tracked this down to .NET Code Access Security. I have some internally-developed binary modules that are stored on and executed from a network share. To get .NET 2.0/PowerShell 2.0 to load them, I had added a URL rule to the Intranet code group to trust that directory:

PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -listgroups
Microsoft (R) .NET Framework CasPol 2.0.50727.5420
Copyright (c) Microsoft Corporation.  All rights reserved.

Security is ON
Execution checking is ON
Policy change prompt is ON

Level = Machine

Code Groups:

1.  All code: Nothing
    1.1.  Zone - MyComputer: FullTrust
        1.1.1.  StrongName - ...: FullTrust
        1.1.2.  StrongName - ...: FullTrust
    1.2.  Zone - Intranet: LocalIntranet
        1.2.1.  All code: Same site Web
        1.2.2.  All code: Same directory FileIO - 'Read, PathDiscovery'
        1.2.3.  Url - file://Server/Share/Directory/WindowsPowerShell/Modules/*: FullTrust
    1.3.  Zone - Internet: Internet
        1.3.1.  All code: Same site Web
    1.4.  Zone - Untrusted: Nothing
    1.5.  Zone - Trusted: Internet
        1.5.1.  All code: Same site Web

Note that, depending on which versions of .NET are installed and whether it's 32- or 64-bit Windows, caspol.exe can exist in the following locations, each with their own security configuration (security.config):

  • $Env:SystemRoot\Microsoft.NET\Framework\v2.0.50727\
  • $Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\
  • $Env:SystemRoot\Microsoft.NET\Framework\v4.0.30319\
  • $Env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\

After deleting group 1.2.3....

PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -remgroup 1.2.3.
Microsoft (R) .NET Framework CasPol 2.0.50727.9136
Copyright (c) Microsoft Corporation.  All rights reserved.

The operation you are performing will alter security policy.
Are you sure you want to perform this operation? (yes/no)
yes
Removed code group from the Machine level.
Success

...I am left with the default CAS configuration and local scripts now work again. It's been a while since I've tinkered with CAS, and I'm not sure why my rule would seem to interfere with those granting FullTrust to MyComputer, but since CAS is deprecated as of .NET 4.0 (on which PowerShell 3.0 is based), I guess it's a moot point now.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

If you didn't change anything related to certificates (didn't replace or update them) just do a Product -> Clean. It helped me several times. (Xcode 6.2)

How do I create a self-signed certificate for code signing on Windows?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:

  • http://timestamp.verisign.com/scripts/timstamp.dll
  • http://timestamp.globalsign.com/scripts/timstamp.dll
  • http://timestamp.comodoca.com/authenticode

Full Microsoft documentation

Downloads

For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).

Sorting a tab delimited file

I was having this problem with sort in cygwin in a bash shell when using 'general-numeric-sort'. If I specified -t$'\t' -kFg, where F is the field number, it didn't work, but when I specified both -t$'\t' and -kF,Fg (e.g -k7,7g for the 7th field) it did work. -kF,Fg without the -t$'\t' did not work.

Execute CMD command from code

You can use this to work cmd in C#:

ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = @"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();

Don't forget to write /c before your argument !!

How do I convert from BLOB to TEXT in MySQL?

That's unnecessary. Just use SELECT CONVERT(column USING utf8) FROM..... instead of just SELECT column FROM...

How do you check that a number is NaN in JavaScript?

Try this code:

isNaN(parseFloat("geoff"))

For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?

Display names of all constraints for a table in Oracle SQL

select constraint_name,constraint_type 
from user_constraints
where table_name = 'YOUR TABLE NAME';

note: table name should be in caps.

In case you don't know the name of the table then,

select constraint_name,constraint_type,table_name 
from user_constraints;

Refresh a page using PHP

header('Location: .'); seems to refresh the page in Chrome, Firefox, Edge, and Internet Explorer 11.

Java 8 LocalDate Jackson format

In configuration class define LocalDateSerializer and LocalDateDeserializer class and register them to ObjectMapper via JavaTimeModule like below:

@Configuration
public class AppConfig
{
@Bean
    public ObjectMapper objectMapper()
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_EMPTY);
        //other mapper configs
        // Customize de-serialization


        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
        mapper.registerModule(javaTimeModule);

        return mapper;
    }

    public class LocalDateSerializer extends JsonSerializer<LocalDate> {
        @Override
        public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(Constant.DATE_TIME_FORMATTER));
        }
    }

    public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

        @Override
        public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return LocalDate.parse(p.getValueAsString(), Constant.DATE_TIME_FORMATTER);
        }
    }
}

Run class in Jar file

You want:

java -cp myJar.jar myClass

The Documentation gives the following example:

C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Go To: File --> Setting --> Build, Execution, Deployment --> Gradle, then tick the use local Gradle distribution, then set Gradle home by giving path to Gradle. Tick offline work.

Like so:

Difference between Constructor and ngOnInit

The constructor is a method in JavaScript and is considered as a feature of the class in es6 .When the class is instantiated it immediately runs the constructor whether it is used in Angular framework or not.So it is called by JavaScript engine and Angular has no control on that.

import {Component} from '@angular/core';
@Component({})
class CONSTRUCTORTEST {

//This is called by Javascript not the Angular.
     constructor(){
        console.log("view constructor initialised");
     }
}

The "ConstructorTest" class is instantiated below;So it internally calls the constructor(All these happens by JavaScript(es6) no Angular).

new CONSTRUCTORTEST();

That is why there is ngOnInit lifecycle hook in Angular.ngOnInit renders when Angular has finished initialising the component.

import {Component} from '@angular/core';
@Component({})
class NGONINITTEST implements onInit{
   constructor(){}
   //ngOnInit calls by Angular
   ngOnInit(){
     console.log("Testing ngOnInit");
   }
}

First we instantiate the class as below which happen to immediate runs of constructor method.

let instance = new NGONINITTEST();

ngOnInit is called by Angular when necessary as below:

instance.ngOnInit();

But you may ask why we are using constructor in Angular?

The answer is dependencies injections.As it is mentioned before, constructor calls by JavaScript engine immediately when the class is instantiated (before calling ngOnInit by Angular), so typescript helps us to get the type of the dependencies are defined in the constructor and finally tells Angular what type of dependencies we want to use in that specific component.

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

Wait until page is loaded with Selenium WebDriver for Python

On a side note, instead of scrolling down 100 times, you can check if there are no more modifications to the DOM (we are in the case of the bottom of the page being AJAX lazy-loaded)

def scrollDown(driver, value):
    driver.execute_script("window.scrollBy(0,"+str(value)+")")

# Scroll down the page
def scrollDownAllTheWay(driver):
    old_page = driver.page_source
    while True:
        logging.debug("Scrolling loop")
        for i in range(2):
            scrollDown(driver, 500)
            time.sleep(2)
        new_page = driver.page_source
        if new_page != old_page:
            old_page = new_page
        else:
            break
    return True

How to ensure a <select> form field is submitted when it is disabled?

<select disabled="disabled">
    ....
</select>
<input type="hidden" name="select_name" value="selected value" />

Where select_name is the name that you would normally give the <select>.

Another option.

<select name="myselect" disabled="disabled">
    <option value="myselectedvalue" selected="selected">My Value</option>
    ....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />

Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.

If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.

difference between iframe, embed and object elements

Another reason to use object over iframe is that object sub resources (when an <object> performs HTTP requests) are considered as passive/display in terms of Mixed content, which means it's more secure when you must have Mixed content.

Mixed content means that when you have https but your resource is from http.

Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

Adding click event for a button created dynamically using jQuery

Question 1: Use .delegate on the div to bind a click handler to the button.

Question 2: Use $(this).val() or this.value (the latter would be faster) inside of the click handler. this will refer to the button.

$("#pg_menu_content").on('click', '#btn_a', function () {
  alert($(this).val());
});

$div = $('<div data-role="fieldcontain"/>');
$("<input type='button' value='Dynamic Button' id='btn_a' />").appendTo($div.clone()).appendTo('#pg_menu_content');

How to change sa password in SQL Server 2008 express?

I didn't know the existing sa password so this is what I did:

  1. Open Services in Control Panel

  2. Find the "SQL Server (SQLEXPRESS)" entry and select properties

  3. Stop the service

  4. Enter "-m" at the beginning of the "Start parameters" fields. If there are other parameters there already add a semi-colon after -m;

  5. Start the service

  6. Open a Command Prompt

Enter the command:

osql -S YourPcName\SQLEXPRESS -E

(change YourPcName to whatever your PC is called).

  1. At the prompt type the following commands:
alter login sa enable
go
sp_password NULL,'new_password','sa'
go
quit
  1. Stop the "SQL Server (SQLEXPRESS)" service

  2. Remove the "-m" from the Start parameters field

  3. Start the service

MySQL COUNT DISTINCT

 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

How to obtain the last path segment of a URI

You can use getPathSegments() function. (Android Documentation)

Consider your example URI:

String uri = "http://base_path/some_segment/id"

You can get the last segment using:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegment will be id.

What does it mean to bind a multicast (UDP) socket?

It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.

I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.

For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.

  // This is a fix for that bug that causes Servers to pop offline/online.
  // Servers will intermittently pop offline/online for 10 seconds or so.
  // The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
  // After several minutes, the route to the DHCP gateway may timeout, at which
  // point the pingponging stops.
  // You need 3 machines, Client machine, server A, and server B
  // Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
  // Now turn off the ping from machine B (en1), but leave the network connected.
  // You will notice that the machine transmitting on the interface with
  // the DHCP gateway will fail sendto() with errno 'No route to host'
  if ( theErr == 0 )
  {
     // inspired by 'ping -b' option in man page:      
     //      -b boundif
     //             Bind the socket to interface boundif for sending.
     struct sockaddr_in bindInterfaceAddr;
     bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
     bindInterfaceAddr.sin_family = AF_INET;
     bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
     bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
     theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     struct sockaddr_in serverAddress;
     int namelen = sizeof(serverAddress);  
     if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
        DLogErr(@"ERROR Publishing service... getsockname err");
     }
     else
     {
        DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
     }

Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.

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));

Open a Web Page in a Windows Batch FIle

Unfortunately, the best method to approach this is to use Internet Explorer as it's a browser that is guaranteed to be on Windows based machines. This will also bring compatibility of other users which might have alternative browsers such as Firefox, Chrome, Opera..etc,

start "iexplore.exe" http://www.website.com

Error when trying vagrant up

The first and most important step before starting a Vagrant is, check which all boxes are present in your system. Use this command for getting the list of boxes available.

vagrant box list

Then move to further process that is, selecting a particular box

vagrant init ubuntu/trusty64 (I have selected ubuntu/trusty64)

then,

vagrant up

Thanks

APK signing error : Failed to read key from keystore

It could be any one of the parameter, not just the file name or alias - for me it was the Key Password.

How to solve privileges issues when restore PostgreSQL Database

For people using AWS, the COMMENT ON EXTENSION is possible only as superuser, and as we know by the docs, RDS instances are managed by Amazon. As such, to prevent you from breaking things like replication, your users - even the root user you set up when you create the instance - will not have full superuser privileges:

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html

When you create a DB instance, the master user system account that you create is assigned to the rds_superuser role. The rds_superuser role is a pre-defined Amazon RDS role similar to the PostgreSQL superuser role (customarily named postgres in local instances), but with some restrictions. As with the PostgreSQL superuser role, the rds_superuser role has the most privileges on your DB instance and you should not assign this role to users unless they need the most access to the DB instance.

In order to fix this error, just use -- to comment out the lines of SQL that contains COMMENT ON EXTENSION

How to fill background image of an UIView

For Swift 3.0 use the following code:

    UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "bg.png")?.drawAsPattern(in: self.view.bounds)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)

How to find a parent with a known class in jQuery?

Assuming that this is .d, you can write

$(this).closest('.a');

The closest method returns the innermost parent of your element that matches the selector.

Delete last commit in bitbucket

By now, cloud bitbucket (I'm not sure which version) allows to revert a commit from the file system as follows (I do not see how to revert from the Bitbucket interface in the Chrome browser).

-backup your entire directory to secure the changes you inadvertently committed

-select checked out directory

-right mouse button: tortoise git menu

-repo-browser (the menu option 'revert' only undoes the uncommited changes)

-press the HEAD button

-select the uppermost line (the last commit)

-right mouse button: revert change by this commit

-after it undid the changes on the file system, press commit

-this updates GIT with a message 'Revert (your previous message). This reverts commit so-and-so'

-select 'commit and push'.

Access Form - Syntax error (missing operator) in query expression

I had this same problem. As Dedren says, the problem is not the query, but the form object's control source. Put [] around each objects Control Source. eg: Contol Source: [Product number], Control Source: Salesperson.[Salesperson number], etc.

Makita recomends going to the original table that you are referencing in your query and rename the field so that there are no spaces eg: SalesPersonNumber, ProductNumber, etc. This will solve many future problems as well. Best of Luck!

How do I get the APK of an installed app without root access?

Or you can get 'Bluetooth File Transfer' from Google Play and set the home folder to /system/ . Then you can even go to / .

How to use code to open a modal in Angular 2?

Simply, npm install --save @types/bootstrap try to match typing version with your bootstrap version. E.g. you have Bootstrap 4.3.1 then npm install --save @types/[email protected]

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

I know it is a pointed question, and the op wanted to load different properties file.

My answer is, doing custom hacks like this is a terrible idea.

If you are using spring-boot with a cloud provider such as cloud foundry, please do yourself a favor and use cloud config services

https://spring.io/projects/spring-cloud-config

It loads and merges default/dev/project-default/project-dev specific properties like magic

Again, Spring boot already gives you enough ways to do this right https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Please do not re-invent the wheel.

Optimistic vs. Pessimistic locking

Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.

If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.

This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.

In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.

How to set minDate to current date in jQuery UI Datepicker?

Set minDate to current date in jQuery Datepicker :

$("input.DateFrom").datepicker({
    minDate: new Date()
});

Automatically size JPanel inside JFrame

As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);

GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.

MySQL how to join tables on two fields

SELECT * 
FROM t1
JOIN t2 USING (id, date)

perhaps you'll need to use INNEER JOIN or where t2.id is not null if you want results only matching both conditions

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

For those want to use pragma table_info()'s result as part of a larger SQL.

select count(*) from
pragma_table_info('<table_name>')
where name='<column_name>';

The key part is to use pragma_table_info('<table_name>') instead of pragma table_info('<table_name>').


This answer is inspired by @Robert Hawkey 's reply. The reason I post it as a new answer is I don't have enough reputation to post it as comment.

HTML5 canvas ctx.fillText won't do line breaks?

Using javascript I developed a solution. It isn't beautiful but it worked for me:


function drawMultilineText(){

    // set context and formatting   
    var context = document.getElementById("canvas").getContext('2d');
    context.font = fontStyleStr;
    context.textAlign = "center";
    context.textBaseline = "top";
    context.fillStyle = "#000000";

    // prepare textarea value to be drawn as multiline text.
    var textval = document.getElementByID("textarea").value;
    var textvalArr = toMultiLine(textval);
    var linespacing = 25;
    var startX = 0;
    var startY = 0;

    // draw each line on canvas. 
    for(var i = 0; i < textvalArr.length; i++){
        context.fillText(textvalArr[i], x, y);
        y += linespacing;
    }
}

// Creates an array where the <br/> tag splits the values.
function toMultiLine(text){
   var textArr = new Array();
   text = text.replace(/\n\r?/g, '<br/>');
   textArr = text.split("<br/>");
   return textArr;
}

Hope that helps!

When to use a linked list over an array/array list?

I think that main difference is whether you frequently need to insert or remove stuff from the top of the list.

With an array, if you remove something from the top of list than the complexity is o(n) because all of the indices of the array elements will have to shift.

With a linked list, it is o(1) because you need only create the node, reassign the head and assign the reference to next as the previous head.

When frequently inserting or removing at the end of the list, arrays are preferable because the complexity will be o(1), no reindexing is required, but for a linked list it will be o(n) because you need to go from the head to the last node.

I think that searching in both linked list and arrays will be o(log n) because you will be probably be using a binary search.

Printing all global variables/local variables?

In case you want to see the local variables of a calling function use select-frame before info locals

E.g.:

(gdb) bt
#0  0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1  0xfec36f39 in thr_kill () from /lib/libc.so.1
#2  0xfebe3603 in raise () from /lib/libc.so.1
#3  0xfebc2961 in abort () from /lib/libc.so.1
#4  0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5  0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb) 

Python Matplotlib Y-Axis ticks on Right Side of Plot

Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:

import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()

It will show this:

enter image description here

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

How to add a custom Ribbon tab using VBA?

The answers on here are specific to using the custom UI Editor. I spent some time creating the interface without that wonderful program, so I am documenting the solution here to help anyone else decide if they need that custom UI editor or not.

I came across the following microsoft help webpage - https://msdn.microsoft.com/en-us/library/office/ff861787.aspx. This shows how to set up the interface manually, but I had some trouble when pointing to my custom add-in code.

To get the buttons to work with your custom macros, setup the macro in your .xlam subs to be called as described in this SO answer - Calling an excel macro from the ribbon. Basically, you'll need to add that "control As IRibbonControl" paramter to any module pointed from your ribbon xml. Also, your ribbon xml should have the onAction="myaddin!mymodule.mysub" syntax to properly call any modules loaded by the add in.

Using those instructions I was able to create an excel add in (.xlam file) that has a custom tab loaded when my VBA gets loaded into Excel along with the add in. The buttons execute code from the add in and the custom tab uninstalls when I remove the add in.

Remove a symlink to a directory

# this works:
rm foo
# versus this, which doesn't:
rm foo/

Basically, you need to tell it to delete a file, not delete a directory. I believe the difference between rm and rmdir exists because of differences in the way the C library treats each.

At any rate, the first should work, while the second should complain about foo being a directory.

If it doesn't work as above, then check your permissions. You need write permission to the containing directory to remove files.

Does Java support structs?

The equivalent in Java to a struct would be

class Member
{
    public String FirstName; 
    public String LastName;  
    public int    BirthYear; 
 };

and there's nothing wrong with that in the right circumstances. Much the same as in C++ really in terms of when do you use struct verses when do you use a class with encapsulated data.

Selecting multiple items in ListView

and to get it :

public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

                Log.d(getLocalClassName(), "onItemClick(" + view + ","
                        + position + "," + id + ")");
        }
    });

Calling dynamic function with dynamic number of parameters

Your code only works for global functions, ie. members of the window object. To use it with arbitrary functions, pass the function itself instead of its name as a string:

function dispatch(fn, args) {
    fn = (typeof fn == "function") ? fn : window[fn];  // Allow fn to be a function object or the name of a global function
    return fn.apply(this, args || []);  // args is optional, use an empty array by default
}

function f1() {}

function f2() {
    var f = function() {};
    dispatch(f, [1, 2, 3]);
}

dispatch(f1, ["foobar"]);
dispatch("f1", ["foobar"]);

f2();  // calls inner-function "f" in "f2"
dispatch("f", [1, 2, 3]);  // doesn't work since "f" is local in "f2"

How do I revert a Git repository to a previous commit?

It can be done much easier with Sourcetree. Just right click commit you are looking for and chose 'Checkout' from menu.

Enter image description here

How to refer environment variable in POM.xml?

Can't we use

<properties>
    <my.variable>${env.MY_VARIABLE}</my.variable>
</properties>

Should I always use a parallel stream when possible?

Never parallelize an infinite stream with a limit. Here is what happens:

    public static void main(String[] args) {
        // let's count to 1 in parallel
        System.out.println(
            IntStream.iterate(0, i -> i + 1)
                .parallel()
                .skip(1)
                .findFirst()
                .getAsInt());
    }

Result

    Exception in thread "main" java.lang.OutOfMemoryError
        at ...
        at java.base/java.util.stream.IntPipeline.findFirst(IntPipeline.java:528)
        at InfiniteTest.main(InfiniteTest.java:24)
    Caused by: java.lang.OutOfMemoryError: Java heap space
        at java.base/java.util.stream.SpinedBuffer$OfInt.newArray(SpinedBuffer.java:750)
        at ...

Same if you use .limit(...)

Explanation here: Java 8, using .parallel in a stream causes OOM error

Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g.

public static void main(String[] args) {
    // let's count to 1 in parallel
    System.out.println(
            IntStream.range(1, 1000_000_000)
                    .parallel()
                    .skip(100)
                    .findFirst()
                    .getAsInt());
}

This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.

Why can't I set text to an Android TextView?

In your XML, you had used Textview, But in Java Code you had used EditText instead of TextView. If you change it into TextView you can set Text to to your TextView Object.

text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");

hope it will work.

Set Focus After Last Character in Text Box

This is the easy way to do it. If you're going backwards, just add $("#Prefix").val($("#Prefix").val()); after you set the focus

This is the more proper (cleaner) way:

function SetCaretAtEnd(elem) {
        var elemLen = elem.value.length;
        // For IE Only
        if (document.selection) {
            // Set focus
            elem.focus();
            // Use IE Ranges
            var oSel = document.selection.createRange();
            // Reset position to 0 & then set at end
            oSel.moveStart('character', -elemLen);
            oSel.moveStart('character', elemLen);
            oSel.moveEnd('character', 0);
            oSel.select();
        }
        else if (elem.selectionStart || elem.selectionStart == '0') {
            // Firefox/Chrome
            elem.selectionStart = elemLen;
            elem.selectionEnd = elemLen;
            elem.focus();
        } // if
    } // SetCaretAtEnd()

Convert hexadecimal string (hex) to a binary string

public static byte[] hexToBytes(String string) {
 int length = string.length();
 byte[] data = new byte[length / 2];
 for (int i = 0; i < length; i += 2) {
  data[i / 2] = (byte)((Character.digit(string.charAt(i), 16) << 4) + Character.digit(string.charAt(i + 1), 16));
 }
 return data;
}

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

This is caused since the generation tried to add your component to a module, i.e. to add this line

import { MyComponent } from './Components/my-component/my-component.component';

but it found 2 modules.

As stated here, they fixed it to a situation where as long as in the root src/app folder you have only 1 module, you're fine, so just move the secondaries modules to a sub-folder.

Otherwise you have to use --module

How to print a dictionary's key?

Or you can do it that manner:

for key in my_dict:
     print key, my_dict[key]

Change Project Namespace in Visual Studio

Right click properties, Application tab, then see the assembly name and default namespace

Python: Best way to add to sys.path relative to the current running script

You can run the script with python -m from the relevant root dir. And pass the "modules path" as argument.

Example: $ python -m module.sub_module.main # Notice there is no '.py' at the end.


Another example:

$ tree  # Given this file structure
.
+-- bar
¦   +-- __init__.py
¦   +-- mod.py
+-- foo
    +-- __init__.py
    +-- main.py

$ cat foo/main.py
from bar.mod import print1
print1()

$ cat bar/mod.py
def print1():
    print('In bar/mod.py')

$ python foo/main.py  # This gives an error
Traceback (most recent call last):
  File "foo/main.py", line 1, in <module>
    from bar.mod import print1
ImportError: No module named bar.mod

$ python -m foo.main  # But this succeeds
In bar/mod.py

AngularJS : Initialize service with asynchronous data

Have you had a look at $routeProvider.when('/path',{ resolve:{...}? It can make the promise approach a bit cleaner:

Expose a promise in your service:

app.service('MyService', function($http) {
    var myData = null;

    var promise = $http.get('data.json').success(function (data) {
      myData = data;
    });

    return {
      promise:promise,
      setData: function (data) {
          myData = data;
      },
      doStuff: function () {
          return myData;//.getSomeData();
      }
    };
});

Add resolve to your route config:

app.config(function($routeProvider){
  $routeProvider
    .when('/',{controller:'MainCtrl',
    template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
    resolve:{
      'MyServiceData':function(MyService){
        // MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
        return MyService.promise;
      }
    }})
  }):

Your controller won't get instantiated before all dependencies are resolved:

app.controller('MainCtrl', function($scope,MyService) {
  console.log('Promise is now resolved: '+MyService.doStuff().data)
  $scope.data = MyService.doStuff();
});

I've made an example at plnkr: http://plnkr.co/edit/GKg21XH0RwCMEQGUdZKH?p=preview

How do I POST JSON data with cURL?

This worked well for me, additionally using BASIC authentication:

curl -v --proxy '' --basic -u Administrator:password -X POST -H "Content-Type: application/json"
        --data-binary '{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}'
        http://httpbin.org/post

Of course, you should never use BASIC authentication without SSL and a checked certificate.

I ran into this again today, using Cygwin's cURL 7.49.1 for Windows... And when using --data or --data-binary with a JSON argument, cURL got confused and would interpret the {} in the JSON as a URL template. Adding a -g argument to turn off cURL globbing fixed that.

See also Passing a URL with brackets to curl.

Extracting the top 5 maximum values in excel

There 3 functions you want to look at here:

I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:

Excel sample

  • In Cells A13 to A17, the values 1 to 5 were inserted to specify the nth highest value.
  • In Cell B13, the following formula was added: =LARGE($B$2:$B$11, A13)
  • In Cell C13, the following formula was added: =INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
  • These formulae get the highest ranking OPS and Player based on the value in A13.
  • Simply select and drag to copy these formulae down to the next 4 cells which will reference the corresponding ranking in Column A.

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
         /
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
                 /
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

How to compile LEX/YACC files on Windows?

You can find the latest windows version of flex & bison here: http://sourceforge.net/projects/winflexbison/

MySQL - select data from database between two dates

You can use MySQL DATE function like below

For instance, if you want results between 2017-09-05 till 2017-09-09

SELECT DATE(timestamp_field) as date FROM stocks_annc WHERE DATE(timestamp_field) >= '2017-09-05' AND DATE(timestamp_field) <= '2017-09-09'

Make sure to wrap the dates within single quotation ''

Hope this helps.

What is the role of "Flatten" in Keras?

If you read the Keras documentation entry for Dense, you will see that this call:

Dense(16, input_shape=(5,3))

would result in a Dense network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x) transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])] with shape (5, 16). In order to have the behavior you specify you may first Flatten your input to a 15-d vector and then apply Dense:

model = Sequential()
model.add(Flatten(input_shape=(3, 2)))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(4))
model.compile(loss='mean_squared_error', optimizer='SGD')

EDIT: As some people struggled to understand - here you have an explaining image:

enter image description here

Recover from git reset --hard?

(answer suitable for a subset of users)

If you're on (any recent) macOS, and even if you're away from your Time Machine disk, the OS will have saved hourly backups, called local snapshots.

Enter Time Machine and navigate to the file you lost. The OS will then ask you:

The location to which you're restoring "file.ext" already contains an
item with the same name. Do you want to replace it with the one you're
restoring?

You should be able to recover the file(s) you lost.

Visualizing decision tree in scikit-learn

Simple way founded here with pydotplus (graphviz must be installed):

from IPython.display import Image  
from sklearn import tree
import pydotplus # installing pyparsing maybe needed

...

dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())

How to create a Date in SQL Server given the Day, Month and Year as Integers

In SQL Server 2012+, you can use DATEFROMPARTS():

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT DATEFROMPARTS (@Year, @Month, @Day);

In earlier versions, one method is to create and convert a string.

There are a few string date formats which SQL Server reliably interprets regardless of the date, language, or internationalization settings.

A six- or eight-digit string is always interpreted as ymd. The month and day must always be two digits.

https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql

So a string in the format 'yyyymmdd' will always be properly interpreted.

(ISO 8601-- YYYY-MM-DDThh:mm:ss-- also works, but you have to specify time and therefore it's more complicated than you need.)

While you can simply CAST this string as a date, you must use CONVERT in order to specify a style, and you must specify a style in order to be deterministic (if that matters to you).

The "yyyymmdd" format is style 112, so your conversion looks like this:

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

And it results in:

2016-10-25

Technically, the ISO/112/yyyymmdd format works even with other styles specified. For example, using that text format with style 104 (German, dd.mm.yyyy):

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),104);

Also still results in:

2016-10-25

Other formats are not as robust. For example this:

SELECT CASE WHEN CONVERT(date,'01-02-1900',110) = CONVERT(date,'01-02-1900',105) THEN 1 ELSE 0 END;

Results in:

0

As a side note, with this method, beware that nonsense inputs can yield valid but incorrect dates:

DECLARE @Year int = 2016, @Month int = 0, @Day int = 1025;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

Also yields:

2016-10-25

DATEFROMPARTS protects you from invalid inputs. This:

DECLARE @Year int = 2016, @Month int = 10, @Day int = 32;
SELECT DATEFROMPARTS (@Year, @Month, @Day);

Yields:

Msg 289, Level 16, State 1, Line 2 Cannot construct data type date, some of the arguments have values which are not valid.

Also beware that this method does not work for dates prior to 1000-01-01. For example:

DECLARE @Year int = 900, @Month int = 1, @Day int = 1;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

Yields:

Msg 241, Level 16, State 1, Line 2 Conversion failed when converting date and/or time from character string.

That's because the resulting string, '9000101', is not in the 'yyyymmdd' format. To ensure proper formatting, you'd have to pad it with leading zeroes, at the sacrifice of some small amount of performance. For example:

DECLARE @Year int = 900, @Month int = 1, @Day int = 1;
SELECT CONVERT(date,RIGHT('000' + CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),8),112);

Results in:

0900-01-01

There are other methods aside from string conversion. Several are provided in answers to "Create a date with T-SQL". A notable example involves creating the date by adding years, months, and days to the "zero date".

(This answer was inspired by Gordon Linoff's answer, which I expanded on and provided additional documentation and notes.)

How do I draw a set of vertical lines in gnuplot?

From the Gnuplot documentation. To draw a vertical line from the bottom to the top of the graph at x=3, use:

set arrow from 3, graph 0 to 3, graph 1 nohead

Create directories using make file

make in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:

outDir/someTarget: Makefile outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget

This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.

However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:

# The pipe symbol tells make that the following prerequisites are order-only
#                           |
#                           v
outDir/someTarget: Makefile | outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

This correctly yields:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
make: 'outDir/someTarget' is up to date.

TL;DR:

Write a rule to create the directory:

$(OUT_DIR):
    mkdir -p $(OUT_DIR)

And have the targets for the stuff inside depend on the directory order-only:

$(OUT_DIR)/someTarget: ... | $(OUT_DIR)

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Return value from exec(@sql)

On the one hand you could use sp_executesql:

exec sp_executesql N'select @rowcount=count(*) from anytable', 
                    N'@rowcount int output', @rowcount output;

On the other hand you could use a temporary table:

declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);

How to download image from url

For anyone who wants to download an image WITHOUT saving it to a file:

Image DownloadImage(string fromUrl)
{
    using (System.Net.WebClient webClient = new System.Net.WebClient())
    {
        using (Stream stream = webClient.OpenRead(fromUrl))
        {
            return Image.FromStream(stream);
        }
    }
}

Check if checkbox is NOT checked on click - jQuery

Check out some of the answers to this question - I think it might apply to yours:

how to run click function after default behaviour of a element

I think you're running into an inconsistency in the browser implementation of the onclick function. Some choose to toggle the checkbox before the event is fired and some after.

WPF Binding StringFormat Short Date String

Try this:

<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />

which is culture sensitive and requires .NET 3.5 SP1 or above.

NOTE: This is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.

There's a full list of string format on the MSDN page on Standard Date and Time Format Strings and a fuller explanation of all the options on this MSDN blog post

However, there is one gotcha with this - it always outputs the date in US format unless you set the culture to the correct value yourself.

If you do not set this property, the binding engine uses the Language property of the binding target object. In XAML this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if one has been explicitly set.

Source

One way to do this is in the code behind (assuming you've set the culture of the thread to the correct value):

this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

The other way is to set the converter culture in the binding:

<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />

Though this doesn't allow you to localise the output.

How Can I Remove “public/index.php” in the URL Generated Laravel?

Don't get confused with other option the snippet below I am using and will be useful for you too. Put the below htacces in your root.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    public/    [L]
    RewriteRule    (.*) public/$1    [L]
</IfModule>

Go to your public directory and put another htaccess file with the code snippet below

<IfModule mod_rewrite.c>
    RewriteEngine On
    # Removes index.php from ExpressionEngine URLs  
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

</IfModule>

Its working... !!!

Laravel Uses below .htaccess

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

Check date with todays date

tl;dr

LocalDate
.parse( "2021-01-23" )
.isBefore(
    LocalDate.now(
        ZoneId.of( "Africa/Tunis" ) 
    )
)

… or:

try 
{
    org.threeten.extra.LocalDateRange range =         
        LocalDateRange.of( 
            LocalDate.of( "2021-01-23" ) ,
            LocalDate.of( "2021-02-21" )
        )
    ;
    if( range.isAfter( 
        LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
    ) { … }
    else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
    // Handle error where end is before start.
}

Details

The other answers ignore the crucial issue of time zone.

The other answers use outmoded classes.

Avoid old date-time classes

The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.

java.time

LocalDate

For date-only values, without time-of-day and without time zone, use the LocalDate class.

LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );

Time Zone

Be aware that while LocalDate does not store a time zone, determining a date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.

If all you have is an offset-from-UTC, use ZoneOffset. If you have a full time zone (continent/region), then use ZoneId. If you want UTC, use the handy constant ZoneOffset.UTC.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

Comparing is easy with isEqual, isBefore, and isAfter methods.

boolean invalidInterval = stop.isBefore( start );

We can check to see if today is contained within this date range. In my logic shown here I use the Half-Open approach where the beginning is inclusive while the ending is exclusive. This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.

// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;

LocalDateRange

If working extensively with such spans of time, consider adding the ThreeTen-Extra library to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.

ThreeTen-Extra includes an LocalDateRange class with handy methods such as abuts, contains, encloses, overlaps, and so on.


About java.time

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

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

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

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

Where to obtain the java.time classes?

Pandas - replacing column values

Can try this too!
Create a dictionary of replacement values.

import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

enter image description here

replace_dict= {0:'Female',1:'Male'}
print(replace_dict)

enter image description here

Use the map function for replacing values

data['sex']=data['sex'].map(replace_dict)

Output after replacing
enter image description here

minimize app to system tray

don't forget to add icon file to your notifyIcon or it will not appear in the tray.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I had the same issue on Windows 7 and I had to install both JDK and JRE and it's a success.

What's the best way to add a drop shadow to my UIView

On viewWillLayoutSubviews:

override func viewWillLayoutSubviews() {
    sampleView.layer.masksToBounds =  false
    sampleView.layer.shadowColor = UIColor.darkGrayColor().CGColor;
    sampleView.layer.shadowOffset = CGSizeMake(2.0, 2.0)
    sampleView.layer.shadowOpacity = 1.0
}

Using Extension of UIView:

extension UIView {

    func addDropShadowToView(targetView:UIView? ){
        targetView!.layer.masksToBounds =  false
        targetView!.layer.shadowColor = UIColor.darkGrayColor().CGColor;
        targetView!.layer.shadowOffset = CGSizeMake(2.0, 2.0)
        targetView!.layer.shadowOpacity = 1.0
    }
}

Usage:

sampleView.addDropShadowToView(sampleView)

Undefined Reference to

Try to remove the constructor and destructors, it's working for me....

Get first n characters of a string

if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For anyone coming along later, like I did, and seeing this...

I was receiving the same error because I did not have the extension "enabled" in my php.ini file. I would imagine you might also get this error if you have recently upgraded your php version and did not properly update your php.ini file.

If you are receiving this error shortly after upgrading your php version, the info below might help you out:

PHP 7.4 slightly changed its syntax in the php.ini file. Now, to enable the mysql pdo, make sure extension=pdo_mysql is uncommented in your php.ini file. (line 931 in the default php.ini setup)

The line used to be:

extension=php_pdo_mysql.dll on Windows

extension=php_pdo_mysql.so on Linux/Mac

as Sk8erPeter pointed out. but the .dll and .so endings are to be deprecated and so it is best practice to begin getting rid of those endings and using just extension=<ext>

The below is pulled from the default php.ini-production file from the php 7.4 zip download under "Dynamic Extensions":

Note : The syntax used in previous PHP versions ('extension=.so' and 'extension='php_.dll') is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Ruby: How to get the first character of a string

Try this:

def word(string, num)
    string = 'Smith'
    string[0..(num-1)]
end

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Find current directory and file's directory

A bit late to the party, but I think the most succinct way to find just the name of your current execution context would be

current_folder_path, current_folder_name = os.path.split(os.getcwd())

Releasing memory in Python

Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (PyObject_Malloc) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.

Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The int type maintains a freelist with its own allocated memory, and clearing it requires calling PyInt_ClearFreeList(). This can be called indirectly by doing a full gc.collect.

Try it like this, and tell me what you get. Here's the link for psutil.Process.memory_info.

import os
import gc
import psutil

proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss

# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss

# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss

# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss

pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)

Output:

Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%

Edit:

I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.

The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with mallopt (M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you free.

In 3.x range doesn't create a list, so the test above won't create 10 million int objects. Even if it did, the int type in 3.x is basically a 2.x long, which doesn't implement a freelist.

Joining three tables using MySQL

SELECT 
employees.id, 
CONCAT(employees.f_name," ",employees.l_name) AS   'Full Name', genders.gender_name AS 'Sex', 
depts.dept_name AS 'Team Name', 
pay_grades.pay_grade_name AS 'Band', 
designations.designation_name AS 'Role' 
FROM employees 
LEFT JOIN genders ON employees.gender_id = genders.id 
LEFT JOIN depts ON employees.dept_id = depts.id 
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id 
LEFT JOIN designations ON employees.designation_id = designations.id 
ORDER BY employees.id;

You can JOIN multiple TABLES like this example above.

How do I use cascade delete with SQL Server?

I think you cannot just delete the tables property what if this is actual production data, just delete the contents that dont affect the table schema.

How to read the last row with SQL Server

SELECT * from Employees where [Employee ID] = ALL (SELECT MAX([Employee ID]) from Employees)

Where does git config --global get written to?

I had also a problem with my global .gitconfig This is for the case someone also has this strange

git said:

fatal: unknown error occured while reading the configuration files

Now I fixed it. The problem was a second .gitconfig in this folder:

c:\Users\myUser.config\git\config

I don't know where it came from... But now everything works like a charme again.

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

How do I call one constructor from another in Java?

Yes it is possible

public class User {

 private String name = "";
 private String surname = "";
 private int age = 0;
 public User(){
    this("name is undefined","surname is undefined",0);
 }
    public User(String name,String surname){
      this(name,surname,0);
   }


    public User(String name, String surname, int age) {
      this.name = name;
      this.surname = surname;
      this.age = age;
  }
}

explicit casting from super class to subclass

As explained, it is not possible. If you want to use a method of the subclass, evaluate the possibility to add the method to the superclass (may be empty) and call from the subclasses getting the behaviour you want (subclass) thanks to polymorphism. So when you call d.method() the call will succeed withoug casting, but in case the object will be not a dog, there will not be a problem

Using openssl to get the certificate from a server

You can get and store the server root certificate using next bash script:

CERTS=$(echo -n | openssl s_client -connect $HOST_NAME:$PORT -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p')
echo "$CERTS" | awk -v RS="-----BEGIN CERTIFICATE-----" 'NR > 1 { printf RS $0 > "'$SERVER_ROOT_CERTIFICATE'"; close("'$SERVER_ROOT_CERTIFICATE'") }'

Just overwrite required variables.

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

How can I change column types in Spark SQL's DataFrame?

One can change data type of a column by using cast in spark sql. table name is table and it has two columns only column1 and column2 and column1 data type is to be changed. ex-spark.sql("select cast(column1 as Double) column1NewName,column2 from table") In the place of double write your data type.

Descending order by date filter in AngularJs

You can prefix the argument in orderBy with a '-' to have descending order instead of ascending. I would write it like this:

<div class="recent" 
   ng-repeat="reader in book.reader | orderBy: '-created_at' | limitTo: 1">
</div>

This is also stated in the documentation for the filter orderBy.

How to unblock with mysqladmin flush hosts

You can easily restart your MySql service. This kicks the error off.

List of Java processes

You can use single command pgrep as well (doesn't require you to use pipes and multiple commands):

pgrep -fl java

Keep CMD open after BAT file executes

When the .bat file is started not from within the command line (e.g. double-clicking).

echo The echoed text
@pause

at_pause

echo The echoed text
pause

pause

echo The echoed text
cmd /k

cmd k

echo The echoed text & pause

and_pause

Magento - Retrieve products with a specific attribute value

$attribute = Mage::getModel('eav/entity_attribute')
                ->loadByCode('catalog_product', 'manufacturer');

$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
            ->setAttributeFilter($attribute->getData('attribute_id'))
            ->setStoreFilter(0, false);

$preparedManufacturers = array();            
foreach($valuesCollection as $value) {
    $preparedManufacturers[$value->getOptionId()] = $value->getValue();
}   


if (count($preparedManufacturers)) {
    echo "<h2>Manufacturers</h2><ul>";
    foreach($preparedManufacturers as $optionId => $value) {
        $products = Mage::getModel('catalog/product')->getCollection();
        $products->addAttributeToSelect('manufacturer');
        $products->addFieldToFilter(array(
            array('attribute'=>'manufacturer', 'eq'=> $optionId,          
        ));

        echo "<li>" . $value . " - (" . $optionId . ") - (Products: ".count($products).")</li>";
    }
    echo "</ul>";
}

how to use ng-option to set default value of select element

So assuming that object is in your scope:

<div ng-controller="MyCtrl">
  <select ng-model="prop.value" ng-options="v for v in prop.values">
  </select>
</div>

 

function MyCtrl($scope) {
  $scope.prop = {
    "type": "select", 
    "name": "Service",
    "value": "Service 3", 
    "values": [ "Service 1", "Service 2", "Service 3", "Service 4"] 
  };
}

Working Plunkr: http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g

How do I use a third-party DLL file in Visual Studio C++?

These are two ways of using a DLL file in Windows:

  1. There is a stub library (.lib) with associated header files. When you link your executable with the lib-file it will automatically load the DLL file when starting the program.

  2. Loading the DLL manually. This is typically what you want to do if you are developing a plugin system where there are many DLL files implementing a common interface. Check out the documentation for LoadLibrary and GetProcAddress for more information on this.

For Qt I would suspect there are headers and a static library available that you can include and link in your project.

Java HTML Parsing

The nu.validator project is an excellent, high performance HTML parser that doesn't cut corners correctness-wise.

The Validator.nu HTML Parser is an implementation of the HTML5 parsing algorithm in Java. The parser is designed to work as a drop-in replacement for the XML parser in applications that already support XHTML 1.x content with an XML parser and use SAX, DOM or XOM to interface with the parser. Low-level functionality is provided for applications that wish to perform their own IO and support document.write() with scripting. The parser core compiles on Google Web Toolkit and can be automatically translated into C++. (The C++ translation capability is currently used for porting the parser for use in Gecko.)

Reverse of JSON.stringify?

JSON.stringify and JSON.parse are almost oposites, and "usually" this kind of thing will work:

var obj = ...;
var json = JSON.stringify(obj);  
var obj2 = JSON.parse(json);

so that obj and obj2 are "the same".

However there are some limitations to be aware of. Often these issues dont matter as you're dealing with simple objects. But I'll illustrate some of them here, using this helper function:

function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
  • You'll only get ownProperties of the object and lose prototypes:

    var MyClass = function() { this.foo="foo"; } 
    MyClass.prototype = { bar:"bar" }
    
    var o = new MyClass();
    var oo = jsonrepack(o);
    console.log(oo.bar); // undefined
    console.log( oo instanceof MyClass ); // false
    
  • You'll lose identity:

    var o = {};
    var oo = jsonrepack(o);
    console.log( o === oo ); // false
    
  • Functions dont survive:

    jsonrepack( { f:function(){} } ); // Returns {}
    
  • Date objects end up as strings:

    jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
    
  • Undefined values dont survive:

    var v = { x:undefined }
    console.log("x" in v);              // true
    console.log("x" in jsonrepack(v));  // false
    
  • Objects that provide a toJSON function may not behave correctly.

    x = { f:"foo", toJSON:function(){ return "EGAD"; } }
    jsonrepack(x) // Returns 'EGAD'
    

I'm sure there are issues with other built-in-types too. (All this was tested using node.js so you may get slightly different behaviour depending on your environment too).

When it does matter it can sometimes be overcome using the additional parameters of JSON.parse and JSON.stringify. For example:

function MyClass (v) {
   this.date = new Date(v.year,1,1);
   this.name = "an object";
};

MyClass.prototype.dance = function() {console.log("I'm dancing"); }

var o = new MyClass({year:2010});
var s = JSON.stringify(o);

// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
  if(k==="") { 
     var rv = new MyClass(1990,0,0);
     rv.date = v.date;
     rv.name = v.name;
     return rv
  } else if(k==="date") {
    return new Date( Date.parse(v) );
  } else { return v; } } );

console.log(o);             // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance();                  // I'm dancing

console.log(o2);            // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]        
o2.dance();                 // I'm dancing

turn typescript object into json string

TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:

  • JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
  • JSON.stringify() method converts a JavaScript object or value to a JSON string.

Example:

_x000D_
_x000D_
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';_x000D_
_x000D_
_x000D_
const JSobj = JSON.parse(jsonString);_x000D_
_x000D_
console.log(JSobj);_x000D_
console.log(typeof JSobj);_x000D_
_x000D_
const JSON_string = JSON.stringify(JSobj);_x000D_
_x000D_
console.log(JSON_string);_x000D_
console.log(typeof JSON_string);
_x000D_
_x000D_
_x000D_

How to send POST in angularjs with multiple params?

You can also send (POST) multiple params within {} and add it.

Example:

$http.post(config.url+'/api/assign-badge/', {employeeId:emp_ID,bType:selectedCat,badge:selectedBadge})
    .then(function(response) {
        NotificationService.displayNotification('Info', 'Successfully Assigned!', true);
    }, function(response) {
});

where employeeId, bType (Badge Catagory), and badge are three parameters.

Bootstrap 4 responsive tables won't take up 100% width

That's because the .table-responsive class adds the property display: block to your element which changes it from the previous display: table.

Override this property back to display: table in your own stylesheet

.table-responsive {
    display: table;
}

Note: make sure this style executes after your bootstrap code for it to override.

How to read data from java properties file using Spring Boot

i would suggest the following way:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

Setting a custom back button disable the swipe back feature.

The best thing to do to keep it is to subclass UINavigationViewController and set itself as the interactivePopGestureRecognizer delegate; then you can return YES from gestureRecognizerShouldBegin to allow the swipe back.

For example, this is done in AHKNavigationController

And a Swift version here: https://stackoverflow.com/a/43433530/308315

Is it possible to use the instanceof operator in a switch statement?

Here's a functional way of accomplishing it in Java 8 using http://www.vavr.io/

import static io.vavr.API.*;
import static io.vavr.Predicates.instanceOf;
public Throwable liftRootCause(final Throwable throwable) {
        return Match(throwable).of(
                Case($(instanceOf(CompletionException.class)), Throwable::getCause),
                Case($(instanceOf(ExecutionException.class)), Throwable::getCause),
                Case($(), th -> th)
        );
    }

Visual Studio Community 2015 expiration date

I also get same issue after I repair vs2015, even I click check license online, still fail. Correct action is: 1. Sign out 2. Check License Status, then it will pop-up login window, after login then it able to successfully get the license info.

Read a file in Node.js

simple synchronous way with node:

let fs = require('fs')

let filename = "your-file.something"

let content = fs.readFileSync(process.cwd() + "/" + filename).toString()

console.log(content)

Checking if a character is a special character in Java

Take a look at class java.lang.Character static member methods (isDigit, isLetter, isLowerCase, ...)

Example:

String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
   char ch = str.charAt(i);
   if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
      ++specials;
   } else if (Character.isDigit(ch)) {
      ++digits;
   } else if (Character.isSpace(ch)) {
      ++spaces;
   } else {
      ++letters;
   }
}

How to output oracle sql result into a file in windows?

just to make the Answer 2 much easier, you can also define the folder where you can put your saved file

    spool /home/admin/myoutputfile.txt
    select * from table_name;
    spool off;

after that only with nano or vi myoutputfile.txt, you will see all the sql track.

hope is that help :)

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)

    [Table("UserOtherEntity")]
        public partial class UserOtherEntity
        {
            public Guid UserOtherEntityId { get; set; }
            [Required]
            [StringLength(128)]
            public string UserId { get; set; }
            [Required]
            public Guid OtherEntityId { get; set; }
            public virtual OtherEntity OtherEntity { get; set; }
        }

    public partial class UserOtherEntity : DataManager
        {
            public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
            {
                return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
            }
        }

public partial class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [NotMapped]
        public IEnumerable<OtherEntity> OtherEntities
        {
            get
            {
                return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
            }
        }
    }

Init array of structs in Go

It looks like you are trying to use (almost) straight up C code here. Go has a few differences.

  • First off, you can't initialize arrays and slices as const. The term const has a different meaning in Go, as it does in C. The list should be defined as var instead.
  • Secondly, as a style rule, Go prefers basenameOpts as opposed to basename_opts.
  • There is no char type in Go. You probably want byte (or rune if you intend to allow unicode codepoints).
  • The declaration of the list must have the assignment operator in this case. E.g.: var x = foo.
  • Go's parser requires that each element in a list declaration ends with a comma. This includes the last element. The reason for this is because Go automatically inserts semi-colons where needed. And this requires somewhat stricter syntax in order to work.

For example:

type opt struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}

var basenameOpts = []opt { 
    opt {
        shortnm: 'a', 
        longnm: "multiple", 
        needArg: false, 
        help: "Usage for a",
    },
    opt {
        shortnm: 'b', 
        longnm: "b-option", 
        needArg: false, 
        help: "Usage for b",
    },
}

An alternative is to declare the list with its type and then use an init function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init functions are run when the program is being initialized and are guaranteed to finish before main is executed. You can have multiple init functions in a package, or even in the same source file.

    type opt struct {
        shortnm      byte
        longnm, help string
        needArg      bool
    }

    var basenameOpts []opt

    func init() { 
        basenameOpts = []opt{
            opt {
                shortnm: 'a', 
                longnm: "multiple", 
                needArg: false, 
                help: "Usage for a",
            },
            opt {
                shortnm: 'b', 
                longnm: "b-option", 
                needArg: false, 
               help: "Usage for b",
            },
        }
    }

Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.

Blur the edges of an image or background image with CSS

<html>
<head>
<meta charset="utf-8">
<title>test</title>

<style>
#grad1 {
  height: 400px;
  width: 600px;
  background-image: url(t1.jpg);/* Select Image Hare */
}


#gradup {
  height: 100%;
  width: 100%;
  background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */

}
</style>

</head>

<body>
<h1>Fade Image Edge With Radial Gradient</h1>

<div id="grad1"><div id="gradup"></div></div>

</body>
</html>

Using jQuery to see if a div has a child with a certain class

Simple Way

if ($('#text-field > p.filled-text').length != 0)

Angular 2 - Checking for server errors from subscribe

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

this.httpService.makeRequest()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

Rx.Observable.prototype.finally(action)

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';

// ...

this.httpService.getRequest()
    .finally(() => {
      // Execute after graceful or exceptionally termination
      console.log('Handle logging logic...');
    })
    .subscribe (
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // No errors, route to new page
      }
    );

Find where python is installed (if it isn't default dir)

To find all the installations of Python on Windows run this at the command prompt:

dir site.py /s

Make sure you are in the root drive. You will see something like this.

A SQL Query to select a string between two known strings

<pre>

DECLARE @text VARCHAR(MAX)

SET @text = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'

declare @pretext as nvarchar(100) = 'the dog'    
declare @posttext as nvarchar(100) = 'immediately'

SELECT 
 CASE 
When CHARINDEX(@posttext, @Text) - (CHARINDEX(@pretext, @Text) + len(@pretext)) < 0 THEN 
''
Else
SUBSTRING(@Text, CHARINDEX(@pretext, @Text) + len(@pretext)
,   CHARINDEX(@posttext, @Text) - (CHARINDEX(@pretext, @Text) + len(@pretext)) )    
END as betweentext  

How can you represent inheritance in a database?

The 3rd option is to create a "Policy" table, then a "SectionsMain" table that stores all of the fields that are in common across the types of sections. Then create other tables for each type of section that only contain the fields that are not in common.

Deciding which is best depends mostly on how many fields you have and how you want to write your SQL. They would all work. If you have just a few fields then I would probably go with #1. With "lots" of fields I would lean towards #2 or #3.

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

You can use [FromBody] but you need to set the Content-Type header of your request to application/json, i.e.

Content-Type: application/json

How to write log to file

To help others, I create a basic log function to handle the logging in both cases, if you want the output to stdout, then turn debug on, its straight forward to do a switch flag so you can choose your output.

func myLog(msg ...interface{}) {
    defer func() { r := recover(); if r != nil { fmt.Print("Error detected logging:", r) } }()
    if conf.DEBUG {
        fmt.Println(msg)
    } else {
        logfile, err := os.OpenFile(conf.LOGDIR+"/"+conf.AppName+".log", os.O_RDWR | os.O_CREATE | os.O_APPEND,0666)
        if !checkErr(err) {
            log.SetOutput(logfile)
            log.Println(msg)
        }
        defer logfile.Close()
    }
}




copy db file with adb pull results in 'permission denied' error

  1. Create a folder in sdcard :
adb shell "su 0 mkdir /sdcard/com.test"
  1. Move your files to the new folder :
adb shell "su 0 mv -F /data/data/com.test/files/ /sdcard/com.test/"
  1. You can now use adb pull :
adb pull /sdcard/com.test

Java Synchronized list

Yes, it will work fine as you have synchronized the list . I would suggest you to use CopyOnWriteArrayList.

CopyOnWriteArrayList<String> cpList=new CopyOnWriteArrayList<String>(new ArrayList<String>());

    void remove(String item)
    {
         do something; (doesn't work on the list)
                 cpList..remove(item);
    }

How to load external scripts dynamically in Angular?

import { Injectable } from '@angular/core';
import * as $ from 'jquery';

interface Script {
    src: string;
    loaded: boolean;
}

@Injectable()
export class ScriptLoaderService {
    public _scripts: Script[] = [];

    /**
     * @deprecated
     * @param tag
     * @param {string} scripts
     * @returns {Promise<any[]>}
     */
    load(tag, ...scripts: string[]) {
        scripts.forEach((src: string) => {
            if (!this._scripts[src]) {
                this._scripts[src] = { src: src, loaded: false };
            }
        });

        const promises: any[] = [];
        scripts.forEach(src => promises.push(this.loadScript(tag, src)));

        return Promise.all(promises);
    }

    /**
     * Lazy load list of scripts
     * @param tag
     * @param scripts
     * @param loadOnce
     * @returns {Promise<any[]>}
     */
    loadScripts(tag, scripts, loadOnce?: boolean) {
        debugger;
        loadOnce = loadOnce || false;

        scripts.forEach((script: string) => {
            if (!this._scripts[script]) {
                this._scripts[script] = { src: script, loaded: false };
            }
        });

        const promises: any[] = [];
        scripts.forEach(script => promises.push(this.loadScript(tag, script, loadOnce)));

        return Promise.all(promises);
    }

    /**
     * Lazy load a single script
     * @param tag
     * @param {string} src
     * @param loadOnce
     * @returns {Promise<any>}
     */
    loadScript(tag, src: string, loadOnce?: boolean) {
        debugger;
        loadOnce = loadOnce || false;

        if (!this._scripts[src]) {
            this._scripts[src] = { src: src, loaded: false };
        }

        return new Promise((resolve, _reject) => {
            // resolve if already loaded
            if (this._scripts[src].loaded && loadOnce) {
                resolve({ src: src, loaded: true });
            } else {
                // load script tag
                const scriptTag = $('<script/>')
                    .attr('type', 'text/javascript')
                    .attr('src', this._scripts[src].src);

                $(tag).append(scriptTag);

                this._scripts[src] = { src: src, loaded: true };
                resolve({ src: src, loaded: true });
            }
        });
    }

    reloadOnSessionChange() {
        window.addEventListener('storage', function(data) {
            if (data['key'] === 'token' && data['oldValue'] == null && data['newValue']) {
                document.location.reload();
            }
        });
    }
}

How to increase editor font size?

ok I reached to this solution by the help of two people who answered above, Mosh Feu and Suragch First open settings (ctrl+alt+s), second go to Editor->General->Fonts->Size.

Classes cannot be accessed from outside package

public SmartSaverCals(Context context)
{
    this.context= context;
}

add public to Your constructor.in my case problem solved

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You have two options for displaying the Map

  1. Use Maps Library for Android to render the Map
  2. Use Maps API V3 inside a web view

For showing local POIs around a Lat, Long use Places APIs

How can I implement rate limiting with Apache? (requests per second)

There are numerous way including web application firewalls but the easiest thing to implement if using an Apache mod.

One such mod I like to recommend is mod_qos. It's a free module that is veryf effective against certin DOS, Bruteforce and Slowloris type attacks. This will ease up your server load quite a bit.

It is very powerful.

The current release of the mod_qos module implements control mechanisms to manage:

  • The maximum number of concurrent requests to a location/resource (URL) or virtual host.

  • Limitation of the bandwidth such as the maximum allowed number of requests per second to an URL or the maximum/minimum of downloaded kbytes per second.

  • Limits the number of request events per second (special request conditions).

  • Limits the number of request events within a defined period of time.
  • It can also detect very important persons (VIP) which may access the web server without or with fewer restrictions.
  • Generic request line and header filter to deny unauthorized operations.

  • Request body data limitation and filtering (requires mod_parp).

  • Limits the number of request events for individual clients (IP).

  • Limitations on the TCP connection level, e.g., the maximum number of allowed connections from a single IP source address or dynamic keep-alive control.

  • Prefers known IP addresses when server runs out of free TCP connections.

This is a sample config of what you can use it for. There are hundreds of possible configurations to suit your needs. Visit the site for more info on controls.

Sample configuration:
# minimum request rate (bytes/sec at request reading):
QS_SrvRequestRate                                 120

# limits the connections for this virtual host:
QS_SrvMaxConn                                     800

# allows keep-alive support till the server reaches 600 connections:
QS_SrvMaxConnClose                                600

# allows max 50 connections from a single ip address:
QS_SrvMaxConnPerIP                                 50

# disables connection restrictions for certain clients:
QS_SrvMaxConnExcludeIP                    172.18.3.32
QS_SrvMaxConnExcludeIP                    192.168.10.

http://opensource.adnovum.ch/mod_qos/

Import and Export Excel - What is the best library?

I'm going to throw my hand in for flat csv files, if only because you've got the greatest control over the code. Just make sure that you read in the rows and process them one at a time (reading the document to the end and splitting will eat up all of your memory - same with writing, stream it out).

Yes, the user will have to save-as CSV in excel before you can process it, but perhaps this limitation can be overcome by training and providing clear instructions on the page?

Finally, when you export to the customer, if you set the mime type to text/csv, Excel is usually mapped to that type so it appears to the user to be 'an Excel file'.

Merging multiple PDFs using iTextSharp in c#.net

I found the answer:

Instead of the 2nd Method, add more files to the first array of input files.

public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
    // step 1: creation of a document-object
    Document document = new Document();
    //create newFileStream object which will be disposed at the end
    using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
    {
       // step 2: we create a writer that listens to the document
       PdfCopy writer = new PdfCopy(document, newFileStream );
       if (writer == null)
       {
           return;
       }

       // step 3: we open the document
       document.Open();

       foreach (string fileName in fileNames)
       {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(fileName);
           reader.ConsolidateNamedDestinations();

           // step 4: we add content
           for (int i = 1; i <= reader.NumberOfPages; i++)
           {                
               PdfImportedPage page = writer.GetImportedPage(reader, i);
               writer.AddPage(page);
           }

           PRAcroForm form = reader.AcroForm;
           if (form != null)
           {
               writer.CopyAcroForm(reader);
           }

           reader.Close();
       }

       // step 5: we close the document and writer
       writer.Close();
       document.Close();
   }//disposes the newFileStream object
}

Are Git forks actually Git clones?

In simplest terms,

When you say you are forking a repository, you are basically creating a copy of the original repository under your GitHub ID in your GitHub account.

and

When you say you are cloning a repository, you are creating a local copy of the original repository in your system (PC/laptop) directly without having a copy in your GitHub account.

How to catch an Exception from a thread

That's because exceptions are local to a thread, and your main thread doesn't actually see the run method. I suggest you read more about how threading works, but to quickly summarize: your call to start starts up a different thread, totally unrelated to your main thread. The call to join simply waits for it to be done. An exception that is thrown in a thread and never caught terminates it, which is why join returns on your main thread, but the exception itself is lost.

If you want to be aware of these uncaught exceptions you can try this:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("Caught " + e);
    }
});

More information about uncaught exception handling can be found here.

Jquery: Checking to see if div contains text, then action

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

CSS3 selector to find the 2nd div of the same class

And for people who are looking for a jQuery compatible answer:

$('.foo:eq(1)').css('color', 'red');

HTML:

<div>
  <div class="other"></div>
  <div class="foo"></div>
  <div class="foo">Find me</div>
  ...    

How do I print output in new line in PL/SQL?

You can concatenate the CR and LF:

chr(13)||chr(10)

(on windows)

or just:

chr(10)

(otherwise)

dbms_output.put_line('Hi,'||chr(13)||chr(10) ||'good' || chr(13)||chr(10)|| 'morning' ||chr(13)||chr(10) || 'friends');

Getting multiple values with scanf()

Passable for getting multiple values with scanf()

int r,m,v,i,e,k;

scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);

display html page with node.js

but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display.

That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.

You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391

Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js

ssl.SSLError: tlsv1 alert protocol version

I believe TLSV1_ALERT_PROTOCOL_VERSION is alerting you that the server doesn't want to talk TLS v1.0 to you. Try to specify TLS v1.2 only by sticking in these lines:

import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

# Create HTTPS connection
c = HTTPSConnection("0.0.0.0", context=context)

Note, you may need sufficiently new versions of Python (2.7.9+ perhaps?) and possibly OpenSSL (I have "OpenSSL 1.0.2k 26 Jan 2017" and the above seems to work, YMMV)

Xpath: select div that contains class AND whose specific child element contains text

You can change your second condition to check only the span element:

...and contains(div/span, 'someText')]

If the span isn't always inside another div you can also use

...and contains(.//span, 'someText')]

This searches for the span anywhere inside the div.

Convert dictionary to list collection in C#

If you want convert Keys:

List<string> listNumber = dicNumber.Keys.ToList();

else if you want convert Values:

List<string> listNumber = dicNumber.Values.ToList();

Deploy a project using Git push

You could conceivably set up a git hook that when say a commit is made to say the "stable" branch it will pull the changes and apply them to the PHP site. The big downside is you won't have much control if something goes wrong and it will add time to your testing - but you can get an idea of how much work will be involved when you merge say your trunk branch into the stable branch to know how many conflicts you may run into. It will be important to keep an eye on any files that are site specific (eg. configuration files) unless you solely intend to only run the one site.

Alternatively have you looked into pushing the change to the site instead?

For information on git hooks see the githooks documentation.

Print a variable in hexadecimal in Python

You mean you have a string of bytes in my_hex which you want to print out as hex numbers, right? E.g., let's take your example:

>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex')  # python 2 only
>>> print my_hex
Þ ­ ¾ ï

This construction only works on Python 2; but you could write the same string as a literal, in either Python 2 or Python 3, like this:

my_hex = "\xde\xad\xbe\xef"

So, to the answer. Here's one way to print the bytes as hex integers:

>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef

The comprehension breaks the string into bytes, ord() converts each byte to the corresponding integer, and hex() formats each integer in the from 0x##. Then we add spaces in between.

Bonus: If you use this method with unicode strings (or Python 3 strings), the comprehension will give you unicode characters (not bytes), and you'll get the appropriate hex values even if they're larger than two digits.

Addendum: Byte strings

In Python 3 it is more likely you'll want to do this with a byte string; in that case, the comprehension already returns ints, so you have to leave out the ord() part and simply call hex() on them:

>>> my_hex = b'\xde\xad\xbe\xef'
>>> print(" ".join(hex(n) for n in my_hex))
0xde 0xad 0xbe 0xef

How to Store Historical Data

Just wanted to add an option that I started using because I use Azure SQL and the multiple table thing was way too cumbersome for me. I added an insert/update/delete trigger on my table and then converted the before/after change to json using the "FOR JSON AUTO" feature.

 SET @beforeJson = (SELECT * FROM DELETED FOR JSON AUTO)
SET @afterJson = (SELECT * FROM INSERTED FOR JSON AUTO)

That returns a JSON representation fo the record before/after the change. I then store those values in a history table with a timestamp of when the change occurred (I also store the ID for current record of concern). Using the serialization process, I can control how data is backfilled in the case of changes to schema.

I learned about this from this link here

jQuery keypress() event not firing?

You have the word 'document' in a string. Change:

$('document').keypress(function(e){

to

$(document).keypress(function(e){

MySQL Error 1264: out of range value for column

tl;dr

Make sure your AUTO_INCREMENT is not out of range. In that case, set a new value for it with:

ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number

Explanation

AUTO_INCREMENT can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.

Solution

If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT to one bigger than the latest row's id. So if your latest row's id is 100 then:

ALTER TABLE table_name AUTO_INCREMENT=101

If you would like to check AUTO_INCREMENT's current value, use this command:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

How to get File Created Date and Modified Date

File.GetLastWriteTime Method

Returns the date and time the specified file or directory was last written to.

string path = @"c:\Temp\MyTest.txt";
DateTime dt = File.GetLastWriteTime(path);

For create time File.GetCreationTime Method

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
Console.WriteLine("file created: " + fileCreatedDate);

How to trigger the window resize event in JavaScript?

I wasn't actually able to get this to work with any of the above solutions. Once I bound the event with jQuery then it worked fine as below:

$(window).bind('resize', function () {
    resizeElements();
}).trigger('resize');

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

When I had this problem it was because I was trying to use an actual function in place of an anonymous function.

Incorrect:

$(document).on('change', "#MyId", MyFunction());

Correct

$(document).on('change', "#MyId", MyFunction);

or also correct and if you need to pass event object or other params.

$(document).on('change', "#MyId", function(e) { MyFunction(e); });

Android Fragments and animation

To animate the transition between fragments, or to animate the process of showing or hiding a fragment you use the Fragment Manager to create a Fragment Transaction.

Within each Fragment Transaction you can specify in and out animations that will be used for show and hide respectively (or both when replace is used).

The following code shows how you would replace a fragment by sliding out one fragment and sliding the other one in it's place.

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);

DetailsFragment newFragment = DetailsFragment.newInstance();

ft.replace(R.id.details_fragment_container, newFragment, "detailFragment");

// Start the animated transition.
ft.commit();

To achieve the same thing with hiding or showing a fragment you'd simply call ft.show or ft.hide, passing in the Fragment you wish to show or hide respectively.

For reference, the XML animation definitions would use the objectAnimator tag. An example of slide_in_left might look something like this:

<?xml version="1.0" encoding="utf-8"?>
<set>
  <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="x" 
    android:valueType="floatType"
    android:valueFrom="-1280"
    android:valueTo="0" 
    android:duration="500"/>
</set>

Javascript return number of days,hours,minutes,seconds between two dates

Here's in javascript: (For example, the future date is New Year's Day)

DEMO (updates every second)

var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();

var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);

hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API.
NSOperation and NSOperationQueue are Objective-C classes.
NSOperationQueue is objective C wrapper over GCD. If you are using NSOperation, then you are implicitly using Grand Central Dispatch.

GCD advantage over NSOperation:
i. implementation
For GCD implementation is very light-weight
NSOperationQueue is complex and heavy-weight

NSOperation advantages over GCD:

i. Control On Operation
you can Pause, Cancel, Resume an NSOperation

ii. Dependencies
you can set up a dependency between two NSOperations
operation will not started until all of its dependencies return true for finished.

iii. State of Operation
can monitor the state of an operation or operation queue. ready ,executing or finished

iv. Max Number of Operation
you can specify the maximum number of queued operations that can run simultaneously

When to Go for GCD or NSOperation
when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD

ref:
https://cocoacasts.com/choosing-between-nsoperation-and-grand-central-dispatch/ http://iosinfopot.blogspot.in/2015/08/nsthread-vs-gcd-vs-nsoperationqueue.html http://nshipster.com/nsoperation/

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Append a dictionary to a dictionary

You can do

orig.update(extra)

or, if you don't want orig to be modified, make a copy first:

dest = dict(orig)  # or orig.copy()
dest.update(extra)

Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}

How do you update a DateTime field in T-SQL?

Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.

e.g.

Given a table created like :

create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())

The following should always work :

update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic

The following will work :

SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1

However, this won't :

SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1  

This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .

The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.

More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

1920 is a generic error code that means the service didn't start. My hunch is this:

http://blog.iswix.com/2008/09/different-year-same-problem.html

To confirm, with the installer on the abort, retry, ignore, cancel dialog up... go into services.msc and set the username and password manually. If you get a message saying the user was granted logon as service right, try hitting retry on the MSI dialog and see if it starts.

It could also be missing dependencies or exceptions being thrown in your code.

Understanding Chrome network log "Stalled" state

https://developers.google.com/web/tools/chrome-devtools/network-performance/understanding-resource-timing

This comes from the official site of Chome-devtools and it helps. Here i quote:

  • Queuing If a request is queued it indicated that:
    • The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
    • The request was put on hold to wait for an unavailable TCP socket that's about to free up.
    • The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1. Time spent making disk cache entries (typically very quick.)
  • Stalled/Blocking Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.

Regex: Remove lines containing "help", etc

Search with a regular expression:

^.*(help).*$

Better techniques for trimming leading zeros in SQL Server?

Try this:

replace(ltrim(replace(@str, '0', ' ')), ' ', '0')

How to create a file name with the current date & time in Python?

now is a class method in the class datetime in the module datetime. So you need

datetime.datetime.now()

Or you can use a different import

from datetime import datetime

Done this way allows you to use datetime.now as per the code in the question.

How to use router.navigateByUrl and router.navigate in Angular

router.navigate vs router.navigateByUrl

router.navigate is just a convenience method that wraps router.navigateByUrl, it boils down to:

navigate(commands: any[], extras) {
    return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}

As mentioned in other answers router.navigateByUrl will only accept absolute URLs:

// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})

All the relative calculations are done by router.createUrlTree and router.navigate. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".." - go up, "path" - go down, {expand: true} - add query param, etc.. You can use it like this:

// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});

That {relativeTo: route} parameter is important as that's what router will use as the root for relative operations.

Get it through your component's constructor:

  // In my-awesome.component.ts:

  constructor(private route: ActivatedRoute, private router: Router) {}
  
  // Example call
  onNavigateClick() {
    // Navigates to a parent component
    this.router.navigate([..], { relativeTo: this.route })
  }

routerLink directive

Nicest thing about this directive is that it will retrieve the ActivatedRoute for you. Under the hood it's using already familiar:

router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });

Following variants will produce identical result:

[routerLink]="['../..']"

// if the string parameter is passed it will be wrapped into an array
routerLink="../.."

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

What is the role of the package-lock.json?

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.

{
    "name": "mobileapp",
    "version": "1.0.0",
    "lockfileVersion": 1,
    "requires": true,
    "dependencies": {
    "@angular-devkit/architect": {
      "version": "0.11.4",
      "resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
      "integrity": "sha512-2zi6S9tPlk52vyqNFg==",
      "dev": true,
      "requires": {
        "@angular-devkit/core": "7.1.4",
        "rxjs": "6.3.3"
      }
    },
}       

Access parent DataContext from DataTemplate

RelativeSource vs. ElementName

These two approaches can achieve the same result,

RelativeSource

Binding="{Binding Path=DataContext.MyBindingProperty, 
          RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

This method looks for a control of a type Window (in this example) in the visual tree and when it finds it you basically can access it's DataContext using the Path=DataContext..... The Pros about this method is that you don't need to be tied to a name and it's kind of dynamic, however, changes made to your visual tree can affect this method and possibly break it.

ElementName

Binding="{Binding Path=DataContext.MyBindingProperty, ElementName=MyMainWindow}

This method referes to a solid static Name so as long as your scope can see it, you're fine.You should be sticking to your naming convention not to break this method of course.The approach is qute simple and all you need is to specify a Name="..." for your Window/UserControl.

Although all three types (RelativeSource, Source, ElementName) are capable of doing the same thing, but according to the following MSDN article, each one better be used in their own area of specialty.

How to: Specify the Binding Source

Find the brief description of each plus a link to a more details one in the table on the bottom of the page.

Auto-loading lib files in Rails 4

Use config.to_prepare to load you monkey patches/extensions for every request in development mode.

config.to_prepare do |action_dispatcher|
 # More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
 Rails.logger.info "\n--- Loading extensions for #{self.class} "
 Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
   Rails.logger.info "Loading extension(s): #{entry}"
   require_dependency "#{entry}"
 end
 Rails.logger.info "--- Loaded extensions for #{self.class}\n"

end

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

Setting up and using Meld as your git difftool and mergetool

I prefer to setup meld as a separate command, like so:

git config --global alias.meld '!git difftool -t meld --dir-diff'

This makes it similar to the git-meld.pl script here: https://github.com/wmanley/git-meld

You can then just run

git meld

How can I view the shared preferences file using Android Studio?

Shared Preferences File path for Android Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/data/data/com.app.domain/shared_prefs/

SQL Server AS statement aliased column within WHERE statement

This would work on your edited question !

SELECT * FROM (SELECT <Column_List>,  
( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) )  
AS distance 
FROM poi_table) TMP
WHERE distance < 500; 

Best way to run scheduled tasks

If you own the server you should use the windows task scheduler. Use AT /? from the command line to see the options.

Otherwise, from a web based environment, you might have to do something nasty like set up a different machine to make requests to a certain page on a timed interval.

Summernote image upload

Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

Route::get('/your-route-to-editor', function () {
    return view('your-view');
});

Route::post('/your-route-to-processor', function (Request $request) {

       $this->validate($request, [
           'editordata' => 'required',
       ]);

       $data = $request->input('editordata');

       //loading the html data from the summernote editor and select the img tags from it
       $dom = new \DomDocument();
       $dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);    
       $images = $dom->getElementsByTagName('img');
       
       foreach($images as $k => $img){
           //for now src attribute contains image encrypted data in a nonsence string
           $data = $img->getAttribute('src');
           //getting the original file name that is in data-filename attribute of img
           $file_name = $img->getAttribute('data-filename');
           //extracting the original file name and extension
           $arr = explode('.', $file_name);
           $upload_base_directory = 'public/';

           $original_file_name='time()'.$k;
           $original_file_extension='png';

           if (sizeof($arr) ==  2) {
                $original_file_name = $arr[0];
                $original_file_extension = $arr[1];
           }
           else
           {
                //the file name contains extra . in itself
                $original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
                $original_file_extension = $arr[sizeof($arr)-1];
           }

           list($type, $data) = explode(';', $data);
           list(, $data)      = explode(',', $data);

           $data = base64_decode($data);

           $path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;

           //uploading the image to an actual file on the server and get the url to it to update the src attribute of images
           Storage::put($path, $data);

           $img->removeAttribute('src');       
           //you can remove the data-filename attribute here too if you want.
           $img->setAttribute('src', Storage::url($path));
           // data base stuff here :
           //saving the attachments path in an array
       }

       //updating the summernote WYSIWYG markdown output.
       $data = $dom->saveHTML();

       // data base stuff here :
       // save the post along with it attachments array
       return view('your-preview-page')->with(['data'=>$data]);

});

http://localhost/ not working on Windows 7. What's the problem?

Before installing Wamp, go to controlpanel=> Adminstrative tools => IIS Manager and turn off the IIS server. Install wamp and everything works fine. When IIS is on it also uses port 80. You can go through a lot of changing the ports and permissions for wamp but I have found this the quickest and easiest method of getting wamp to run successfully.

Check if String / Record exists in DataTable

Something like this

 string find = "item_manuf_id = 'some value'";
 DataRow[] foundRows = table.Select(find);

Cannot open Windows.h in Microsoft Visual Studio

I got this error fatal error lnk1104: cannot open file 'kernel32.lib'. this error is getting because there is no path in VC++ directories. To solve this problem

Open Visual Studio 2008

  1. go to Tools-options-Projects and Solutions-VC++ directories-*
  2. then at right corner select Library files
  3. here you need to add path of kernel132.lib

In my case It is C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib

Differences between strong and weak in Objective-C

It may be helpful to think about strong and weak references in terms of balloons.

A balloon will not fly away as long as at least one person is holding on to a string attached to it. The number of people holding strings is the retain count. When no one is holding on to a string, the ballon will fly away (dealloc). Many people can have strings to that same balloon. You can get/set properties and call methods on the referenced object with both strong and weak references.

A strong reference is like holding on to a string to that balloon. As long as you are holding on to a string attached to the balloon, it will not fly away.

A weak reference is like looking at the balloon. You can see it, access it's properties, call it's methods, but you have no string to that balloon. If everyone holding onto the string lets go, the balloon flies away, and you cannot access it anymore.

How to convert HH:mm:ss.SSS to milliseconds?

If you want to parse the format yourself you could do it easily with a regex such as

private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");

public static long dateParseRegExp(String period) {
    Matcher matcher = pattern.matcher(period);
    if (matcher.matches()) {
        return Long.parseLong(matcher.group(1)) * 3600000L 
            + Long.parseLong(matcher.group(2)) * 60000 
            + Long.parseLong(matcher.group(3)) * 1000 
            + Long.parseLong(matcher.group(4)); 
    } else {
        throw new IllegalArgumentException("Invalid format " + period);
    }
}

However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.

How do I choose the URL for my Spring Boot webapp?

The issue of changing the context path of a Spring application is handled very well in the post titled Spring Boot Change Context Path

Basically the post discusses multiple ways of realizing this viz.

  1. Java Config
  2. Command Line Arguments
  3. Java System Properties
  4. OS Environment Variables
  5. application.properties in Current Directory
  6. application.properties in the classpath (src/main/resources or the packaged jar file)

How do I make a C++ console program exit?

In main(), there is also:

return 0;

Error: Cannot pull with rebase: You have unstaged changes

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply stash@{0} or the simpler git stash pop

Number prime test in JavaScript

you can use below code in javascript for checking number is prime or not. It will reduce no of iteration and get the result fast.

function testPrime(num) {
        var isPrime = true;
        if (num >= 2) {
            if(num == 2 || num == 3){
               isPrime = true;
            }
            else if (num % 2 == 0) {
                isPrime = false;
            }
            else {
                for (i = 3; i <= Math.floor(Math.sqrt(num)); i += 2) {
                    if (num % i == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }
        }
        else {
            isPrime = false;
        }
        return isPrime;
    }

//testPrime(21) false

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

Your question "what are they" is already answered above.

As far as debugging (your second question) though, and in developing libraries where you want to check for special input values, you may find the following functions useful in Windows C++:

_isnan(), _isfinite(), and _fpclass()

On Linux/Unix you should find isnan(), isfinite(), isnormal(), isinf(), fpclassify() useful (and you may need to link with libm by using the compiler flag -lm).

how to check for datatype in node js- specifically for integer

You can check your numbers by checking their constructor.

var i = "5";

if( i.constructor !== Number )
{
 console.log('This is not number'));
}

SQL Stored Procedure: If variable is not null, update statement

Yet another approach is ISNULL().

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = ISNULL(@ABC, [ABC]),
    [ABCD] = ISNULL(@ABCD, [ABCD])

The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.

select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'

Android getText from EditText field

Sample code for How to get text from EditText.

Android Java Syntax

EditText text = (EditText)findViewById(R.id.vnosEmaila);
String value = text.getText().toString();

Kotlin Syntax

val text = findViewById<View>(R.id.vnosEmaila) as EditText
val value = text.text.toString()

C++ trying to swap values in a vector

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

What's the difference between OpenID and OAuth?

I am currently working on OAuth 2.0 and OpenID connect spec. So here is my understanding: Earlier they were:

  1. OpenID was proprietary implementation of Google allowing third party applications like for newspaper websites you can login using google and comment on an article and so on other usecases. So essentially, no password sharing to newspaper website. Let me put up a definition here, this approach in enterprise approach is called Federation. In Federation, You have a server where you authenticate and authorize (called IDP, Identity Provider) and generally the keeper of User credentials. the client application where you have business is called SP or Service Provider. If we go back to same newspaper website example then newspaper website is SP here and Google is IDP. In enterprise this problem was earlier solved using SAML. that time XML used to rule the software industry. So from webservices to configuration, everything used to go to XML so we have SAML, a complete Federation protocol
  2. OAuth: OAuth saw it's emergence as an standard looking at all these kind of proprietary approaches and so we had OAuth 1.o as standard but addressing only authorization. Not many people noticed but it kind of started picking up. Then we had OAuth 2.0 in 2012. CTOs, Architects really started paying attention as world is moving towards Cloud computing and with computing devices moving towards mobile and other such devices. OAuth kind of looked upon as solving major problem where software customers might give IDP Service to one company and have many services from different vendors like salesforce, SAP, etc. So integration here really looks like federation scenario bit one big problem, using SAML is costly so let's explore OAuth 2.o. Ohh, missed one important point that during this time, Google sensed that OAuth actually doesn't address Authentication, how will IDP give user data to SP (which is actually wonderfully addressed in SAML) and with other loose ends like:

    a. OAuth 2.o doesn't clearly say, how client registration will happen b. it doesn't mention anything about the interaction between SP (Resource Server) and client application (like Analytics Server providing data is Resource Server and application displaying that data is Client)

There are already wonderful answers given here technically, I thought of giving of giving brief evolution perspective

Download old version of package with NuGet

By using the Nuget Package Manager UI as mentioned above it helps to uninstall the nuget package first. I always have problems when going back on a nuget package version if I don't uninstall first. Some references are not cleaned properly. So I suggest the following workflow when installing an old nuget package through the Nuget Package Manager:

  1. Selected your nuget server / source
  2. Find and select the nuget package your want to install an older version
  3. Uninstall current version
  4. Click on the install drop-down > Select older version > Click Install

enter image description here

Good Luck :)

Node.js quick file server (static files over HTTP)

You can use the NPM serve package for this, if you don't need the NodeJS stuff it is a quick and easy to use tool:

1 - Install the package on your PC:

npm install -g serve

2 - Serve your static folder with serve <path> :

d:> serve d:\StaticSite

It will show you which port your static folder is being served, just navigate to the host like:

http://localhost:3000

Elegant way to read file into byte[] array in Java

Use a ByteArrayOutputStream. Here is the process:

  • Get an InputStream to read data
  • Create a ByteArrayOutputStream.
  • Copy all the InputStream into the OutputStream
  • Get your byte[] from the ByteArrayOutputStream using the toByteArray() method

Creating a directory in /sdcard fails

There are three things to consider here:

  1. Don't assume that the sd card is mounted at /sdcard (May be true in the default case, but better not to hard code.). You can get the location of sdcard by querying the system:

    Environment.getExternalStorageDirectory();
    
  2. You have to inform Android that your application needs to write to external storage by adding a uses-permission entry in the AndroidManifest.xml file:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  3. If this directory already exists, then mkdir is going to return false. So check for the existence of the directory, and then try creating it if it does not exist. In your component, use something like:

    File folder = new File(Environment.getExternalStorageDirectory() + "/map");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdir();
    }
    if (success) {
        // Do something on success
    } else {
        // Do something else on failure 
    }