Programs & Examples On #Turbo basic

Turbo Basic is a BASIC compiler developed by Borland for DOS in 1989. It includes a graphics API. It lives on as PowerBASIC.

What causes signal 'SIGILL'?

Make sure that all functions with non-void return type have a return statement.

While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

wordpress contactform7 textarea cols and rows change in smaller screens

Code will be As below.

[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->

[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->

[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->

[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->

For Details: https://contactform7.com/text-fields/

What is pipe() function in Angular

Don't get confused with the concepts of Angular and RxJS

We have pipes concept in Angular and pipe() function in RxJS.

1) Pipes in Angular: A pipe takes in data as input and transforms it to the desired output
https://angular.io/guide/pipes

2) pipe() function in RxJS: You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
https://angular.io/guide/rx-library (search for pipes in this URL, you can find the same)

So according to your question, you are referring pipe() function in RxJS

Auto number column in SharePoint list

Sharepoint Lists automatically have an column with "ID" which auto increments. You simply need to select this column from the "modify view" screen to view it.

Waiting until two async blocks are executed before starting another block

Answers above are all cool, but they all missed one thing. group executes tasks(blocks) in the thread where it entered when you use dispatch_group_enter/dispatch_group_leave.

- (IBAction)buttonAction:(id)sender {
      dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
      dispatch_async(demoQueue, ^{
        dispatch_group_t demoGroup = dispatch_group_create();
        for(int i = 0; i < 10; i++) {
          dispatch_group_enter(demoGroup);
          [self testMethod:i
                     block:^{
                       dispatch_group_leave(demoGroup);
                     }];
        }

        dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
          NSLog(@"All group tasks are done!");
        });
      });
    }

    - (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
      NSLog(@"Group task started...%ld", index);
      NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
      [NSThread sleepForTimeInterval:1.f];

      if(completeBlock) {
        completeBlock();
      }
    }

this runs in the created concurrent queue demoQueue. If i dont create any queue, it runs in main thread.

- (IBAction)buttonAction:(id)sender {
    dispatch_group_t demoGroup = dispatch_group_create();
    for(int i = 0; i < 10; i++) {
      dispatch_group_enter(demoGroup);
      [self testMethod:i
                 block:^{
                   dispatch_group_leave(demoGroup);
                 }];
    }

    dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
      NSLog(@"All group tasks are done!");
    });
    }

    - (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
      NSLog(@"Group task started...%ld", index);
      NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
      [NSThread sleepForTimeInterval:1.f];

      if(completeBlock) {
        completeBlock();
      }
    }

and there's a third way to make tasks executed in another thread:

- (IBAction)buttonAction:(id)sender {
      dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
      //  dispatch_async(demoQueue, ^{
      __weak ViewController* weakSelf = self;
      dispatch_group_t demoGroup = dispatch_group_create();
      for(int i = 0; i < 10; i++) {
        dispatch_group_enter(demoGroup);
        dispatch_async(demoQueue, ^{
          [weakSelf testMethod:i
                         block:^{
                           dispatch_group_leave(demoGroup);
                         }];
        });
      }

      dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
        NSLog(@"All group tasks are done!");
      });
      //  });
    }

Of course, as mentioned you can use dispatch_group_async to get what you want.

Python: How to remove empty lists from a list?

A few options:

filter(lambda x: len(x) > 0, list1)  # Doesn't work with number types
filter(None, list1)  # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)

sample session:

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>

How to use count and group by at the same select statement

With Oracle you could use analytic functions:

select town, count(town), sum(count(town)) over () total_count from user
group by town

Your other options is to use a subquery:

select town, count(town), (select count(town) from user) as total_count from user
group by town

Display array values in PHP

You can use implode to return your array with a string separator.

$withComma = implode(",", $array);

echo $withComma;
// Will display apple,banana,orange

How to get the last five characters of a string using Substring() in C#?

string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}

Get difference between 2 dates in JavaScript?

Here is a solution using moment.js:

var a = moment('7/11/2010','M/D/YYYY');
var b = moment('12/12/2010','M/D/YYYY');
var diffDays = b.diff(a, 'days');
alert(diffDays);

I used your original input values, but you didn't specify the format so I assumed the first value was July 11th. If it was intended to be November 7th, then adjust the format to D/M/YYYY instead.

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

Although you should have no problem running a 2005 instance of the database engine beside a 2008 instance, The tools are installed into a shared directory, so you can't have two versions of the tools installed. Fortunately, the 2008 tools are backwards-compatible. As we speak, I'm using SSMS 2008 and Profiler 2008 to manage my 2005 Express instances. Works great.

Before installing the 2008 tools, you need to remove any and all "shared" components from 2005. Try going to your Add/Remove programs control panel, find Microsoft SQL Server 2005, and click "Change." Then choose "Workstation Components" and remove everything there (this will not remove your database engine).

I believe the 2008 installer also has an option to upgrade shared components only. You might try that. Good luck!

Print Pdf in C#

I wrote and released a small Nuget Package which can be used to print a PDF file to a printerdriver. It can also print to a XPS file or PDF file. Here is a link to it.

How to convert a byte to its binary string representation

String byteToBinaryString(byte b){
    StringBuilder binaryStringBuilder = new StringBuilder();
    for(int i = 0; i < 8; i++)
        binaryStringBuilder.append(((0x80 >>> i) & b) == 0? '0':'1');
    return binaryStringBuilder.toString();
}

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

Padding is invalid and cannot be removed?

I had the same problem trying to port a Go program to C#. This means that a lot of data has already been encrypted with the Go program. This data must now be decrypted with C#.

The final solution was PaddingMode.None or rather PaddingMode.Zeros.

The cryptographic methods in Go:

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/sha1"
    "encoding/base64"
    "io/ioutil"
    "log"

    "golang.org/x/crypto/pbkdf2"
)

func decryptFile(filename string, saltBytes []byte, masterPassword []byte) (artifact string) {

    const (
        keyLength         int = 256
        rfc2898Iterations int = 6
    )

    var (
        encryptedBytesBase64 []byte // The encrypted bytes as base64 chars
        encryptedBytes       []byte // The encrypted bytes
    )

    // Load an encrypted file:
    if bytes, bytesErr := ioutil.ReadFile(filename); bytesErr != nil {
        log.Printf("[%s] There was an error while reading the encrypted file: %s\n", filename, bytesErr.Error())
        return
    } else {
        encryptedBytesBase64 = bytes
    }

    // Decode base64:
    decodedBytes := make([]byte, len(encryptedBytesBase64))
    if countDecoded, decodedErr := base64.StdEncoding.Decode(decodedBytes, encryptedBytesBase64); decodedErr != nil {
        log.Printf("[%s] An error occur while decoding base64 data: %s\n", filename, decodedErr.Error())
        return
    } else {
        encryptedBytes = decodedBytes[:countDecoded]
    }

    // Derive key and vector out of the master password and the salt cf. RFC 2898:
    keyVectorData := pbkdf2.Key(masterPassword, saltBytes, rfc2898Iterations, (keyLength/8)+aes.BlockSize, sha1.New)
    keyBytes := keyVectorData[:keyLength/8]
    vectorBytes := keyVectorData[keyLength/8:]

    // Create an AES cipher:
    if aesBlockDecrypter, aesErr := aes.NewCipher(keyBytes); aesErr != nil {
        log.Printf("[%s] Was not possible to create new AES cipher: %s\n", filename, aesErr.Error())
        return
    } else {

        // CBC mode always works in whole blocks.
        if len(encryptedBytes)%aes.BlockSize != 0 {
            log.Printf("[%s] The encrypted data's length is not a multiple of the block size.\n", filename)
            return
        }

        // Reserve memory for decrypted data. By definition (cf. AES-CBC), it must be the same lenght as the encrypted data:
        decryptedData := make([]byte, len(encryptedBytes))

        // Create the decrypter:
        aesDecrypter := cipher.NewCBCDecrypter(aesBlockDecrypter, vectorBytes)

        // Decrypt the data:
        aesDecrypter.CryptBlocks(decryptedData, encryptedBytes)

        // Cast the decrypted data to string:
        artifact = string(decryptedData)
    }

    return
}

... and ...

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/sha1"
    "encoding/base64"
    "github.com/twinj/uuid"
    "golang.org/x/crypto/pbkdf2"
    "io/ioutil"
    "log"
    "math"
    "os"
)

func encryptFile(filename, artifact string, masterPassword []byte) (status bool) {

    const (
        keyLength         int = 256
        rfc2898Iterations int = 6
    )

    status = false
    secretBytesDecrypted := []byte(artifact)

    // Create new salt:
    saltBytes := uuid.NewV4().Bytes()

    // Derive key and vector out of the master password and the salt cf. RFC 2898:
    keyVectorData := pbkdf2.Key(masterPassword, saltBytes, rfc2898Iterations, (keyLength/8)+aes.BlockSize, sha1.New)
    keyBytes := keyVectorData[:keyLength/8]
    vectorBytes := keyVectorData[keyLength/8:]

    // Create an AES cipher:
    if aesBlockEncrypter, aesErr := aes.NewCipher(keyBytes); aesErr != nil {
        log.Printf("[%s] Was not possible to create new AES cipher: %s\n", filename, aesErr.Error())
        return
    } else {

        // CBC mode always works in whole blocks.
        if len(secretBytesDecrypted)%aes.BlockSize != 0 {
            numberNecessaryBlocks := int(math.Ceil(float64(len(secretBytesDecrypted)) / float64(aes.BlockSize)))
            enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
            copy(enhanced, secretBytesDecrypted)
            secretBytesDecrypted = enhanced
        }

        // Reserve memory for encrypted data. By definition (cf. AES-CBC), it must be the same lenght as the plaintext data:
        encryptedData := make([]byte, len(secretBytesDecrypted))

        // Create the encrypter:
        aesEncrypter := cipher.NewCBCEncrypter(aesBlockEncrypter, vectorBytes)

        // Encrypt the data:
        aesEncrypter.CryptBlocks(encryptedData, secretBytesDecrypted)

        // Encode base64:
        encodedBytes := make([]byte, base64.StdEncoding.EncodedLen(len(encryptedData)))
        base64.StdEncoding.Encode(encodedBytes, encryptedData)

        // Allocate memory for the final file's content:
        fileContent := make([]byte, len(saltBytes))
        copy(fileContent, saltBytes)
        fileContent = append(fileContent, 10)
        fileContent = append(fileContent, encodedBytes...)

        // Write the data into a new file. This ensures, that at least the old version is healthy in case that the
        // computer hangs while writing out the file. After a successfully write operation, the old file could be
        // deleted and the new one could be renamed.
        if writeErr := ioutil.WriteFile(filename+"-update.txt", fileContent, 0644); writeErr != nil {
            log.Printf("[%s] Was not able to write out the updated file: %s\n", filename, writeErr.Error())
            return
        } else {
            if renameErr := os.Rename(filename+"-update.txt", filename); renameErr != nil {
                log.Printf("[%s] Was not able to rename the updated file: %s\n", fileContent, renameErr.Error())
            } else {
                status = true
                return
            }
        }

        return
    }
}

Now, decryption in C#:

public static string FromFile(string filename, byte[] saltBytes, string masterPassword)
{
    var iterations = 6;
    var keyLength = 256;
    var blockSize = 128;
    var result = string.Empty;
    var encryptedBytesBase64 = File.ReadAllBytes(filename);

    // bytes -> string:
    var encryptedBytesBase64String = System.Text.Encoding.UTF8.GetString(encryptedBytesBase64);

    // Decode base64:
    var encryptedBytes = Convert.FromBase64String(encryptedBytesBase64String);
    var keyVectorObj = new Rfc2898DeriveBytes(masterPassword, saltBytes.Length, iterations);
    keyVectorObj.Salt = saltBytes;
    Span<byte> keyVectorData = keyVectorObj.GetBytes(keyLength / 8 + blockSize / 8);
    var key = keyVectorData.Slice(0, keyLength / 8);
    var iv = keyVectorData.Slice(keyLength / 8);

    var aes = Aes.Create();
    aes.Padding = PaddingMode.Zeros;
    // or ... aes.Padding = PaddingMode.None;
    var decryptor = aes.CreateDecryptor(key.ToArray(), iv.ToArray());
    var decryptedString = string.Empty;

    using (var memoryStream = new MemoryStream(encryptedBytes))
    {
        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
        {
            using (var reader = new StreamReader(cryptoStream))
            {
                decryptedString = reader.ReadToEnd();
            }
        }
    }

    return result;
}

How can the issue with the padding be explained? Just before encryption the Go program checks the padding:

// CBC mode always works in whole blocks.
if len(secretBytesDecrypted)%aes.BlockSize != 0 {
    numberNecessaryBlocks := int(math.Ceil(float64(len(secretBytesDecrypted)) / float64(aes.BlockSize)))
    enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
    copy(enhanced, secretBytesDecrypted)
    secretBytesDecrypted = enhanced
}

The important part is this:

enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
copy(enhanced, secretBytesDecrypted)

A new array is created with an appropriate length, so that the length is a multiple of the block size. This new array is filled with zeros. The copy method then copies the existing data into it. It is ensured that the new array is larger than the existing data. Accordingly, there are zeros at the end of the array.

Thus, the C# code can use PaddingMode.Zeros. The alternative PaddingMode.None just ignores any padding, which also works. I hope this answer is helpful for anyone who has to port code from Go to C#, etc.

What does the keyword Set actually do in VBA?

In your case, it will produce an error. :-)

Set assigns an object reference. For all other assignments the (implicit, optional, and little-used) Let statement is correct:

Set object = New SomeObject
Set object = FunctionReturningAnObjectRef(SomeArgument)

Let i = 0
Let i = FunctionReturningAValue(SomeArgument)

' or, more commonly '

i = 0
i = FunctionReturningAValue(SomeArgument)

How to make a machine trust a self-signed Java application

I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..

Formatting code in Notepad++

The latest plugin is tidy2, which can be installed through Plugins>Plugin Manager>Show Plugin Manager.

I suggest editing config 1 and setting quote-marks: no, especially if you have script that makes use of quotes.

Also, tidying more than once can result in inserting ampersands the first time and then replacing the ampersands the second time. You may want to play with the config to get it to where you need it.

Artisan, creating tables in database

in laravel 5 first we need to create migration and then run the migration

Step 1.

php artisan make:migration create_users_table --create=users

Step 2.

php artisan migrate

Passing a local variable from one function to another

Adding to @pranay-rana's list:

Third way is:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

Whats wrong in this?

<form class="navbar-form navbar-right" method="post" action="login.php">
  <div class="form-group">
    <input type="email" name="email" class="form-control" placeholder="email">
    <input type="password" name="password" class="form-control" placeholder="password">
  </div>
  <input type="submit" name="submit" value="submit" class="btn btn-success">
</form>

login.php

if(isset($_POST['submit']) && !empty($_POST['submit'])) {
  // if (!logged_in()) 
  echo 'asodj';
}

CSS Font "Helvetica Neue"

Helvetica Neue is a paid font, so you shouldn't @font-face it, as you'd be freely distributing a copyrighted font. It's included in Mac systems but not in windows/linux ones, so yes, plenty of your users wont have it installed. Anyway, you can use 'Arial Narrow' as a windows substitute, which is it's windows equivalent.

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

how to use LIKE with column name

declare @LkeVal as Varchar(100)
declare @LkeSelect Varchar(100)

Set @LkeSelect = (select top 1 <column> from <table> where <column> = 'value')
Set @LkeVal = '%' + @LkeSelect

select * from <table2> where <column2> like(''+@LkeVal+'');

Open youtube video in Fancybox jquery

I started by using the answers here, but modified it to use YouTube's new iframe embedding...

$('a.more').on('click', function(event) {
    event.preventDefault();
    $.fancybox({
        'type' : 'iframe',
        // hide the related video suggestions and autoplay the video
        'href' : this.href.replace(new RegExp('watch\\?v=', 'i'), 'embed/') + '?rel=0&autoplay=1',
        'overlayShow' : true,
        'centerOnScroll' : true,
        'speedIn' : 100,
        'speedOut' : 50,
        'width' : 640,
        'height' : 480
    });
});

Nginx location priority

From the HTTP core module docs:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

Example from the documentation:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

If it's still confusing, here's a longer explanation.

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

explicit casting from super class to subclass

Elaborating the answer given by Michael Berry.

Dog d = (Dog)Animal; //Compiles but fails at runtime

Here you are saying to the compiler "Trust me. I know d is really referring to a Dog object" although it's not. Remember compiler is forced to trust us when we do a downcast.

The compiler only knows about the declared reference type. The JVM at runtime knows what the object really is.

So when the JVM at the runtime figures out that the Dog d is actually referring to an Animal and not a Dog object it says. Hey... you lied to the compiler and throws a big fat ClassCastException.

So if you are downcasting you should use instanceof test to avoid screwing up.

if (animal instanceof Dog) { Dog dog = (Dog) animal; }

Now a question comes to our mind. Why the hell compiler is allowing the downcast when eventually it is going to throw a java.lang.ClassCastException?

The answer is that all the compiler can do is verify that the two types are in the same inheritance tree, so depending on whatever code might have come before the downcast, it's possible that animal is of type dog.

The compiler must allow things that might possible work at runtime.

Consider the following code snipet:

public static void main(String[] args) 
{   
    Dog d = getMeAnAnimal();// ERROR: Type mismatch: cannot convert Animal to Dog
    Dog d = (Dog)getMeAnAnimal(); // Downcast works fine. No ClassCastException :)
    d.eat();

}

private static Animal getMeAnAnimal()
{
    Animal animal = new Dog();
    return animal;
}

However, if the compiler is sure that the cast would not possible work, compilation will fail. I.E. If you try to cast objects in different inheritance hierarchies

String s = (String)d; // ERROR : cannot cast for Dog to String

Unlike downcasting, upcasting works implicitly because when you upcast you are implicitly restricting the number of method you can invoke, as opposite to downcasting, which implies that later on, you might want to invoke a more specific method.

Dog d = new Dog(); Animal animal1 = d; // Works fine with no explicit cast Animal animal2 = (Animal) d; // Works fine with n explicit cast

Both of the above upcast will work fine without any exception because a Dog IS-A Animal, anithing an Animal can do, a dog can do. But it's not true vica-versa.

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery: is typically used when there is nothing returned from the Sql statements like insert ,update, delete operations.

cmd.ExcecuteNonQuery();

ExecuteScalar:

It will be used when Sql query returns single value.

Int b = cmd.ExcecuteScalar();

ExecuteReader

It will be used when Sql query or Stored Procedure returns multiple rows/columns

SqlDataReader dr = cmd.ExecuteReader();

for more information you can click here http://www.dotnetqueries.com/Article/148/-difference-between-executescalar-executereader-executenonquery

ReactJS - .JS vs .JSX

There is none when it comes to file extensions. Your bundler/transpiler/whatever takes care of resolving what type of file contents there is.

There are however some other considerations when deciding what to put into a .js or a .jsx file type. Since JSX isn't standard JavaScript one could argue that anything that is not "plain" JavaScript should go into its own extensions ie., .jsx for JSX and .ts for TypeScript for example.

There's a good discussion here available for read

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

Correct way to use StringBuilder in SQL

[[ There are some good answers here but I find that they still are lacking a bit of information. ]]

return (new StringBuilder("select id1, " + " id2 " + " from " + " table"))
     .toString();

So as you point out, the example you give is a simplistic but let's analyze it anyway. What happens here is the compiler actually does the + work here because "select id1, " + " id2 " + " from " + " table" are all constants. So this turns into:

return new StringBuilder("select id1,  id2  from  table").toString();

In this case, obviously, there is no point in using StringBuilder. You might as well do:

// the compiler combines these constant strings
return "select id1, " + " id2 " + " from " + " table";

However, even if you were appending any fields or other non-constants then the compiler would use an internal StringBuilder -- there's no need for you to define one:

// an internal StringBuilder is used here
return "select id1, " + fieldName + " from " + tableName;

Under the covers, this turns into code that is approximately equivalent to:

StringBuilder sb = new StringBuilder("select id1, ");
sb.append(fieldName).append(" from ").append(tableName);
return sb.toString();

Really the only time you need to use StringBuilder directly is when you have conditional code. For example, code that looks like the following is desperate for a StringBuilder:

// 1 StringBuilder used in this line
String query = "select id1, " + fieldName + " from " + tableName;
if (where != null) {
   // another StringBuilder used here
   query += ' ' + where;
}

The + in the first line uses one StringBuilder instance. Then the += uses another StringBuilder instance. It is more efficient to do:

// choose a good starting size to lower chances of reallocation
StringBuilder sb = new StringBuilder(64);
sb.append("select id1, ").append(fieldName).append(" from ").append(tableName);
// conditional code
if (where != null) {
   sb.append(' ').append(where);
}
return sb.toString();

Another time that I use a StringBuilder is when I'm building a string from a number of method calls. Then I can create methods that take a StringBuilder argument:

private void addWhere(StringBuilder sb) {
   if (where != null) {
      sb.append(' ').append(where);
   }
}

When you are using a StringBuilder, you should watch for any usage of + at the same time:

sb.append("select " + fieldName);

That + will cause another internal StringBuilder to be created. This should of course be:

sb.append("select ").append(fieldName);

Lastly, as @T.J.rowder points out, you should always make a guess at the size of the StringBuilder. This will save on the number of char[] objects created when growing the size of the internal buffer.

Batch File: ( was unexpected at this time

Oh, dear. A few little problems...

As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.

Two other matters of which you should be aware:

First, set/p will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:

 set "var="
 set /p var=

That is, of course, if you don't WANT enter to repeat the existing value.
Another useful form is

 set "var=default"
 set /p var=

or

 set "var=default"
 set /p "var=[%var%]"

(which prompts with the default value; !var! if in a block statement with delayedexpansion)

Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment (which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/

Thanks

How to use NSJSONSerialization

#import "homeViewController.h"
#import "detailViewController.h"

@interface homeViewController ()

@end

@implementation homeViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.frame = CGRectMake(0, 20, 320, 548);
    self.title=@"Jason Assignment";

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self clientServerCommunication];
}

-(void)clientServerCommunication
{
    NSURL *url = [NSURL URLWithString:@"http://182.72.122.106/iphonetest/getTheData.php"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
    if (connection)
    {
        webData = [[NSMutableData alloc]init];
    }
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];

    /*Third party API
     NSString *respStr = [[NSString alloc]initWithData:webData encoding:NSUTF8StringEncoding];
     SBJsonParser *objSBJson = [[SBJsonParser alloc]init];
     NSDictionary *responseDict = [objSBJson objectWithString:respStr]; */
    resultArray = [[NSArray alloc]initWithArray:[responseDict valueForKey:@"result"]];
    NSLog(@"resultArray: %@",resultArray);
    [self.tableView reloadData];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [resultArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    cell.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"name"];
    cell.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"designation"];

    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] valueForKey:@"image"]]];
cell.imageview.image = [UIImage imageWithData:imageData];

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here, for example:
     //Create the next view controller.
    detailViewController *detailViewController1 = [[detailViewController alloc]initWithNibName:@"detailViewController" bundle:nil];

 //detailViewController *detailViewController = [[detailViewController alloc] initWithNibName:@"detailViewController" bundle:nil];

 // Pass the selected object to the new view controller.

 // Push the view controller.
 detailViewController1.nextDict = [[NSDictionary alloc]initWithDictionary:[resultArray objectAtIndex:indexPath.row]];
 [self.navigationController pushViewController:detailViewController1 animated:YES];

    // Pass the selected object to the new view controller.

    // Push the view controller.
  //  [self.navigationController pushViewController:detailViewController animated:YES];
}



@end

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    empName.text=[nextDict valueForKey:@"name"];
    deptlbl.text=[nextDict valueForKey:@"department"];
    designationLbl.text=[nextDict valueForKey:@"designation"];
    idLbl.text=[nextDict valueForKey:@"id"];
    salaryLbl.text=[nextDict valueForKey:@"salary"];
    NSString *ImageURL = [nextDict valueForKey:@"image"];
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
    image.image = [UIImage imageWithData:imageData];
}

Change SVN repository URL

If you are using TortoiseSVN client then you can follow the below steps

Right-click in the source directory and then click on SVN Relocate Image#1

After that, you need to change the URL to what you want, click ok, it will be taking a few seconds.Image#2

Check if a class `active` exist on element with jquery

    if($('selector').hasClass('active')){ }

i think this will check if the selector hasClass active ...

How to control size of list-style-type disc in CSS?

I'm surprised that no one has mentioned the list-style-image property

ul {
    list-style-image: url('images/ico-list-bullet.png');
}

MySQL Join Where Not Exists

There are three possible ways to do that.

  1. Option

    SELECT  lt.* FROM    table_left lt
    LEFT JOIN
        table_right rt
    ON      rt.value = lt.value
    WHERE   rt.value IS NULL
    
  2. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   lt.value NOT IN
    (
    SELECT  value
    FROM    table_right rt
    )
    
  3. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   NOT EXISTS
    (
    SELECT  NULL
    FROM    table_right rt
    WHERE   rt.value = lt.value
    )
    

Convert NSDate to NSString

It's swift format :

func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {

    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: calndarIdentifier)
    formatter.dateFormat = dateFormat

    return formatter
}


//Usage
let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018

Regular expression for checking if capital letters are found consecutively in a string?

Edit: 2015-10-26: thanks for the upvotes - but take a look at tchrist's answer, especially if you develop for the web or something more "international".

Oren Trutners answer isn't quite right (see sample input of "RightHerE" which must be matched but isn't)

Here is the correct solution:

(?!^.*[A-Z]{2,}.*$)^[A-Za-z]*$

edit:

(?!^.*[A-Z]{2,}.*$)  // don't match the whole expression if there are two or more consecutive uppercase letters
^[A-Za-z]*$          // match uppercase and lowercase letters

/edit

the key for the solution is a negative lookahead see: http://www.regular-expressions.info/lookaround.html

How to declare a type as nullable in TypeScript?

You can just implement a user-defined type like the following:

type Nullable<T> = T | undefined | null;

var foo: Nullable<number> = 10; // ok
var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
var baz: Nullable<number> = null; // ok

var arr1: Nullable<Array<number>> = [1,2]; // ok
var obj: Nullable<Object> = {}; // ok

 // Type 'number[]' is not assignable to type 'string[]'. 
 // Type 'number' is not assignable to type 'string'
var arr2: Nullable<Array<string>> = [1,2];

Simple Java Client/Server Program

you can get ip of that computer runs server program from DHCP list in that router you connected to.

Cross origin requests are only supported for HTTP but it's not cross-domain

I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.

  1. Install express npm install express

  2. Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server

  3. Put something like the following in the server.js file and read about this on the express gihub site:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    // __dirname will use the current path from where you run this file 
    app.use(express.static(__dirname));
    app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
    
    app.listen(8000);
    console.log('Listening on port 8000');
    
  4. After you've saved server.js, you can run the server using:

node server.js

  1. Go to http://localhost:8000/FILENAME and you should see the HTML file you were trying to load

Default value of 'boolean' and 'Boolean' in Java

The default value for a Boolean (object) is null.
The default value for a boolean (primitive) is false.

How to debug "ImagePullBackOff"?

On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.

In my case, I had :

Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
 rpc error: code = Unknown desc = error pulling image configuration: unknown blob

It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.

When is JavaScript synchronous?

"I have been under the impression for that JavaScript was always asynchronous"

You can use JavaScript in a synchronous way, or an asynchronous way. In fact JavaScript has really good asynchronous support. For example I might have code that requires a database request. I can then run other code, not dependent on that request, while I wait for that request to complete. This asynchronous coding is supported with promises, async/await, etc. But if you don't need a nice way to handle long waits then just use JS synchronously.

What do we mean by 'asynchronous'. Well it does not mean multi-threaded, but rather describes a non-dependent relationship. Check out this image from this popular answer:

         A-Start ------------------------------------------ A-End   
           | B-Start -----------------------------------------|--- B-End   
           |    |      C-Start ------------------- C-End      |      |   
           |    |       |                           |         |      |
           V    V       V                           V         V      V      
1 thread->|<-A-|<--B---|<-C-|-A-|-C-|--A--|-B-|--C-->|---A---->|--B-->| 

We see that a single threaded application can have async behavior. The work in function A is not dependent on function B completing, and so while function A began before function B, function A is able to complete at a later time and on the same thread.

So, just because JavaScript executes one command at a time, on a single thread, it does not then follow that JavaScript can only be used as a synchronous language.

"Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous"

I'm wondering if this is the heart of your question. I take it that you mean how do you know if some code you are calling is async or sync. That is, will the rest of your code run off and do something while you wait for some result? Your first check should be the documentation for whichever library you are using. Node methods, for example, have clear names like readFileSync. If the documentation is no good there is a lot of help here on SO. EG:

How to know if a function is async?

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Android XXHDPI resources

The resolution is 480 dpi, the launcher icon is 144*144px all is scaled 3x respect to mdpi (so called "base", "baseline" or "normal") sizes.

Reverting to a specific commit based on commit id with Git?

If you want to force the issue, you can do:

git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07

send you back to how your git clone looked like at the time of the checkin

How many significant digits do floats and doubles have in java?

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

Override console.log(); for production

I would recommend using: https://github.com/sunnykgupta/jsLogger

Features:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.

Is open for modifications and will be updated whenever new suggestions come up.

Disclaimer: I am the author of the plugin.

Change Circle color of radio button

I made it short way like this (Working on API pre 21 as well as post 21)

Your radio button in xml should look like this

  <RadioButton android:id="@+id/radioid"                    
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"                 
                android:button="@drawable/radiodraw" />

in radiodraw.xml

  <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">    
      <item android:state_checked="false" >
          <shape  android:shape="oval" >
              <stroke android:width="1dp" android:color="#000"/>
              <size android:width="30dp" android:height="30dp"/>
              <solid android:color="@android:color/transparent"/>
          </shape>
      </item>
      <item android:state_checked="true">
          <layer-list>
              <item>
                  <shape android:shape="oval">
                      <stroke android:width="1dp" android:color="#000"/>
                      <size android:width="30dp" android:height="30dp"/>
                      <solid android:color="@android:color/transparent"/>
                  </shape>
              </item>
              <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp">
                  <shape android:shape="oval">
                      <solid android:width="1dp" android:color="#000"/>
                      <size android:width="10dp" android:height="10dp"/>
                  </shape>
              </item>
          </layer-list>
      </item>
  </selector>

have to add color transparent for drawing the unchecked status ;else it draw solid black oval.

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

mysql query: SELECT DISTINCT column1, GROUP BY column2

Somehow your requirement sounds a bit contradictory ..

group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

What do you think should happen if two people (names) worked from the same IP within the time period specified?


Did you try this?

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday AND time <$today 
GROUP BY name,ip

How to check whether an object is a date?

For all types I cooked up an Object prototype function. It may be of use to you

Object.prototype.typof = function(chkType){
      var inp        = String(this.constructor),
          customObj  = (inp.split(/\({1}/))[0].replace(/^\n/,'').substr(9),
          regularObj = Object.prototype.toString.apply(this),
          thisType   = regularObj.toLowerCase()
                        .match(new RegExp(customObj.toLowerCase()))
                       ? regularObj : '[object '+customObj+']';
     return chkType
            ? thisType.toLowerCase().match(chkType.toLowerCase()) 
               ? true : false
            : thisType;
}

Now you can check any type like this:

var myDate     = new Date().toString(),
    myRealDate = new Date();
if (myRealDate.typof('Date')) { /* do things */ }
alert( myDate.typof() ); //=> String

[Edit march 2013] based on progressing insight this is a better method:

Object.prototype.is = function() {
        var test = arguments.length ? [].slice.call(arguments) : null
           ,self = this.constructor;
        return test ? !!(test.filter(function(a){return a === self}).length)
               : (this.constructor.name ||
                  (String(self).match ( /^function\s*([^\s(]+)/im)
                    || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Some = function(){ /* ... */}
   ,Other = function(){ /* ... */}
   ,some = new Some;
2..is(String,Function,RegExp);        //=> false
2..is(String,Function,Number,RegExp); //=> true
'hello'.is(String);                   //=> true
'hello'.is();                         //-> String
/[a-z]/i.is();                        //-> RegExp
some.is();                            //=> 'ANONYMOUS_CONSTRUCTOR'
some.is(Other);                       //=> false
some.is(Some);                        //=> true
// note: you can't use this for NaN (NaN === Number)
(+'ab2').is(Number);                 //=> true

Making a UITableView scroll when text field is selected

Combining and filling in the blanks from several answers (in particular Ortwin Gentz, user 98013) and another post, this will work out of the box for SDK 4.3 on an iPad in Portrait or Landscape mode:

@implementation UIView (FindFirstResponder)
- (UIResponder *)findFirstResponder
{
  if (self.isFirstResponder) {        
    return self;     
  }

  for (UIView *subView in self.subviews) {
    UIResponder *firstResponder = [subView findFirstResponder];
    if (firstResponder != nil) {
      return firstResponder;
    }
  }

  return nil;
}
@end

@implementation MyViewController

- (UIResponder *)currentFirstResponder {
  return [self.view findFirstResponder];
}

- (IBAction)editingEnded:sender {
  [sender resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  [textField resignFirstResponder];
  return NO;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
  UITableViewCell *cell = (UITableViewCell*) [[textField superview] superview];
  [_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardWillShow:(NSNotification*)notification {
  if ([self currentFirstResponder] != nil) {
    NSDictionary* userInfo = [notification userInfo];

    // we don't use SDK constants here to be universally compatible with all SDKs = 3.0
    NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
    if (!keyboardFrameValue) {
      keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
    }

    // Reduce the tableView height by the part of the keyboard that actually covers the tableView
    CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
    CGRect viewRectAbsolute = [_tableView convertRect:_tableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
    CGRect frame = _tableView.frame;
    if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
      windowRect = CGRectMake(windowRect.origin.y, windowRect.origin.x, windowRect.size.height, windowRect.size.width);
      viewRectAbsolute = CGRectMake(viewRectAbsolute.origin.y, viewRectAbsolute.origin.x, viewRectAbsolute.size.height, viewRectAbsolute.size.width);
    }
    frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
    _tableView.frame = frame;
    [UIView commitAnimations];

    UITableViewCell *textFieldCell = (id)((UITextField *)self.currentFirstResponder).superview.superview;
    NSIndexPath *textFieldIndexPath = [_tableView indexPathForCell:textFieldCell];

    // iOS 3 sends hide and show notifications right after each other
    // when switching between textFields, so cancel -scrollToOldPosition requests
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    _topmostRowBeforeKeyboardWasShown = [[_tableView indexPathsForVisibleRows] objectAtIndex:0];
    [_tableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  }
}

- (void) scrollToOldPosition {
  [_tableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification {
  if ([self currentFirstResponder] != nil) {

    NSDictionary* userInfo = [notification userInfo];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
    _tableView.frame = self.view.bounds;
    [UIView commitAnimations];

    [self performSelector:@selector(scrollToOldPosition) withObject:nil afterDelay:0.1];
  }
}   

@end

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I had a similar issue where the tests where not being discovered. I had the correct version of NUnit, versions matched up between NUnit and adapter, and the tests where tagged correctly. I was running VS 2017 Enterprise not as an administrator. After starting VS as administrator the tests appeared.

Python re.sub replace with matched content

Simply use \1 instead of $1:

In [1]: import re

In [2]: method = 'images/:id/huge'

In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'

Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I agree with noa -- if you need to have multiple versions of node, io.js then brew is not the appropriate solution.

You can help beta-test io.js support in nvm: https://github.com/creationix/nvm/pull/616

If you just want io.js and are not switching versions, then you can install the binary distribution of io.js from https://iojs.org/dist/v1.0.2/iojs-v1.0.2-darwin-x64.tar.gz ; that includes npm and you will not need nvm if you are not switching versions.

Remember to update npm after installing: sudo npm install -g npm@latest

How do I automatically set the $DISPLAY variable for my current session?

I'm guessing here, based on issues I've had in the past which I did solve:

  • you're connecting to a vnc server on machine B, displaying it using a VNC client on machine A
  • you're launching a console (xterm or equivalent) on machine B and using that to connect to machine C
  • you want to launch an X-based application on machine C, having it display to the VNC server on machine B, so you can see it on machine A.

I ended up with two solutions. My original solution was based on using rsh. Since then, most of our servers have had ssh installed, which has made this easier.

Using rsh, I put together a table of machines vs OS vs custom options which would guide this process in perl. Bourne shell wasn't sufficient, and we don't have bash on Sun or HP machines (and didn't have bash on AIX at the time - AIX 5L wasn't out yet). Korn shell wasn't much of an option, either, since most of our Linux boxes don't have pdksh installed. But, if you don't face these limitations, you can implement the idea in ksh or bash, I think.

Anyway, I would basically run 'rsh $machine -l $user "$cmd"' where $machine, of course, was the machine I was logging in to, $user, similarly obvious (though when I was going in as "root" this had some variance as we have multiple roots on some machines for reasons I don't fully understand), and $cmd was basically "DISPLAY=$DISPLAY xterm", though if I were launching konsole, for example, $cmd would be "konsole --display=$DISPLAY". Since $DISPLAY was being evaluated locally (where it's set properly), and not being passed literally across rsh, the display would always be set correctly.

I also had to make sure that no one did anything silly like reset DISPLAY if it was already set.

Now, I just use ssh, make sure that X11Forwarding is set to yes on the server (sshd_config), and then I can just ssh to the machine, let X commands go across the wire encrypted, and it'll always go back to the right place.

Consider marking event handler as 'passive' to make the page more responsive

This hides the warning message:

jQuery.event.special.touchstart = {
  setup: function( _, ns, handle ) {
      this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
  }
};

java - path to trustStore - set property doesn't work?

Alternatively, if using javax.net.ssl.trustStore for specifying the location of your truststore does not work ( as it did in my case for two way authentication ), you can also use SSLContextBuilder as shown in the example below. This example also includes how to create a httpclient as well to show how the SSL builder would work.

SSLContextBuilder sslcontextbuilder = SSLContexts.custom();

sslcontextbuilder.loadTrustMaterial(
            new File("C:\\path to\\truststore.jks"), //path to jks file
            "password".toCharArray(), //enters in the truststore password for use
            new TrustSelfSignedStrategy() //will trust own CA and all self-signed certs
            );

SSLContext sslcontext = sslcontextbuilder.build(); //load trust store

SSLConnectionSocketFactory sslsockfac = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());

CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsockfac).build(); //sets up a httpclient for use with ssl socket factory 



try { 
        HttpGet httpget = new HttpGet("https://localhost:8443"); //I had a tomcat server running on localhost which required the client to have their trust cert

        System.out.println("Executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

How to download files using axios

        axios.get(
            '/app/export'
        ).then(response => {    
            const url = window.URL.createObjectURL(new Blob([response]));
            const link = document.createElement('a');
            link.href = url;
            const fileName = `${+ new Date()}.csv`// whatever your file name .
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            link.remove();// you need to remove that elelment which is created before.
})

"Please provide a valid cache path" error in laravel

/path/to/laravel/storage/framework/

sessions views cache

Above is working solution

Could not open a connection to your authentication agent

This worked for me.

In the CMD window, type the following command:

cd path-to-Git/bin # (for example,cd C:\Program Files\Git\bin)
bash
exec ssh-agent bash
ssh-add path/to/.ssh/id_rsa

Handling Dialogs in WPF with MVVM

You should use a mediator for this. Mediator is a common design pattern also known as Messenger in some of its implementations. It's a paradigm of type Register/Notify and enables your ViewModel and Views to communicate through a low-coupled messaging mecanism.

You should check out the google WPF Disciples group, and just search for Mediator. You will be much happy with the answers...

You can however start with this:

http://joshsmithonwpf.wordpress.com/2009/04/06/a-mediator-prototype-for-wpf-apps/

Enjoy !

Edit: you can see the answer to this problem with the MVVM Light Toolkit here:

http://mvvmlight.codeplex.com/Thread/View.aspx?ThreadId=209338

RESTful Authentication via Spring

Why don't you start using OAuth with JSON WebTokens

http://projects.spring.io/spring-security-oauth/

OAuth2 is an standardized authorization protocol/framework. As per Official OAuth2 Specification:

You can find more info here

SQL DELETE with INNER JOIN

Add .* to s in your first line.

Try:

DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

How to make remote REST call inside Node.js? any CURL?

To use latest Async/Await features

https://www.npmjs.com/package/request-promise-native

npm install --save request
npm install --save request-promise-native

//code

async function getData (){
    try{
          var rp = require ('request-promise-native');
          var options = {
          uri:'https://reqres.in/api/users/2',
          json:true
        };

        var response = await rp(options);
        return response;
    }catch(error){
        throw error;
    }        
}

try{
    console.log(getData());
}catch(error){
    console.log(error);
}

How to return history of validation loss in Keras

Another option is CSVLogger: https://keras.io/callbacks/#csvlogger. It creates a csv file appending the result of each epoch. Even if you interrupt training, you get to see how it evolved.

Why emulator is very slow in Android Studio?

Check this list:

  1. install Intel HAXM
  2. just use x86 AVD
  3. use small size screen

Resolve host name to an ip address

Windows XP has the Windows Firewall which can interfere with network traffic if not configured properly. You can turn off the Windows Firewall, if you have administrator privileges, by accessing the Windows Firewall applet through the Control Panel. If your application works with the Windows Firewall turned off then the problem is probably due to the settings of the firewall.

We have an application which runs on multiple PCs communicating using UDP/IP and we have been doing experiments so that the application can run on a PC with a user who does not have administrator privileges. In order for our application to communicate between multiple PCs we have had to use an administrator account to modify the Windows Firewall settings.

In our application, one PC is designated as the server and the others are clients in a server/client group and there may be several groups on the same subnet.

The first change was to use the functionality of the Exceptions tab of the Windows Firewall applet to create an exception for the port that we use for communication.

We are using host name lookup so that the clients can locate their assigned server by using the computer name which is composed of a mnemonic prefix with a dash followed by an assigned terminal number (for instance SERVER100-1). This allows several servers with their assigned clients to coexist on the same subnet. The client uses its prefix to generate the computer name for the assigned server and to then use host name lookup to discover the IP address of the assigned server.

What we found is that the host name lookup using the computer name (assigned through the Computer Name tab of the System Properties dialog) would not work unless the server PC's Windows Firewall had the File and Printer Sharing Service port enabled.

So we had to make two changes: (1) setup an exception for the port we used for communication and (2) enable File and Printer Service in the Exceptions tab to allow for the host name lookup.

** EDIT **

You may also find this Microsoft Knowledge Base article on helpful on Windows XP networking.

And see this article on NETBIOS name resolution in Windows.

Is it possible to Turn page programmatically in UIPageViewController?

- (void)moveToPage {

    NSUInteger pageIndex = ((ContentViewController *) [self.pageViewController.viewControllers objectAtIndex:0]).pageIndex;

    pageIndex++;

    ContentViewController *viewController = [self viewControllerAtIndex:pageIndex];

if (viewController == nil) {
        return;
    }
    [self.pageViewController setViewControllers:@[viewController] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];

}

//now call this method

[self moveToPage];

I hope it works :)

Cannot catch toolbar home button click event

I think the correct solution with support library 21 is the following

// action_bar is def resource of appcompat; 
// if you have not provided your own toolbar I mean  
Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
if (toolbar != null) {
    // change home icon if you wish
    toolbar.setLogo(this.getResValues().homeIconDrawable());
    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //catch here title and home icon click                          
        }                       
    });                 
}

Is there a good Valgrind substitute for Windows?

Definitely Purify! I've used that to analyze some massive code bases (>3,000 kSLOC) and found it to be excellent.

You might like to look at this list at Wikipedia.

By the way, I've found memwatch to be useful. Thanks Johan!

Running a simple shell script as a cronjob

It should run properly at cron also. Please check below things.

1- You are editing proper file to set cron.

2- You have given proper permission(execute permission) to script mean your script is executable.

Python basics printing 1 to 100

because if you change your code with

def gukan(count):
    while count!=100:
      print(count)
      count=count+3;
gukan(0)

count reaches 99 and then, at the next iteration 102.

So

count != 100

never evaluates true and the loop continues forever

If you want to count up to 100 you may use

def gukan(count):
    while count <= 100:
      print(count)
      count=count+3;
gukan(0)

or (if you want 100 always printed)

def gukan(count):
    while count <= 100:
      print(count)
      count=count+3;
      if count > 100:
          count = 100
gukan(0)

python-dev installation error: ImportError: No module named apt_pkg

Please review the following documentation. It will definitely solve the problem. http://www.programmersought.com/article/55001874709/

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

I used the content+wrapper approach ... but I did something different than mentioned so far: I made sure that my wrapper's boundaries did NOT line up with the content's boundaries in the direction that I wanted to be visible.

Important NOTE: It was easy enough to get the content+wrapper, same-bounds approach to work on one browser or another depending on various css combinations of position, overflow-*, etc ... but I never could use that approach to get them all correct (Edge, Chrome, Safari, ...).

But when I had something like:

  <div id="hack_wrapper" // created solely for this purpose
       style="position:absolute; width:100%; height:100%; overflow-x:hidden;">
      <div id="content_wrapper"
           style="position:absolute; width:100%; height:15%; overflow:visible;">         
          ... content with too-much horizontal content ... 
      </div>
  </div>

... all browsers were happy.

JUnit Eclipse Plugin?

It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").

ORA-00054: resource busy and acquire with NOWAIT specified

Step 1:

select object_name, s.sid, s.serial#, p.spid 
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;

Step 2:

alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1

More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php

Facebook share button and custom text

We use something like this [use in one line]:

<a title="send to Facebook" 
  href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
  target="_blank">
  <span>
    <img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook 
  </span>
</a>

Press Enter to move to next control

private void txt_invoice_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_date.Focus();
    }

    private void txt_date_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_patientname.Focus();
    }

}

Get timezone from users browser using moment(timezone).js

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true

Read a variable in bash with a default value

In Bash 4:

name="Ricardo"
read -e -i "$name" -p "Please enter your name: " input
name="${input:-$name}"

This displays the name after the prompt like this:

Please enter your name: Ricardo

with the cursor at the end of the name and allows the user to edit it. The last line is optional and forces the name to be the original default if the user erases the input or default (submitting a null).

How to format numbers by prepending 0 to single-digit numbers?

My Example like this

         var n =9;
         var checkval=('00'+n).slice(-2);
         console.log(checkval)

and the output is 09

How to enter command with password for git pull?

Using the credentials helper command-line option:

git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin

How to draw circle by canvas in Android?

Here is example to draw stroke circle canvas

val paint = Paint().apply {
    color = Color.RED
    style = Paint.Style.STROKE
    strokeWidth = 10f
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Example to draw solid circle canvas

val paint = Paint().apply {
    color = Color.RED
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Hope it help

How can I compare two dates in PHP?

If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:

$date = $row->expireDate;

$date->add(new DateInterval('PT24H')); // adds 24 hours

$now = new \DateTime();

if($now < $date) { /* expired after 24 hours */ }

But in your case you could do the comparison just as the following:

$today = new DateTime('Y-m-d');

$date = $row->expireDate;

if($today < $date) { /* do something */ }

Running npm command within Visual Studio Code

Install

  • Ctrl+P, write ext install npm script runner
  • Restart VS Code

Use (two ways)

  • Ctrl+R Shift+R
  • Ctrl+P, write >npm, select run script, select the desired task

Update: Since version 1.3 Visual Studio Code has integrated terminal. To open it, use any of these methods:

  • Use the Ctrl+` keyboard shortcut.
  • Use the View | Toggle Integrated Terminal menu command.
  • From the Command Palette (Ctrl+Shift+P), use the View:Toggle Integrated Terminal command.

Clearing NSUserDefaults

You can remove the application's persistent domain like this:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

In Swift 3 and later:

if let bundleID = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundleID)
}

This is similar to the answer by @samvermette but is a little bit cleaner IMO.

Why is Java's SimpleDateFormat not thread-safe?

Here is a code example that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I my case the problem was a residual dump file in the database directory. That file was probably generated during a backup script test I had been working on. Once I manually deleted the file I could then drop the database.

Email address validation using ASP.NET MVC data type attributes

[RegularExpression(@"^[A-Za-z0-9]+@([a-zA-Z]+\\.)+[a-zA-Z]{2,6}]&")]

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

Simple JavaScript problem: onClick confirm not preventing default action

I use this, works like a charm. No need to have any functions, just inline with your link(s)

onclick="javascript:return confirm('Are you sure you want to delete this comment?')"

Search for all occurrences of a string in a mysql database

I can't remember where I came across this script, but I've been using it with XCloner to move my WP multisites.

<?php

    // Setup the associative array for replacing the old string with new string
    $replace_array = array( 'FIND' => 'REPLACE', 'FIND' => 'REPLACE');

    $mysql_link = mysql_connect( 'localhost', 'USERNAME', 'PASSWORD' );
    if( ! $mysql_link) {
        die( 'Could not connect: ' . mysql_error() );
    }

    $mysql_db = mysql_select_db( 'DATABASE', $mysql_link );
    if(! $mysql_db ) {
        die( 'Can\'t select database: ' . mysql_error() );
    }

    // Traverse all tables
    $tables_query = 'SHOW TABLES';
    $tables_result = mysql_query( $tables_query );
    while( $tables_rows = mysql_fetch_row( $tables_result ) ) {
        foreach( $tables_rows as $table ) {

            // Traverse all columns
            $columns_query = 'SHOW COLUMNS FROM ' . $table;
            $columns_result = mysql_query( $columns_query );
            while( $columns_row = mysql_fetch_assoc( $columns_result ) ) {

                $column = $columns_row['Field'];
                $type = $columns_row['Type'];

                // Process only text-based columns
                if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
                    // Process all replacements for the specific column                    
                    foreach( $replace_array as $old_string => $new_string ) {
                        $replace_query = 'UPDATE ' . $table . 
                            ' SET ' .  $column . ' = REPLACE(' . $column . 
                            ', \'' . $old_string . '\', \'' . $new_string . '\')';
                        mysql_query( $replace_query );
                    }
                }
            }
        }
    }

    mysql_free_result( $columns_result );
    mysql_free_result( $tables_result );
    mysql_close( $mysql_link );

    echo 'Done!';

?>

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

What is dynamic programming?

Dynamic programming is a technique for solving problems with overlapping sub problems. A dynamic programming algorithm solves every sub problem just once and then Saves its answer in a table (array). Avoiding the work of re-computing the answer every time the sub problem is encountered. The underlying idea of dynamic programming is: Avoid calculating the same stuff twice, usually by keeping a table of known results of sub problems.

The seven steps in the development of a dynamic programming algorithm are as follows:

  1. Establish a recursive property that gives the solution to an instance of the problem.
  2. Develop a recursive algorithm as per recursive property
  3. See if same instance of the problem is being solved again an again in recursive calls
  4. Develop a memoized recursive algorithm
  5. See the pattern in storing the data in the memory
  6. Convert the memoized recursive algorithm into iterative algorithm
  7. Optimize the iterative algorithm by using the storage as required (storage optimization)

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

A bit late, and not a complete solution either, but for everyone who gets hit by this error without any obvious reason (having all the references defined, etc.) This thread put me on the correct track though. The issue seems to originate from some caching related bug in MS Office VBA Editor.

After making some changes to a project including about 40 forms with code modules plus 40 classes and some global modules in MS Access 2016 the compilation failed.

Commenting out code was obviously not an option, nor did exporting and re-importing all the 80+ files seem reasonable. Concentrating on what had recently been changed, my suspicions focused on removal of one class module.

Having no better ideas I re-cereated an empty class module with the same name that had previously been removed. And voliá the error was gone! It was even possible to remove the unused class module again without the error reappearing, until any changes were saved to a form module which previously had contained a WithEvents declaration involving the now removed class.

Not completely sure if WithEvents declaration really is what triggers the error even after the declaration has been removed. And no clues how to actually find out (without having information about the development history) which Form might be the culprit...

But what finally solved the issue was:

  1. In VBE - Copy all code from Form code module
  2. In Access open Form in Design view and set Has Module property to No
  3. Save the project (this removes any code associated with Form)
  4. (Not sure if need to close and re-open Access, but I did it)
  5. Open Form in Design view and set Has Module property back to Yes
  6. In VBE paste back the copied out module code
  7. Save

Position absolute and overflow hidden

You just make divs like this:

<div style="width:100px; height: 100px; border:1px solid; overflow:hidden; ">
    <br/>
    <div style="position:inherit; width: 200px; height:200px; background:yellow;">
        <br/>
        <div style="position:absolute; width: 500px; height:50px; background:Pink; z-index: 99;">
            <br/>
        </div>
    </div>
</div>

I hope this code will help you :)

Programmatically get the version number of a DLL

Here's a nice way using a bit of reflection to get a version of a DLL containing a particular class:

var ver = System.Reflection.Assembly.GetAssembly(typeof(!Class!)).GetName().Version;

Just replace !Class! with the name of a class which is defined in the DLL you wish to get the version of.

This is my preferred method because if I move the DLLs around for different deploys I don't have to change the filepath.

PHP cURL HTTP CODE return 0

Try this after curl_exec to see what's the problem:

print curl_error($ch);

If it's print something like 'malformed' then check your URL format.

how to get the selected index of a drop down

If you are actually looking for the index number (and not the value) of the selected option then it would be

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

or using jQuery

$('select[name="CCards"]')[0].selectedIndex 

How should we manage jdk8 stream for null values

Current thinking seems to be to "tolerate" nulls, that is, to allow them in general, although some operations are less tolerant and may end up throwing NPE. See the discussion of nulls on the Lambda Libraries expert group mailing list, specifically this message. Consensus around option #3 subsequently emerged (with a notable objection from Doug Lea). So yes, the OP's concern about pipelines blowing up with NPE is valid.

It's not for nothing that Tony Hoare referred to nulls as the "Billion Dollar Mistake." Dealing with nulls is a real pain. Even with classic collections (without considering lambdas or streams) nulls are problematic. As fge mentioned in a comment, some collections allow nulls and others do not. With collections that allow nulls, this introduces ambiguities into the API. For example, with Map.get(), a null return indicates either that the key is present and its value is null, or that the key is absent. One has to do extra work to disambiguate these cases.

The usual use for null is to denote the absence of a value. The approach for dealing with this proposed for Java SE 8 is to introduce a new java.util.Optional type, which encapsulates the presence/absence of a value, along with behaviors of supplying a default value, or throwing an exception, or calling a function, etc. if the value is absent. Optional is used only by new APIs, though, everything else in the system still has to put up with the possibility of nulls.

My advice is to avoid actual null references to the greatest extent possible. It's hard to see from the example given how there could be a "null" Otter. But if one were necessary, the OP's suggestions of filtering out null values, or mapping them to a sentinel object (the Null Object Pattern) are fine approaches.

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

How do I print a double value with full precision using cout?

C++20 std::format

This great new C++ library feature has the advantage of not affecting the state of std::cout as std::setprecision does:

#include <format>
#include <string>

int main() {
    std::cout << std::format("{:.2} {:.3}\n", 3.1415, 3.1415);
}

Expected output:

3.14 3.145

The as mentioned at https://stackoverflow.com/a/65329803/895245 not if you don't pass the precision explicitly it prints the shortest decimal representation with a round-trip guarantee. TODO understand in more detail how it compares to: dbl::max_digits10 as shown at https://stackoverflow.com/a/554134/895245 with {:.{}}:

#include <format>
#include <limits>
#include <string>

int main() {
    std::cout << std::format("{:.{}}\n",
        3.1415926535897932384626433, dbl::max_digits10);
}

See also:

How to extend / inherit components?

Now that TypeScript 2.2 supports Mixins through Class expressions we have a much better way to express Mixins on Components. Mind you that you can also use Component inheritance since angular 2.3 (discussion) or a custom decorator as discussed in other answers here. However, I think Mixins have some properties that make them preferable for reusing behavior across components:

  • Mixins compose more flexibly, i.e. you can mix and match Mixins on existing components or combine Mixins to form new Components
  • Mixin composition remains easy to understand thanks to its obvious linearization to a class inheritance hierarchy
  • You can more easily avoid issues with decorators and annotations that plague component inheritance (discussion)

I strongly suggest you read the TypeScript 2.2 announcement above to understand how Mixins work. The linked discussions in angular GitHub issues provide additional detail.

You'll need these types:

export type Constructor<T> = new (...args: any[]) => T;

export class MixinRoot {
}

And then you can declare a Mixin like this Destroyable mixin that helps components keep track of subscriptions that need to be disposed in ngOnDestroy:

export function Destroyable<T extends Constructor<{}>>(Base: T) {
  return class Mixin extends Base implements OnDestroy {
    private readonly subscriptions: Subscription[] = [];

    protected registerSubscription(sub: Subscription) {
      this.subscriptions.push(sub);
    }

    public ngOnDestroy() {
      this.subscriptions.forEach(x => x.unsubscribe());
      this.subscriptions.length = 0; // release memory
    }
  };
}

To mixin Destroyable into a Component, you declare your component like this:

export class DashboardComponent extends Destroyable(MixinRoot) 
    implements OnInit, OnDestroy { ... }

Note that MixinRoot is only necessary when you want to extend a Mixin composition. You can easily extend multiple mixins e.g. A extends B(C(D)). This is the obvious linearization of mixins I was talking about above, e.g. you're effectively composing an inheritnace hierarchy A -> B -> C -> D.

In other cases, e.g. when you want to compose Mixins on an existing class, you can apply the Mixin like so:

const MyClassWithMixin = MyMixin(MyClass);

However, I found the first way works best for Components and Directives, as these also need to be decorated with @Component or @Directive anyway.

What is a NullPointerException, and how do I fix it?

It's like you are trying to access an object which is null. Consider below example:

TypeA objA;

At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense.

See this below example as well:

String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown

How to prettyprint a JSON file?

To be able to pretty print from the command line and be able to have control over the indentation etc. you can set up an alias similar to this:

alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"

And then use the alias in one of these ways:

cat myfile.json | jsonpp
jsonpp < myfile.json

PHP: Call to undefined function: simplexml_load_string()

If the XML module is not installed, install it.

Current version 5.6 on ubuntu 14.04:

sudo apt-get install php5.6-xml

And don't forget to run sudo service apache2 restart command after it

Zulhilmi Zainudi

How to make the background DIV only transparent using CSS

I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.

Which mean:

<div id="a">
<div id="b">
</div></div>

Div#a has 0.6 opacity
div#b has 1 opacity

Has #b is within #a then it's maximum opacity is always 0.6

If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity

How to make a div with a circular shape?

.circle {
    border-radius: 50%;
    width: 500px;
    height: 500px;
    background: red;
}

<div class="circle"></div>

see this FIDDLE

Storing an object in state of a React component?

this.setState({abc: {xyz: 'new value'}}); will NOT work, as state.abc will be entirely overwritten, not merged.

This works for me:

this.setState((previousState) => {
  previousState.abc.xyz = 'blurg';
  return previousState;
});

Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html

Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:

const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

How to force HTTPS using a web.config file

In .Net Core, follow the instructions at https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl

In your startup.cs add the following:

// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });`enter code here`

To redirect Http to Https, add the following in the startup.cs

// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var options = new RewriteOptions()
       .AddRedirectToHttps();

    app.UseRewriter(options);

How do I find an array item with TypeScript? (a modern, easier way)

For some projects it's easier to set your target to es6 in your tsconfig.json.

{
  "compilerOptions": {
    "target": "es6",
    ...

How to generate service reference with only physical wsdl file

There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.

1. To create it via the IDE:

In the solution explorer pane, right click on the project that you would like to add the Service to:

enter image description here

Then, you can enter the path to your service WSDL and hit go:

enter image description here

2. To create it via the command line:

Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:

WSDL /verbose C:\path\to\wsdl

WSDL.exe will then output a .cs file for your consumption.

If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:

WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd

If you need VB output, use /language:VB in addition to the /verbose.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

Just add this sentence in your build.gradle:

compile 'com.android.support:design:23.1.1'

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST some data to www.abc.com/blog and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog from the same user. So it'll give the 409 error.

Subscripts in plots in R

As other users have pointed out, we use expression(). I'd like to answer the original question which involves a comma in the subscript:

How can I write v 1,2 with 1,2 as subscripts?

plot(1:10, 11:20 , main=expression(v["1,2"]))

Also, I'd like to add the reference for those looking to find the full expression syntax in R plotting: For more information see the ?plotmath help page. Running demo(plotmath) will showcase many expressions and relevant syntax.

Remember to use * to join different types of text within an expression.

Here is some of the sample output from demo(plotmath):

enter image description here

Hook up Raspberry Pi via Ethernet to laptop without router?

What worked for me was a combination of the answers from Nicole Finnie and Ciro Santilli along with some answers from elsewhere.

Setting up the pi

We will need to do two things: activate ssh on the pi, and configure the pi to use a static ip.

Activating ssh

Add a file called ssh in the boot partition of the sd card (not the /boot folder in the root partition). This is well documented other places.

Static ip

Open /etc/dhcpcd.conf on the pi's SD-card, and uncomment the example for a static ip (starts around line 40). Set the addresses to

# Example static IP configuration:
interface eth0
static ip_address=10.42.0.182/24
static routers=10.42.0.1
static domain_name_servers=10.42.0.1 8.8.8.8 fd51:42f8:caae:d92e::1

Setting up your laptop

First, make sure you have networkmanager (with GUI) installed on your laptop. Then, make sure dnsmasq is not running as a service:
systemctl status dnsmasq
If this command prints that the service is stopped, then you're good.

Next we have to config networkmanager. Open /etc/NetworkManager/NetworkManager.conf and add the following two lines at the top:

[main]
DNS=dnsmasq

Then reboot. This step might not be necessary. It might be sufficient to restart the NetworkManager service. Now go to the NetworkManager GUI (usually accessed by an icon in the corner of the screen) and choose Edit Connections... In the window that pops up, click the + icon to create a new connection. Choose Ethernet as the type and press Create.... Go to the IPv4 Settings tab and select the method Shared to other computers. Give the connection a good name and save.

Connect the Raspberry Pi and make sure your laptop is using your new connection as its ethernet connection. If it is, your pi should now have an ip given to it by your pc. You can find this by first running ifconfig. This should give you several blocks of text, one for each network interface. You're interested in the one that is something like enp0s25 or eth0. It should have a line that reads something similar to
inet 10.42.0.1 netmask 255.255.255.0 broadcast 10.42.0.255
look at the broadcast address (in this case 10.42.0.255). If it is different than mine, power off the pi and put the SD card back in your laptop to change the static ip_address to something where the first three numbers are the same as in your broadcast address. Also change the static routers and the first of the domain_name_servers to your laptop's inet address. Power the pi back on and connect it. Run ifconfig again to see that the addresses have not changed.

ssh into the pi

ssh [email protected]
If you get connection refused, the pi isn't running an ssh server. If you get host unreachable, I'm sorry.

Hope this helps someone!

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

Vue.js data-bind style backgroundImage not working

<div :style="{'background-image': 'url(' + require('./assets/media/img.jpg') + ')'}"></div>

Oracle query to identify columns having special characters

Compare the length using lengthB and length function in oracle.

SELECT * FROM test WHERE length(sampletext) <> lengthb(sampletext)

Netbeans - class does not have a main method

My situation was different I believe because non of the above solutions di work for me. Let me share my situation.

  1. I am importing an existing project (NewProject->Java->Import Existing Projects)
  2. I name the project to xyz. The 'main' function exists in Main.class.
  3. I try to run the code I modified in the main function but the error pops out. I tried the shift_f6, specifically rebuild. Nothing works.

    Solution: I took the project properties and saw the 'Source Package Folder' mappings in the Sources branch was blank. I mapped it and voila it worked.

Now anyone might think that was very silly of me. Although I am new to Java and Netbeans this is not the first time I am importing sample projects and I saw all of them had the properties similar. The only difference I saw was that the main class was not having the name as the project which I believe is a java convention. I am using JDK7u51 (latest till date), is it causing the issue? I have no idea. But I am happy the project is running fine now.

Conversion failed when converting the varchar value to data type int in sql

The line

SELECT  @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))

is wrong.

@Prefix is 'J' and LEN(...anything...) is an int, hence the type mismatch.


It seems to me, you actually want to do,

SELECT
        @maxCode = MAX(
            CAST(SUBSTRING(
                Voucher_No,
                @startFrom + 1,
                LEN(Voucher_No) - (@startFrom + 1)) AS INT)
    FROM
        dbo.Journal_Entry;

SELECT  @Prefix + CAST(@maxCode AS VARCHAR(10));

but, I couldn't say. If you illustrated before and after data, it would help.

What is a Subclass

It is a class that extends another class.

example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)

public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}

remove space between paragraph and unordered list

You can (A) change the markup to not use paragraphs

<span>Text</span>
<br>
<ul>
  <li>One</li>
</ul>
<span>Text 2</span>

Or (B) change the css

p{margin:0px;}

Demos here: http://jsfiddle.net/ZnpVu/1

Guzzlehttp - How get the body of a response from Guzzle 6?

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:

$contents = (string) $response->getBody();

You can also do it with

$contents = $response->getBody()->getContents();

The difference between the two approaches is that getContents returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind or seek .

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents

Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

100% width table overflowing div container

update your CSS to the following: this should fix

.page {
    width: 280px;
    border:solid 1px blue;
    overflow-x: auto;
}

How can I access iframe elements with Javascript?

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

form serialize javascript (no framework)

HTMLElement.prototype.serialize = function(){
    var obj = {};
    var elements = this.querySelectorAll( "input, select, textarea" );
    for( var i = 0; i < elements.length; ++i ) {
        var element = elements[i];
        var name = element.name;
        var value = element.value;

        if( name ) {
            obj[ name ] = value;
        }
    }
    return JSON.stringify( obj );
}

To use like this:

var dataToSend = document.querySelector("form").serialize();

I hope I have helped.

Group By Multiple Columns

Procedural sample

.GroupBy(x => new { x.Column1, x.Column2 })

Why is using onClick() in HTML a bad practice?

There are a few reasons:

  1. I find it aids maintenence to separate markup, i.e. the HTML and client-side scripts. For example, jQuery makes it easy to add event handlers programatically.

  2. The example you give would be broken in any user agent that doesn't support javascript, or has javascript turned off. The concept of progressive enhancement would encourage a simple hyperlink to /map/ for user agents without javascript, then adding a click handler prgramatically for user agents that support javascript.

For example:

Markup:

<a id="example" href="/map/">link</a>

Javascript:

$(document).ready(function(){

    $("#example").click(function(){
        popup('/map/', 300, 300, 'map');
        return false;
    });

})

Redirect website after certain amount of time

<meta http-equiv="refresh" content="3;url=http://www.google.com/" />

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.

For example:

import math
import numpy as np
alpha = 0.2 
beta=1-alpha
C = (-math.log(1-beta))/alpha

coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C

The error:

    coff *= C 
TypeError: can't multiply sequence by non-int of type 'float'

The solution - convert the list to numpy array:

coff = np.asarray(coff) * C

How to pass data between fragments

Basically here we are dealing with communication between Fragments. Communication between fragments can never be directly possible. It involves activity under the context of which both the fragments are created.

You need to create an interface in the sending fragment and implement the interface in the activity which will reprieve the message and transfer to the receiving fragment.

How to access child's state in React?

As the previous answers saids, try to move the state to a top component and modify the state through callbacks passed to it's children.

In case that you really need to access to a child state that is declared as a functional component (hooks) you can declare a ref in the parent component, then pass it as a ref attribute to the child but you need to use React.forwardRef and then the hook useImperativeHandle to declare a function you can call in the parent component.

Take a look at the following example:

const Parent = () => {
    const myRef = useRef();
    return <Child ref={myRef} />;
}

const Child = React.forwardRef((props, ref) => {
    const [myState, setMyState] = useState('This is my state!');
    useImperativeHandle(ref, () => ({getMyState: () => {return myState}}), [myState]);
})

Then you should be able to get myState in the Parent component by calling: myRef.current.getMyState();

How to reference static assets within vue javascript

I'm using typescript with vue, but this is how I went about it

<template><div><img :src="MyImage" /></div></template>
<script lang="ts">
    import { Vue } from 'vue-property-decorator';
    export default class MyPage extends Vue {
            MyImage = "../assets/images/myImage.png";
        }
</script>

Laravel Fluent Query Builder Join with subquery

I am on Laravel 7.25 and I don't know if it supports on previous versions or not but Its pretty good.

Syntax for the function:

public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)

Example:

Showing/Getting the user ID and the total number of posts by them left joining two tables users and posts.

        return DB::table('users')
            ->joinSub('select user_id,count(id) noOfPosts from posts group by user_id', 'totalPosts', 'users.id', '=', 'totalPosts.user_id', 'left')
            ->select('users.name', 'totalPosts.noOfPosts')
            ->get();

Alternative:

If you don't wanna mention 'left' for leftjoin then you can use another prebuilt function

    public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
    {
        return $this->joinSub($query, $as, $first, $operator, $second, 'left');
    }

And yeah, it actually calls the same function but it passes the join type itself. You can apply the same logic for other joins i.e. righJoinSub(...) etc.

jQuery ID starts with

try:

$("td[id^=" + value + "]")

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

If the "Customer don't want to install and buy MS Office on a server not at any price", then you cannot use Excel ... But I cannot get the trick: it's all about one basic Office licence which costs something like 150 USD ... And I guess that spending time finding an alternative will cost by far more than this amount!

Error: JAVA_HOME is not defined correctly executing maven

You might get this error due to couple of reasons. To fix this quickly please follow below steps,

First find the java location. To get a list of your installed Java platforms, run the following command from the terminal:

$ sudo update-alternatives --config java

Now set JAVA_HOME and PATH,

$ export JAVA_HOME=<java_home>

$ export PATH=$JAVA_HOME/jre/bin:$PATH

Create the symlink

$ sudo ln -s <java_home>/jre <java_symlink_path>

When we take your case as a example :

$ sudo ln -s /usr/lib/jvm/java-7-oracle/jre /usr/lib/jvm/java-7-oracle/jre/bin/java

Above command will create the symlink location where the system is trying to find in your issue.

Finally do the

$ mvn --version

How can I override Bootstrap CSS styles?

Give ID to legend and apply css. Like add id hello to legend() the css is as follw:

#legend  legend {
  display: block;
  width: 100%;
  padding: 0;
  margin-bottom: 20px;
  font-size: 21px;
  line-height: inherit;
  color: #333333;
  border: 0;
  border-bottom: 1px solid #e5e5e5;
}

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Add left/right horizontal padding to UILabel

Subclass UILabel and override drawTextInRect: like this:

- (void)drawTextInRect:(CGRect)rect 
{
    UIEdgeInsets insets = {0, 10, 0, 0};
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

MVC - Set selected value of SelectList

I ended up here because SelectListItem is no longer picking the selected value correctly. To fix it, I changed the usage of EditorFor for a "manual" approach:

        <select id="Role" class="form-control">
            @foreach (var role in ViewBag.Roles)
            {
                if (Model.Roles.First().RoleId == role.Value)
                {
                    <option value="@role.Value" selected>@role.Text</option>
                }
                else
                {
                    <option value="@role.Value">@role.Text</option>
                }
            }
        </select>

Hope it helps someone.

How do I delete files programmatically on Android?

File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();

not working in my case. The issue has been resolved by using below code-

ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );

Initialising mock objects - MockIto

MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:

XXX mockedXxx = mock(XXX.class);

I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

just run the android sdk manager , go to tools then obtions and a new window will apears mark the three checkboxes at the bottom and close it it worked for me

javascript onclick increment number

Since you gave me nothing to start on, here is a simple example.

jsFiddle

Example implementation:

function incrementValue()
{
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}

Example Html

<form>
   <input type="text" id="number" value="0"/>
   <input type="button" onclick="incrementValue()" value="Increment Value" />
</form>

How to convert std::string to lower case?

Try this function :)

string toLowerCase(string str) {

    int str_len = str.length();

    string final_str = "";

    for(int i=0; i<str_len; i++) {

        char character = str[i];

        if(character>=65 && character<=92) {

            final_str += (character+32);

        } else {

            final_str += character;

        }

    }

    return final_str;

}

How to read data when some numbers contain commas as thousand separator?

A very convenient way is readr::read_delim-family. Taking the example from here: Importing csv with multiple separators into R you can do it as follows:

txt <- 'OBJECTID,District_N,ZONE_CODE,COUNT,AREA,SUM
1,Bagamoyo,1,"136,227","8,514,187,500.000000000000000","352,678.813105723350000"
2,Bariadi,2,"88,350","5,521,875,000.000000000000000","526,307.288878142830000"
3,Chunya,3,"483,059","30,191,187,500.000000000000000","352,444.699742995200000"'

require(readr)
read_csv(txt) # = read_delim(txt, delim = ",")

Which results in the expected result:

# A tibble: 3 Ă— 6
  OBJECTID District_N ZONE_CODE  COUNT        AREA      SUM
     <int>      <chr>     <int>  <dbl>       <dbl>    <dbl>
1        1   Bagamoyo         1 136227  8514187500 352678.8
2        2    Bariadi         2  88350  5521875000 526307.3
3        3     Chunya         3 483059 30191187500 352444.7

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

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

Suggestions:

  • use consistent 3-4 space indenting and you will find these problems much easier
  • use a brace style that lines up {} vertically and you will see these problems quickly
  • always indent control blocks another level
  • use a syntax highlighting editor, it helps, you'll thank me later

for example,

type
functionname( arguments )
{
    if (something)
    {
        do stuff
    }
    else
    {
        do other stuff
    }
    switch (value)
    {
        case 'a':
            astuff
            break;
        case 'b':
            bstuff
            //fallthrough //always comment fallthrough as intentional
        case 'c':
            break;
        default: //always consider default, and handle it explicitly
            break;
    }
    while ( the lights are on )
    {
        if ( something happened )
        {
            run around in circles
            if ( you are scared ) //yeah, much more than 3-4 levels of indent are too many!
            {
                scream and shout
            }
        }
    }
    return typevalue; //always return something, you'll thank me later
}

How to configure Docker port mapping to use Nginx as an upstream proxy?

@gdbj's answer is a great explanation and the most up to date answer. Here's however a simpler approach.

So if you want to redirect all traffic from nginx listening to 80 to another container exposing 8080, minimum configuration can be as little as:

nginx.conf:

server {
    listen 80;

    location / {
        proxy_pass http://client:8080; # this one here
        proxy_redirect off;
    }

}

docker-compose.yml

version: "2"
services:
  entrypoint:
    image: some-image-with-nginx
    ports:
      - "80:80"
    links:
      - client  # will use this one here

  client:
    image: some-image-with-api
    ports:
      - "8080:8080"

Docker docs

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Git/GitHub can't push to master

This error occurs when you clone a repo using a call like:

git clone git://github.com/....git

This essentially sets you up as a pull-only user, who can't push up changes.

I fixed this by opening my repo's .git/config file and changing the line:

[remote "origin"]
    url = git://github.com/myusername/myrepo.git

to:

[remote "origin"]
    url = ssh+git://[email protected]/myusername/myrepo.git

This ssh+git protocol with the git user is the authentication mechanism preferred by Github.

The other answers mentioned here technically work, but they all seem to bypass ssh, requiring you to manually enter a password, which you probably don't want.

data.frame rows to a list

An alternative way is to convert the df to a matrix then applying the list apply lappy function over it: ldf <- lapply(as.matrix(myDF), function(x)x)

Group by in LINQ

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key,
                           /**/car = g.Select(g=>g.car).FirstOrDefault()/**/}

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had a similar problem when I deployed my Flask app in the IIS. Apparently, IIS does not accept route that include an underline ("_"). When I removed the underline, problem was resolved.

How to change DataTable columns order

Re-Ordering data Table based on some condition or check box checked. PFB :-

 var tableResult= $('#exampleTable').DataTable();

    var $tr = $(this).closest('tr');
    if ($("#chkBoxId").prop("checked")) 
                    {
                        // re-draw table shorting based on condition
                        tableResult.row($tr).invalidate().order([colindx, 'asc']).draw();
                    }
                    else {
                        tableResult.row($tr).invalidate().order([colindx, "asc"]).draw();
                    }

Print newline in PHP in single quotes

FYI it is possible to get newlines into strings without double quotes:

printf('Please%1$sgive%1$sme%1$snewlines%1$s', PHP_EOL);

Which may be useful If your irrational fear of double quotes knows no bounds. Though I fear this cure may be worse than the disease.

Spring mvc @PathVariable

have a look at the below code snippet.

@RequestMapping(value = "edit.htm", method = RequestMethod.GET) 
    public ModelAndView edit(@RequestParam("id") String id) throws Exception {
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("user", userinfoDao.findById(id));
        return new ModelAndView("edit", modelMap);      
    }

If you want the complete project to see how it works then download it from below link:-

UserInfo Project on GitLab

C: How to free nodes in the linked list?

An iterative function to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

What the function is doing is the follow:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

How do I make bootstrap table rows clickable?

<tr height="70" onclick="location.href='<%=site_adres2 & urun_adres%>'"
    style="cursor:pointer;">

Viewing unpushed Git commits

To list all unpushed commit in all branches easily you can use this command:

 git log --branches  @{u}..

Excel - Shading entire row based on change of value

If you are using MS Excel 2007, you could use the conditional formatting on the Home tab as shown in the screenshot below. You could either use the color scales default option as I have done here or you can go ahead and create a new rule based on your data set. Conditional Formatting

Writing unit tests in Python: How do I start?

As others already replied, it's late to write unit tests, but not too late. The question is whether your code is testable or not. Indeed, it's not easy to put existing code under test, there is even a book about this: Working Effectively with Legacy Code (see key points or precursor PDF).

Now writing the unit tests or not is your call. You just need to be aware that it could be a tedious task. You might tackle this to learn unit-testing or consider writing acceptance (end-to-end) tests first, and start writing unit tests when you'll change the code or add new feature to the project.

Format Instant to String

Time Zone

To format an Instant a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.

The time-zone can be added directly to the formatter using withZone().

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

If you specifically want an ISO-8601 format with no explicit time-zone (as the OP asked), with the time-zone implicitly UTC, you need

DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))

Generating String

Now use that formatter to generate the String representation of your Instant.

Instant instant = Instant.now();
String output = formatter.format( instant );

Dump to console.

System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );

When run.

formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34

move a virtual machine from one vCenter to another vCenter

Yes, you can do this.

  1. Copy all of the cloned VM's files from its directory, and place it on its destination datastore.
  2. In the VI client connected to the destination vCenter, go to the Inventory->Datastores view.
  3. Open the datastore browser for the datastore where you placed the VM's files.
  4. Find the .vmx file that you copied over and right-click it.
  5. Choose 'Register Virtual Machine', and follow whatever prompts ensue. (Depending on your version of vCenter, this may be 'Add to Inventory' or some other variant)

The VM registration process should finish with the cloned VM usable in the new vCenter!

Good luck!

Python not working in command prompt?

Just go with the command py. I'm running python 3.6.2 on windows 7 and it works just fine.
I removed all the python paths from the system directory and the paths don't show up when I run the command echo %path% in cmd. Python is still working fine.
I ran into this by accidentally pressing enter while typing python...

EDIT: I didn't mention that I installed python to a custom folder C:\Python\

SELECT CASE WHEN THEN (SELECT)

For a start the first select has 6 columns and the second has 4 columns. Perhaps make both have the same number of columns (adding nulls?).

MongoDB - Update objects in a document's array (nested updating)

For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:

 db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.

The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:

 db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:

db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
               {$inc : {total : 1 , "items.$.price" : 1}} ,
               false ,
               true);

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

How to convert CSV file to multiline JSON?

As slight improvement to @MONTYHS answer, iterating through a tup of fieldnames:

import csv
import json

csvfilename = 'filename.csv'
jsonfilename = csvfilename.split('.')[0] + '.json'
csvfile = open(csvfilename, 'r')
jsonfile = open(jsonfilename, 'w')
reader = csv.DictReader(csvfile)

fieldnames = ('FirstName', 'LastName', 'IDNumber', 'Message')

output = []

for each in reader:
  row = {}
  for field in fieldnames:
    row[field] = each[field]
output.append(row)

json.dump(output, jsonfile, indent=2, sort_keys=True)

How to get coordinates of an svg element?

The way to determine the coordinates depends on what element you're working with. For circles for example, the cx and cy attributes determine the center position. In addition, you may have a translation applied through the transform attribute which changes the reference point of any coordinates.

Most of the ways used in general to get screen coordinates won't work for SVGs. In addition, you may not want absolute coordinates if the line you want to draw is in the same container as the elements it connects.

Edit:

In your particular code, it's quite difficult to get the position of the node because its determined by a translation of the parent element. So you need to get the transform attribute of the parent node and extract the translation from that.

d3.transform(d3.select(this.parentNode).attr("transform")).translate

Working jsfiddle here.

Decoding a Base64 string in Java

The following should work with the latest version of Apache common codec

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));

and for encoding

byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));

How to pass a URI to an intent?

here how I use it; This button inside my CameraActionActivity Activity class where I call camera

 btn_frag_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intenImatToSec = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                startActivityForResult(intenImatToSec, REQUEST_CODE_VIDEO);
                //intenImatToSec.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                //intenImatToSec.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
                //Toast.makeText(getActivity(), "Hello From Camera", Toast.LENGTH_SHORT).show();
            }
        });



@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {

            if (requestCode == REQUEST_CODE_IMG) {
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");
                Intent intentBitMap = new Intent(getActivity(), DisplayImage.class);
                // aldigimiz imagi burda yonlendirdigimiz sinifa iletiyoruz
                ByteArrayOutputStream _bs = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
                intentBitMap.putExtra("byteArray", _bs.toByteArray());
                startActivity(intentBitMap);

            } else if (requestCode == REQUEST_CODE_VIDEO) {
                Uri videoUrl = data.getData();
                Intent intenToDisplayVideo = new Intent(getActivity(), DisplayVideo.class);
                intenToDisplayVideo.putExtra("videoUri", videoUrl.toString());
                startActivity(intenToDisplayVideo);
            }
        }
    }

And my other DisplayVideo Activity Class

VideoView videoView = (VideoView) findViewById(R.id.videoview_display_video_actvity);
Bundle extras = getIntent().getExtras();
        Uri myUri=  Uri.parse(extras.getString("videoUri"));
        videoView.setVideoURI(myUri);

Is there a RegExp.escape function in JavaScript?

escapeRegExp = function(str) {
  if (str == null) return '';
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};

How to format a numeric column as phone number in SQL

Solutions that use SUBSTRING and concatenation + are nearly independent of RDBMS. Here is a short solution that is specific to SQL Server:

declare @x int = 123456789
select stuff(stuff(@x, 4, 0, '-'), 8, 0, '-')

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

This is working code for your query,you can use it.

Controler

    [HttpPost]
    public ActionResult save(List<ListName> listObject)
    {
    //operation return
    Json(new { istObject }, JsonRequestBehavior.AllowGet); }
    }

javascript

  $("#btnSubmit").click(function () {
    var myColumnDefs = [];
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') })
        } else {
            myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') })
        }
    });
   var data1 = { 'listObject': myColumnDefs};
   var data = JSON.stringify(data1)
   $.ajax({
   type: 'post',
   url: '/Controller/action',
   data:data ,
   contentType: 'application/json; charset=utf-8',
   success: function (response) {
    //do your actions
   },
   error: function (response) {
    alert("error occured");
   }
   });

How do I pass parameters to a jar file at the time of execution?

java [ options ] -jar file.jar [ argument ... ]

if you need to pass the log4j properties file use the below option

-Dlog4j.configurationFile=directory/file.xml


java -Dlog4j.configurationFile=directory/file.xml -jar <JAR FILE> [arguments ...]

How to prevent custom views from losing state across screen orientation changes

I found that this answer was causing some crashes on Android versions 9 and 10. I think it's a good approach but when I was looking at some Android code I found out it was missing a constructor. The answer is quite old so at the time there probably was no need for it. When I added the missing constructor and called it from the creator the crash was fixed.

So here is the edited code:

public class CustomView extends LinearLayout {

    private int stateToSave;

    ...

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        // your custom state
        ss.stateToSave = this.stateToSave;

        return ss;
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container)
    {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        // your custom state
        this.stateToSave = ss.stateToSave;
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
    {
        dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState {
        int stateToSave;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.stateToSave = in.readInt();
        }

        // This was the missing constructor
        @RequiresApi(Build.VERSION_CODES.N)
        SavedState(Parcel in, ClassLoader loader)
        {
            super(in, loader);
            this.stateToSave = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.stateToSave);
        }    
        
        public static final Creator<SavedState> CREATOR =
            new ClassLoaderCreator<SavedState>() {
          
            // This was also missing
            @Override
            public SavedState createFromParcel(Parcel in, ClassLoader loader)
            {
                return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(in, loader) : new SavedState(in);
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in, null);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

HTTP Error 503. The service is unavailable. App pool stops on accessing website

I had a similar issue, all my app pools were stopping whenever a web request was made to them. Although I was getting the following error in the Event Viewer:

The worker process for application pool 'appPoolName' encountered an error 'Configuration file is not well-formed XML ' trying to read configuration data from file '\?\C:\inetpub\temp\apppools\appPoolName\appPoolName.config', line number '3'. The data field contains the error code.

Which told me that there were errors in the application.config at:

C:\Windows\System32\inetsrv\config\applicationHost.config

In my scenario, I edited the web.config on deploy with an element IIS clearly dislikes, the applicationHost.config scraped the web.config and inserted this bad element and wouldn't resolve until I manually removed it