Programs & Examples On #Thread state

Thread state describes state of thread in given time.

What is an idempotent operation?

Idempotent Operations: Operations that have no side-effects if executed multiple times.
Example: An operation that retrieves values from a data resource and say, prints it

Non-Idempotent Operations: Operations that would cause some harm if executed multiple times. (As they change some values or states)
Example: An operation that withdraws from a bank account

What does the 'L' in front a string mean in C++?

It means the text is stored as wchar_t characters rather than plain old char characters.

(I originally said it meant unicode. I was wrong about that. But it can be used for unicode.)

Pandas read_csv low_memory and dtype options

As the error says, you should specify the datatypes when using the read_csv() method. So, you should write

file = pd.read_csv('example.csv', dtype='unicode')

lexical or preprocessor issue file not found occurs while archiving?

For what it's worth, my problem was completely unrelated to the error Xcode was giving. I stumbled onto a solution by deleting the .h reference, compiling, adding the reference back and compiling again. The actual error then became evident.

Angular2: Cannot read property 'name' of undefined

In Angular, there is the support elvis operator ?. to protect against a view render failure. They call it the safe navigation operator. Take the example below:

The current person name is {{nullObject?.name}}

Since it is trying to access name property of a null value, the whole view disappears and you can see the error inside the browser console. It works perfectly with long property paths such as a?.b?.c?.d. So I recommend you to use it everytime you need to access a property inside a template.

Calculating moving average

You could use RcppRoll for very quick moving averages written in C++. Just call the roll_mean function. Docs can be found here.

Otherwise, this (slower) for loop should do the trick:

ma <- function(arr, n=15){
  res = arr
  for(i in n:length(arr)){
    res[i] = mean(arr[(i-n):i])
  }
  res
}

Does MySQL foreign_key_checks affect the entire database?

I had the same error when I tried to migrate Drupal database to a new local apache server(I am using XAMPP on Windows machine). Actually I don't know the meaning of this error, but after trying steps below, I imported the database without errors. Hope this could help:

Changing php.ini at C:\xampp\php\php.ini

max_execution_time = 600
max_input_time = 600
memory_limit = 1024M
post_max_size = 1024M

Changing my.ini at C:\xampp\mysql\bin\my.ini

max_allowed_packet = 1024M

How to overcome root domain CNAME restrictions?

Sipwiz is correct the only way to do this properly is the HTTP and DNS hybrid approach. My registrar is a re-seller for Tucows and they offer root domain forwarding as a free value added service.

If your domain is blah.com they will ask you where you would like the domain forwarded to, and you type in www.blah.com. They assign the A record to their apache server and automaticly add blah.com as a DNS vhost. The vhost responds with an HTTP 302 error redirecting them to the proper URL. It's simple to script/setup and can be handled by low end would otherwise be scrapped hardware.

Run the following command for an example: curl -v eclecticengineers.com

Jquery - How to make $.post() use contentType=application/json?

The "json" datatype that you can pass as the last parameter to post() indicates what type of data the function is expecting in the server's response, not what type it's sending in the request. Specifically it sets the "Accept" header.

Honestly your best bet is to switch to an ajax() call. The post() function is meant as a convenience; a simplified version of the ajax() call for when you are just doing a simple form posting. You aren't.

If you really don't want to switch, you could make your own function called, say, xpost(), and have it simply transform the given parameters into parameters for a jQuery ajax() call, with the content-type set. That way, rather than rewriting all of those post() functions into ajax() functions, you just have to change them all from post to xpost (or whatever).

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

How can I add a table of contents to a Jupyter / JupyterLab notebook?

As Ian already pointed out, there is a table-of-contents extension by minrk for the IPython Notebook. I had some trouble to make it work and made this IPython Notebook which semi-automatically generates the files for minrk's table of contents extension in Windows. It does not use the 'curl'-commands or links, but writes the *.js and *.css files directly into your IPython Notebook-profile-directory.

There is a section in the notebook called 'What you need to do' - follow it and have a nice floating table of contents : )

Here is an html version which already shows it: http://htmlpreview.github.io/?https://github.com/ahambi/140824-TOC/blob/master/A%20floating%20table%20of%20contents.htm

How to pass boolean parameter value in pipeline to downstream jobs?

Not sure if this answers this question. But I was looking for something else. Highly recommend see this 2 minute video. If you wanted to get into more details then see docs - Handling Parameters and this link

And then if you have something like blue ocean, the choices would look something like this:

enter image description here

You define and access your variables like this:

pipeline {
    agent any

    parameters {
    string(defaultValue: "TEST", description: 'What environment?', name: 'userFlag')
    choice(choices: ['TESTING', 'STAGING', 'PRODUCTION'], description: 'Select field for target environment', name: 'DEPLOY_ENV')
    }

    stages {
        stage("foo") {
            steps {
                echo "flag: ${params.userFlag}"
                echo "flag: ${params.DEPLOY_ENV}"
            }
        }
    }
}

Automated builds will pick up the default params. But if you do it manually then you get the option to choose.

And then assign values like this:

enter image description here

Rounded table corners CSS only

Add between <head> tags:

<style>
  td {background: #ffddaa; width: 20%;}
</style>

and in the body:

<div style="background: black; border-radius: 12px;">
  <table width="100%" style="cell-spacing: 1px;">
    <tr>
      <td style="border-top-left-radius: 10px;">
        Noordwest
      </td>
      <td>&nbsp;</td>
      <td>Noord</td>
      <td>&nbsp;</td>
      <td style="border-top-right-radius: 10px;">
        Noordoost
      </td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>West</td>
      <td>&nbsp;</td>
      <td>Centrum</td>
      <td>&nbsp;</td>
      <td>Oost</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td style="border-bottom-left-radius: 10px;">
        Zuidwest
      </td>
      <td>&nbsp;</td>
      <td>Zuid</td>
      <td>&nbsp;</td>
      <td style="border-bottom-right-radius: 10px;">
        Zuidoost
      </td>
    </tr>
  </table>
</div>

The cell color, contents and formatting are of course for example;
it's about spacing color-filled cells within a div. Doing so, the black cell borders/table border are actually the div background color.
Note that you'll need to set the div-border-radius about 2 values greater than the separate cell corner border radii, to take a smooth rounded corner effect.

Git: How to remove remote origin from Git repo

Instead of removing and re-adding, you can do this:

git remote set-url origin git://new.url.here

See this question: How to change the URI (URL) for a remote Git repository?

To remove remote use this:

git remote remove origin

Dynamically create an array of strings with malloc


#define ID_LEN 5
char **orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */

orderedIds = (char **)malloc(variableNumberOfElements * (ID_LEN + 1) * sizeof(char));

..

Replace a newline in TSQL

REPLACE(@string, CHAR(13) + CHAR(10), '')

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

Import multiple csv files into pandas and concatenate into one DataFrame

If the multiple csv files are zipped, you may use zipfile to read all and concatenate as below:

import zipfile
import pandas as pd

ziptrain = zipfile.ZipFile('yourpath/yourfile.zip')

train = []

train = [ pd.read_csv(ziptrain.open(f)) for f in ziptrain.namelist() ]

df = pd.concat(train)

    

Passing HTML to template using Flask/Jinja2

Some people seem to turn autoescape off which carries security risks to manipulate the string display.

If you only want to insert some linebreaks into a string and convert the linebreaks into <br />, then you could take a jinja macro like:

{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}

and in your template just call this with

{{ linebreaks_for_string( my_string_in_a_variable ) }}

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

String concatenation: concat() vs "+" operator

When using +, the speed decreases as the string's length increases, but when using concat, the speed is more stable, and the best option is using the StringBuilder class which has stable speed in order to do that.

I guess you can understand why. But the totally best way for creating long strings is using StringBuilder() and append(), either speed will be unacceptable.

XAMPP installation on Win 8.1 with UAC Warning

There are two things you need to check:

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC (User Account Control) as it restricts certain administrative function needed to run a web server.

To ensure that your user account has administrator privilege, run lusrmgr.msc from the Windows Start > Run menu to bring up the Local Users and Groups Windows. Double-click on your user account that appears under Users, and verifies that it is a member of Administrators.

To disable UAC (as an administrator), from Control Panel:

  1. Type UAC in the search field in the upper right corner.
  2. Click Change User Account Control settings in the search results.
  3. Drag the slider down to Never notifyand click OK.

open up the User Accounts window from Control Panel. Click on the Turn User Account Control on or off option, and un-check the checkbox.

Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86), such as C:\xampp.

Hope this helps.

How to convert int to Integer

int iInt = 10;
Integer iInteger = new Integer(iInt);

Display progress bar while doing some work in C#?

If you want a "rotating" progress bar, why not set the progress bar style to "Marquee" and using a BackgroundWorker to keep the UI responsive? You won't achieve a rotating progress bar easier than using the "Marquee" - style...

How to disable the ability to select in a DataGridView?

You may set a transparent background color for the selected cells as following:

DataGridView.RowsDefaultCellStyle.SelectionBackColor = System.Drawing.Color.Transparent;

For vs. while in C programming?

They are all the same in the work they do. You can do the same things using any of them. But for readability, usability, convenience etc., they differ.

Android: converting String to int

// Convert String to Integer

// String s = "fred";  // use this if you want to test the exception below


String s = "100"; 
try
{
  // the String to int conversion happens here
  int i = Integer.parseInt(s.trim());

  // print out the value after the conversion
  System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
  System.out.println("NumberFormatException: " + nfe.getMessage());
}

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

What is the difference between Amazon SNS and Amazon SQS?

In simple terms,

  • SNS - sends messages to the subscriber using push mechanism and no need of pull.

  • SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.

A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.

Reference from Amazon SNS FAQs.

How to write log to file

maybe this will help you (if the log file exists use it, if it does not exist create it):

package main

import (
    "flag"
    "log"
    "os"
)
//Se declara la variable Log. Esta será usada para registrar los eventos.
var (
    Log *log.Logger = Loggerx()
)

func Loggerx() *log.Logger {
    LOG_FILE_LOCATION := os.Getenv("LOG_FILE_LOCATION")
        //En el caso que la variable de entorno exista, el sistema usa la configuración del docker.
    if LOG_FILE_LOCATION == "" {
        LOG_FILE_LOCATION = "../logs/" + APP_NAME + ".log"
    } else {
        LOG_FILE_LOCATION = LOG_FILE_LOCATION + APP_NAME + ".log"
    }
    flag.Parse()
        //Si el archivo existe se rehusa, es decir, no elimina el archivo log y crea uno nuevo.
    if _, err := os.Stat(LOG_FILE_LOCATION); os.IsNotExist(err) {
        file, err1 := os.Create(LOG_FILE_LOCATION)
        if err1 != nil {
            panic(err1)
        }
                //si no existe,se crea uno nuevo.
        return log.New(file, "", log.Ldate|log.Ltime|log.Lshortfile)
    } else {
                //si existe se rehusa.
        file, err := os.OpenFile(LOG_FILE_LOCATION, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
        if err != nil {
            panic(err)
        }
        return log.New(file, "", log.Ldate|log.Ltime|log.Lshortfile)
    }
}

For more detail: https://su9.co/9BAE74B

C++ initial value of reference to non-const must be an lvalue

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

PDF Blob - Pop up window not showing content

I have been struggling for days finally the solution which worked for me is given below. I had to make the window.print() for PDF in new window needs to work.

 var xhr = new XMLHttpRequest();
      xhr.open('GET', pdfUrl, true);
      xhr.responseType = 'blob';

      xhr.onload = function(e) {
        if (this['status'] == 200) {          
          var blob = new Blob([this['response']], {type: 'application/pdf'});
          var url = URL.createObjectURL(blob);
          var printWindow = window.open(url, '', 'width=800,height=500');
          printWindow.print()
        }
      };

      xhr.send();

Some notes on loading PDF & printing in a new window.

  • Loading pdf in a new window via an iframe will work, but the print will not work if url is an external url.
  • Browser pop ups must be allowed, then only it will work.
  • If you try to load iframe from external url and try window.print() you will get empty print or elements which excludes iframe. But you can trigger print manually, which will work.

how to insert date and time in oracle?

create table Customer(
       CustId int primary key,
       CustName varchar(20),
       DOB date);

insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));

Kotlin's List missing "add", "remove", Map missing "put", etc?

https://kotlinlang.org/docs/reference/collections.html

According to above link List<E> is immutable in Kotlin. However this would work:

var list2 = ArrayList<String>()
list2.removeAt(1)

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

Android 6.0 Marshmallow. Cannot write to SD Card

Android Documentation on Manifest.permission.Manifest.permission.WRITE_EXTERNAL_STORAGE states:

Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir().


I think that this means you do not have to code for the run-time implementation of the WRITE_EXTERNAL_STORAGE permission unless the app is writing to a directory that is not specific to your app.

You can define the max sdk version in the manifest per permission like:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="19" />

Also make sure to change the target SDK in the build.graddle and not the manifest, the gradle settings will always overwrite the manifest settings.

android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    minSdkVersion 17
    targetSdkVersion 22
}

Locking a file in Python

this worked for me: Do not occupy large files, distribute in several small ones you create file Temp, delete file A and then rename file Temp to A.

import os
import json

def Server():
    i = 0
    while i == 0:
        try:        
                with open(File_Temp, "w") as file:
                    json.dump(DATA, file, indent=2)
                if os.path.exists(File_A):
                    os.remove(File_A)
                os.rename(File_Temp, File_A)
                i = 1
        except OSError as e:
                print ("file locked: " ,str(e))
                time.sleep(1)
            
            
def Clients():
    i = 0
    while i == 0:
        try:
            if os.path.exists(File_A):
                with open(File_A,"r") as file:
                    DATA_Temp = file.read()
            DATA = json.loads(DATA_Temp)
            i = 1
        except OSError as e:
            print (str(e))
            time.sleep(1)

Find a string by searching all tables in SQL Server Management Studio 2008

There's no need for nested looping (outer looping through tables and inner looping through all table columns). One can retrieve all (or arbitrary selected/filtered) table-column combinations from INFORMATION_SCHEMA.COLUMNS and in one loop simply pass through (search) all of them:

DECLARE @search VARCHAR(100), @table SYSNAME, @column SYSNAME

DECLARE curTabCol CURSOR FOR
    SELECT c.TABLE_SCHEMA + '.' + c.TABLE_NAME, c.COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS c
    JOIN INFORMATION_SCHEMA.TABLES t 
      ON t.TABLE_NAME=c.TABLE_NAME AND t.TABLE_TYPE='BASE TABLE' -- avoid views
    WHERE c.DATA_TYPE IN ('varchar','nvarchar') -- searching only in these column types
    --AND c.COLUMN_NAME IN ('NAME','DESCRIPTION') -- searching only in these column names

SET @search='john'

OPEN curTabCol
FETCH NEXT FROM curTabCol INTO @table, @column

WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXECUTE('IF EXISTS 
             (SELECT * FROM ' + @table + ' WHERE ' + @column + ' = ''' + @search + ''') 
             PRINT ''' + @table + '.' + @column + '''')
    FETCH NEXT FROM curTabCol INTO @table, @column
END

CLOSE curTabCol
DEALLOCATE curTabCol

Reading a string with scanf

I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

char str[]  
  1. array of values of type char, with its own address in memory
  2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
  3. including termination null character '\0' &str, &str[0] and str, all three represent the same location in memory which is address of the first element of the array str

    char *strPtr = &str[0]; //declaration and initialization

alternatively, you can split this in two:

char *strPtr; strPtr = &str[0];
  1. strPtr is a pointer to a char
  2. strPtr points at array str
  3. strPtr is a variable with its own address in memory
  4. strPtr is a variable that stores value of address &str[0]
  5. strPtr own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
  6. &strPtr represents the address of strPtr itself

I think that you could declare a pointer to a pointer as:

char **vPtr = &strPtr;  

declares and initializes with address of strPtr pointer

Alternatively you could split in two:

char **vPtr;
*vPtr = &strPtr
  1. *vPtr points at strPtr pointer
  2. *vPtr is a variable with its own address in memory
  3. *vPtr is a variable that stores value of address &strPtr
  4. final comment: you can not do str++, str address is a const, but you can do strPtr++

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

@GeneratedValue(strategy=GenerationType.IDENTITY), adding this annotation to the primary key property in your entity bean should solve this issue.

Finding multiple occurrences of a string within a string in Python

This version should be linear in length of the string, and should be fine as long as the sequences aren't too repetitive (in which case you can replace the recursion with a while loop).

def find_all(st, substr, start_pos=0, accum=[]):
    ix = st.find(substr, start_pos)
    if ix == -1:
        return accum
    return find_all(st, substr, start_pos=ix + 1, accum=accum + [ix])

bstpierre's list comprehension is a good solution for short sequences, but looks to have quadratic complexity and never finished on a long text I was using.

findall_lc = lambda txt, substr: [n for n in xrange(len(txt))
                                   if txt.find(substr, n) == n]

For a random string of non-trivial length, the two functions give the same result:

import random, string; random.seed(0)
s = ''.join([random.choice(string.ascii_lowercase) for _ in range(100000)])

>>> find_all(s, 'th') == findall_lc(s, 'th')
True
>>> findall_lc(s, 'th')[:4]
[564, 818, 1872, 2470]

But the quadratic version is about 300 times slower

%timeit find_all(s, 'th')
1000 loops, best of 3: 282 µs per loop

%timeit findall_lc(s, 'th')    
10 loops, best of 3: 92.3 ms per loop

How to fix IndexError: invalid index to scalar variable

In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.

React-router urls don't work when refreshing or writing manually

I know this question has been answered to the death, but it doesn't solve the problem where you want to use your browser router with proxy pass, where you can't use root.

For me the solution is pretty simple.

say you have a url that's pointing to some port.

location / {
  proxy_pass http://127.0.0.1:30002/;
  proxy_set_header    Host            $host;
  port_in_redirect    off;
}

and now because of the browser router sub paths are broken. However you know what the sub paths are.

The solution to this? For sub path /contact

# just copy paste.
location /contact/ {
  proxy_pass http://127.0.0.1:30002/;
  proxy_set_header    Host            $host;
}

Nothing else I've tried works, but this simple fix works like a damn charm.

Remove non-ascii character in string

You can use the following regex to replace non-ASCII characters

str = str.replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')

However, note that spaces, colons and commas are all valid ASCII, so the result will be

> str
"INFO] :, , ,  (Higashikurume)"

Create a Maven project in Eclipse complains "Could not resolve archetype"

I fixed this problem by following the solution to this other StackOverflow question

I had the same problem. I fixed it by adding the maven archetype catalog to eclipse. Steps are provided below: (Please note the https protocol)

  1. Open Window > Preferences
  2. Open Maven > Archetypes
  3. Click 'Add Remote Catalog' and add the following:

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

How to find the lowest common ancestor of two nodes in any binary tree?

Here is the working code in JAVA

public static Node LCA(Node root, Node a, Node b) {
   if (root == null) {
       return null;
   }

   // If the root is one of a or b, then it is the LCA
   if (root == a || root == b) {
       return root;
   }

   Node left = LCA(root.left, a, b);
   Node right = LCA(root.right, a, b);

   // If both nodes lie in left or right then their LCA is in left or right,
   // Otherwise root is their LCA
   if (left != null && right != null) {
      return root;
   }

   return (left != null) ? left : right; 
}

How to make the HTML link activated by clicking on the <li>?

Use jQuery so you don't have to write inline javascript on <li> element:

$(document).ready(function(){
    $("li > a").each(function(index, value) {
        var link = $(this).attr("href");
        $(this).parent().bind("click", function() {
            location.href = link;
        });
    });
}); 

How do I join two lists in Java?

public class TestApp {

/**
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Hi");
    Set<List<String>> bcOwnersList = new HashSet<List<String>>();
    List<String> bclist = new ArrayList<String>();
    List<String> bclist1 = new ArrayList<String>();
    List<String> object = new ArrayList<String>();
    object.add("BC11");
    object.add("C2");
    bclist.add("BC1");
    bclist.add("BC2");
    bclist.add("BC3");
    bclist.add("BC4");
    bclist.add("BC5");
    bcOwnersList.add(bclist);
    bcOwnersList.add(object);

    bclist1.add("BC11");
    bclist1.add("BC21");
    bclist1.add("BC31");
    bclist1.add("BC4");
    bclist1.add("BC5");

    List<String> listList= new ArrayList<String>();
    for(List<String> ll : bcOwnersList){
        listList = (List<String>) CollectionUtils.union(listList,CollectionUtils.intersection(ll, bclist1));
    }
    /*for(List<String> lists : listList){
        test = (List<String>) CollectionUtils.union(test, listList);
    }*/
    for(Object l : listList){
        System.out.println(l.toString());
    }
    System.out.println(bclist.contains("BC"));

}

}

Disable browser cache for entire ASP.NET website

You can try below code in Global.asax file.

protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
    }

Sending simple message body + file attachment using Linux Mailx

The best way is to use mpack!

mpack -s "Subject" -d "./body.txt" "././image.png" mailadress

mpack - subject - body - attachment - mailadress

How to remove a web site from google analytics

After Much Fannying about, deleting this that etc, I found the way to delete a "website" from your list (which is, in fact what the original question was - minus all the flaffing) is

  • Select the Account (Website) that you want to delete
  • In the first column (left hand one)
  • Click Account Settings
  • Down the bottom, it says Delete this account.

That's it… Done.

Remember: for this exercise only Account means Website.

Measure the time it takes to execute a t-sql query

even better, this will measure the average of n iterations of your query! Great for a more accurate reading.

declare @tTOTAL int = 0
declare @i integer = 0
declare @itrs integer = 100

while @i < @itrs
begin
declare @t0 datetime = GETDATE()

--your query here

declare @t1 datetime = GETDATE()

set @tTotal = @tTotal + DATEDIFF(MICROSECOND,@t0,@t1)

set @i = @i + 1
end

select @tTotal/@itrs

How to get index in Handlebars each helper?

In handlebar version 3.0 onwards,

{{#each users as |user userId|}}
  Id: {{userId}} Name: {{user.name}}
{{/each}}

In this particular example, user will have the same value as the current context and userId will have the index value for the iteration. Refer - http://handlebarsjs.com/block_helpers.html in block helpers section

Dynamic Web Module 3.0 -- 3.1

I had similar troubles in eclipse and the only way to fix it for me was to

  • Remove the web module
  • Apply
  • Change the module version
  • Add the module
  • Configure (Further configuration available link at the bottom of the dialog)
  • Apply

Just make sure you configure the web module before applying it as by default it will look for your web files in /WebContent/ and this is not what Maven project structure should be.

EDIT:

Here is a second way in case nothing else helps

  • Exit eclipse, go to your project in the file system, then to .settings folder.
  • Open the org.eclipse.wst.common.project.facet.core.xml , make backup, and remove the web module entry.
  • You can also modify the web module version there, but again, no guarantees.

Regular Expression - 2 letters and 2 numbers in C#

This should get you for starting with two letters and ending with two numbers.

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

[A-Za-z]{2}[0-9]{2}

What is the difference between a process and a thread?

Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.

I'm not sure what "hardware" vs "software" threads you might be referring to. Threads are an operating environment feature, rather than a CPU feature (though the CPU typically has operations that make threads efficient).

Erlang uses the term "process" because it does not expose a shared-memory multiprogramming model. Calling them "threads" would imply that they have shared memory.

ImportError: No module named 'selenium'

Even though the egg file may be present, that does not necessarily mean that it is installed. Check out this previous answer for some hint:

How to install Selenium WebDriver on Mac OS

How to use CSS to surround a number with a circle?

Late to the party, but here is a bootstrap-only solution that has worked for me. I'm using Bootstrap 4:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<body>_x000D_
<div class="row mt-4">_x000D_
<div class="col-md-12">_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">1</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">2</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">3</span>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

You basically add bg-dark text-white rounded-circle px-3 py-1 mx-2 h3 classes to your <span> (or whatever) element and you're done.

Note that you might need to adjust margin and padding classes if your content has more than one digits.

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

You have to add a MySQL jdbc driver to the classpath.

Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.

You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27

Maintain/Save/Restore scroll position when returning to a ListView

A very simple way:

/** Save the position **/
int currentPosition = listView.getFirstVisiblePosition();

//Here u should save the currentPosition anywhere

/** Restore the previus saved position **/
listView.setSelection(savedPosition);

The method setSelection will reset the list to the supplied item. If not in touch mode the item will actually be selected if in touch mode the item will only be positioned on screen.

A more complicated approach:

listView.setOnScrollListener(this);

//Implements the interface:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
    mCurrentX = view.getScrollX();
    mCurrentY = view.getScrollY();
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {

}

//Save anywere the x and the y

/** Restore: **/
listView.scrollTo(savedX, savedY);

A valid provisioning profile for this executable was not found... (again)

Xcode5 has broken this again (congratulations to Apple for failing to bother testing one of their buggiest bits of code. Again).

A new way to break/fix it:

If you have:

  1. An old profile on your device (team profile, or non-team profile)
  2. A new profile generated automatically on the App Store, by any copy of Xcode5, even if it's simply an update to the profile you already had
  3. (NB: if any colleague adds themself to the profile, this triggers the above "change")
  4. You use the new "Accounts" dialog to download profiles (NB: this is now REQUIRED by Apple for various situations - all other approaches, including manual download, appear to be unsupported. Even though the Apple Developer site TELLS YOU TO MANUALLY DOWNLOAD! Don't do it! It breaks Xcode5!)
  5. Xcode5 will INCORRECTLY hide AND RENAME that profile in the drop-down selector in Build Settings
  6. (I detest this drop-down. Some idiot at Apple keeps removing information from it, and someone else keeps adding it back, it flip-flops between Xcode point releases. WHY??!?!)
  7. There is NO WAY you can select the correct profile - whatever you select, Xcode5 will use the wrong one

The solution is easy enough. The "Apple engineering are lazy" solution:

  1. Go to Xcode5 -> Window -> Organizer -> Devices
  2. Select your device
  3. Select provisioning profiles
  4. Delete everything relating to your current project and/or Team (even other projects, if necessary - they can all be downloaded later if still needed!)
  5. Re-build.
  6. You should get an error from Xcode5 that the profile doesn't exist. Even though you manually had seleted the profile that was ALREADY PRESENT on your machine (yep - that dropdown is buggy again. It lies about the profile it selects behind the scenes!)
  7. In the profile selector, select the "real" profile
  8. Build, run - success!

How to write an inline IF statement in JavaScript?

inline if:

(('hypothesis') ? 'truthy conclusion' : 'falsey conclusion')

truthy conclusion: statements executed when hypothesis is true

falsey conclusion: statements executed when hypothesis is false

your example:

var c = ((a < b) ? 'a<b statements' : '!(a<b) statements');

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

GROUP BY without aggregate function

I know you said you want to understand group by if you have data like this:

COL-A  COL-B  COL-C  COL-D
  1      Ac      C1     D1
  2      Bd      C2     D2
  3      Ba      C1     D3
  4      Ab      C1     D4
  5      C       C2     D5

And you want to make the data appear like:

COL-A  COL-B  COL-C  COL-D
  4      Ab      C1     D4
  1      Ac      C1     D1
  3      Ba      C1     D3
  2      Bd      C2     D2
  5      C       C2     D5

You use:

select * from table_name
order by col-c,colb

Because I think this is what you intend to do.

Nesting CSS classes

Not possible with vanilla CSS. However you can use something like:

Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Or

Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.

Example:

#header {
  color: red;
  a {
    font-weight: bold;
    text-decoration: none;
  }
}

How to remove special characters from a string?

You can remove single char as follows:

String str="+919595354336";

 String result = str.replaceAll("\\\\+","");

 System.out.println(result);

OUTPUT:

919595354336

Center a DIV horizontally and vertically

You want to set style

margin: auto;

And remove the positioning styles (top, left, position)

I know this will center horrizontaly but I'm not sure about vertical!

Filter by Dates in SQL

WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))

How do you find the current user in a Windows environment?

Just type whoami in command prompt and you'll get the current username.

nginx- duplicate default server error

In my case junk files from editor caused the problem. I had a config as below:

#...
http {
 # ...
 include ../sites/*;
}

In the ../sites directory initially I had a default.config file. However, by mistake I saved duplicate files as default.config.save and default.config.save.1. Removing them resolved the issue.

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

Lambda function in list comprehensions

The first one creates a single lambda function and calls it ten times.

The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:

[(lambda x: x*x)(x) for x in range(10)]

Or better yet:

[x*x for x in range(10)]

Is there a difference between PhoneGap and Cordova commands?

Late answer but I think this might be useful.

There are differences between the two cli, phonegapis a command that encapsulates cordova. In the create case the only difference is an overriden default app

In some other cases the difference is much more significant. For instance phonegap build comes with a remote build functionality while cordova build only supports local builds.

A big limitation I found to PhoneGap is that, AFAIK, you can only build a release APK using the PhoneGap Build service. On Cordova you can build with cordova build android --release.

JavaScript isset() equivalent

I always use this generic function to prevent errrors on primitive variables as well as arrays and objects.

isset = function(obj) {
  var i, max_i;
  if(obj === undefined) return false;
  for (i = 1, max_i = arguments.length; i < max_i; i++) {
    if (obj[arguments[i]] === undefined) {
        return false;
    }
    obj = obj[arguments[i]];
  }
  return true;
};

console.log(isset(obj));                   // returns false
var obj = 'huhu';
console.log(isset(obj));                   // returns true
obj = {hallo:{hoi:'hoi'}};
console.log(isset(obj, 'niet'));           // returns false
console.log(isset(obj, 'hallo'));          // returns true
console.log(isset(obj, 'hallo', 'hallo')); // returns false
console.log(isset(obj, 'hallo', 'hoi'));   // returns true

How can I trigger a Bootstrap modal programmatically?

The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.

See this code snippet with preview: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba

Summary:

let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";

//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
    row.addEventListener('click', e => {
        //Set parameteres (clone row dataset)
        exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
        //Button click simulation
        //Now we can use relatedTarget
        exampleButton.click();
    })
});

All this is to use the relatedTarget property. (See Bootstrap docs)

Adding to a vector of pair

IMHO, a very nice solution is to use c++11 emplace_back function:

revenue.emplace_back("string", map[i].second);

It just creates a new element in place.

What are the use cases for selecting CHAR over VARCHAR in SQL?

I think in your case there is probably no reason to not pick Varchar. It gives you flexibility and as has been mentioned by a number of respondants, performance is such now that except in very specific circumstances us meer mortals (as opposed to Google DBA's) will not notice the difference.

An interesting thing worth noting when it comes to DB Types is the sqlite (a popular mini database with pretty impressive performance) puts everything into the database as a string and types on the fly.

I always use VarChar and usually make it much bigger than I might strickly need. Eg. 50 for Firstname, as you say why not just to be safe.

How can two strings be concatenated?

You can create you own operator :

'%&%' <- function(x, y)paste0(x,y)
"new" %&% "operator"
[1] newoperator`

You can also redefine 'and' (&) operator :

'&' <- function(x, y)paste0(x,y)
"dirty" & "trick"
"dirtytrick"

messing with baseline syntax is ugly, but so is using paste()/paste0() if you work only with your own code you can (almost always) replace logical & and operator with * and do multiplication of logical values instead of using logical 'and &'

dynamic_cast and static_cast in C++

dynamic_cast uses RTTI. It can slow down your application, you can use modification of the visitor design pattern to achieve downcasting without RTTI http://arturx64.github.io/programming-world/2016/02/06/lazy-visitor.html

Fixing broken UTF-8 encoding

I know this isn't very elegant, but after it was mentioned that the strings may be double encoded, I made this function:

function fix_double encoding($string)
{
    $utf8_chars = explode(' ', 'À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö');
    $utf8_double_encoded = array();
    foreach($utf8_chars as $utf8_char)
    {
            $utf8_double_encoded[] = utf8_encode(utf8_encode($utf8_char));
    }
    $string = str_replace($utf8_double_encoded, $utf8_chars, $string);
    return $string;
}

This seems to work perfectly to remove the double encoding I am experiencing. I am probably missing some of the characters that could be an issue to others. However, for my needs it is working perfectly.

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

Is it possible to listen to a "style change" event?

I think the best answer if from Mike in the case you can't launch your event because is not from your code. But I get some errors when I used it. So I write a new answer for show you the code that I use.

Extension

// Extends functionality of ".css()"
// This could be renamed if you'd like (i.e. "$.fn.cssWithListener = func ...")
(function() {
    orig = $.fn.css;
    $.fn.css = function() {
        var result = orig.apply(this, arguments);
        $(this).trigger('stylechanged');
        return result;
    }
})();

Usage

// Add listener
$('element').on('stylechanged', function () {
    console.log('css changed');
});

// Perform change
$('element').css('background', 'red');

I got error because var ev = new $.Event('style'); Something like style was not defined in HtmlDiv.. I removed it, and I launch now $(this).trigger("stylechanged"). Another problem was that Mike didn't return the resulto of $(css, ..) then It can make problems in some cases. So I get the result and return it. Now works ^^ In every css change include from some libs that I can't modify and trigger an event.

Retrieving Android API version programmatically

I improved code i used

public static float getAPIVerison() {

    float f=1f;
    try {
        StringBuilder strBuild = new StringBuilder();
        strBuild.append(android.os.Build.VERSION.RELEASE.substring(0, 2));
        f= Float.valueOf(strBuild.toString());
    } catch (NumberFormatException e) {
        Log.e("myApp", "error retriving api version" + e.getMessage());
    }

    return f;
}

C dynamically growing array

These posts apparently are in the wrong order! This is #1 in a series of 3 posts. Sorry.

In attempting to use Lie Ryan's code, I had problems retrieving stored information. The vector's elements are not stored contiguously,as you can see by "cheating" a bit and storing the pointer to each element's address (which of course defeats the purpose of the dynamic array concept) and examining them.

With a bit of tinkering, via:

ss_vector* vector; // pull this out to be a global vector

// Then add the following to attempt to recover stored values.

int return_id_value(int i,apple* aa) // given ptr to component,return data item
{   printf("showing apple[%i].id = %i and  other_id=%i\n",i,aa->id,aa->other_id);
    return(aa->id);
}

int Test(void)  // Used to be "main" in the example
{   apple* aa[10]; // stored array element addresses
    vector = ss_init_vector(sizeof(apple));
    // inserting some items
    for (int i = 0; i < 10; i++)
    {   aa[i]=init_apple(i);
        printf("apple id=%i and  other_id=%i\n",aa[i]->id,aa[i]->other_id);
        ss_vector_append(vector, aa[i]);
     }   
 // report the number of components
 printf("nmbr of components in vector = %i\n",(int)vector->size);
 printf(".*.*array access.*.component[5] = %i\n",return_id_value(5,aa[5]));
 printf("components of size %i\n",(int)sizeof(apple));
 printf("\n....pointer initial access...component[0] = %i\n",return_id_value(0,(apple *)&vector[0]));
 //.............etc..., followed by
 for (int i = 0; i < 10; i++)
 {   printf("apple[%i].id = %i at address %i, delta=%i\n",i,    return_id_value(i,aa[i]) ,(int)aa[i],(int)(aa[i]-aa[i+1]));
 }   
// don't forget to free it
ss_vector_free(vector);
return 0;
}

It's possible to access each array element without problems, as long as you know its address, so I guess I'll try adding a "next" element and use this as a linked list. Surely there are better options, though. Please advise.

range() for floats

Why Is There No Floating Point Range Implementation In The Standard Library?

As made clear by all the posts here, there is no floating point version of range(). That said, the omission makes sense if we consider that the range() function is often used as an index (and of course, that means an accessor) generator. So, when we call range(0,40), we're in effect saying we want 40 values starting at 0, up to 40, but non-inclusive of 40 itself.

When we consider that index generation is as much about the number of indices as it is their values, the use of a float implementation of range() in the standard library makes less sense. For example, if we called the function frange(0, 10, 0.25), we would expect both 0 and 10 to be included, but that would yield a generator with 41 values, not the 40 one might expect from 10/0.25.

Thus, depending on its use, an frange() function will always exhibit counter intuitive behavior; it either has too many values as perceived from the indexing perspective or is not inclusive of a number that reasonably should be returned from the mathematical perspective. In other words, it's easy to see how such a function would appear to conflate two very different use cases – the naming implies the indexing use case; the behavior implies a mathematical one.

The Mathematical Use Case

With that said, as discussed in other posts, numpy.linspace() performs the generation from the mathematical perspective nicely:

numpy.linspace(0, 10, 41)
array([  0.  ,   0.25,   0.5 ,   0.75,   1.  ,   1.25,   1.5 ,   1.75,
         2.  ,   2.25,   2.5 ,   2.75,   3.  ,   3.25,   3.5 ,   3.75,
         4.  ,   4.25,   4.5 ,   4.75,   5.  ,   5.25,   5.5 ,   5.75,
         6.  ,   6.25,   6.5 ,   6.75,   7.  ,   7.25,   7.5 ,   7.75,
         8.  ,   8.25,   8.5 ,   8.75,   9.  ,   9.25,   9.5 ,   9.75,  10.
])

The Indexing Use Case

And for the indexing perspective, I've written a slightly different approach with some tricksy string magic that allows us to specify the number of decimal places.

# Float range function - string formatting method
def frange_S (start, stop, skip = 1.0, decimals = 2):
    for i in range(int(start / skip), int(stop / skip)):
        yield float(("%0." + str(decimals) + "f") % (i * skip))

Similarly, we can also use the built-in round function and specify the number of decimals:

# Float range function - rounding method
def frange_R (start, stop, skip = 1.0, decimals = 2):
    for i in range(int(start / skip), int(stop / skip)):
        yield round(i * skip, ndigits = decimals)

A Quick Comparison & Performance

Of course, given the above discussion, these functions have a fairly limited use case. Nonetheless, here's a quick comparison:

def compare_methods (start, stop, skip):

    string_test  = frange_S(start, stop, skip)
    round_test   = frange_R(start, stop, skip)

    for s, r in zip(string_test, round_test):
        print(s, r)

compare_methods(-2, 10, 1/3)

The results are identical for each:

-2.0 -2.0
-1.67 -1.67
-1.33 -1.33
-1.0 -1.0
-0.67 -0.67
-0.33 -0.33
0.0 0.0
...
8.0 8.0
8.33 8.33
8.67 8.67
9.0 9.0
9.33 9.33
9.67 9.67

And some timings:

>>> import timeit

>>> setup = """
... def frange_s (start, stop, skip = 1.0, decimals = 2):
...     for i in range(int(start / skip), int(stop / skip)):
...         yield float(("%0." + str(decimals) + "f") % (i * skip))
... def frange_r (start, stop, skip = 1.0, decimals = 2):
...     for i in range(int(start / skip), int(stop / skip)):
...         yield round(i * skip, ndigits = decimals)
... start, stop, skip = -1, 8, 1/3
... """

>>> min(timeit.Timer('string_test = frange_s(start, stop, skip); [x for x in string_test]', setup=setup).repeat(30, 1000))
0.024284090992296115

>>> min(timeit.Timer('round_test = frange_r(start, stop, skip); [x for x in round_test]', setup=setup).repeat(30, 1000))
0.025324633985292166

Looks like the string formatting method wins by a hair on my system.

The Limitations

And finally, a demonstration of the point from the discussion above and one last limitation:

# "Missing" the last value (10.0)
for x in frange_R(0, 10, 0.25):
    print(x)

0.25
0.5
0.75
1.0
...
9.0
9.25
9.5
9.75

Further, when the skip parameter is not divisible by the stop value, there can be a yawning gap given the latter issue:

# Clearly we know that 10 - 9.43 is equal to 0.57
for x in frange_R(0, 10, 3/7):
    print(x)

0.0
0.43
0.86
1.29
...
8.14
8.57
9.0
9.43

There are ways to address this issue, but at the end of the day, the best approach would probably be to just use Numpy.

WCF timeout exception detailed investigation

I'm having a very similar problem. In the past, this has been related to serialization problems. If you are still having this problem, can you verify that you can correctly serialize the objects you are returning. Specifically, if you are using Linq-To-Sql objects that have relationships, there are known serialization problems if you put a back reference on a child object to the parent object and mark that back reference as a DataMember.

You can verify serialization by writing a console app that serializes and deserializes your objects using the DataContractSerializer on the server side and whatever serialization methods your client uses. For example, in our current application, we have both WPF and Compact Framework clients. I wrote a console app to verify that I can serialize using a DataContractSerializer and deserialize using an XmlDesserializer. You might try that.

Also, if you are returning Linq-To-Sql objects that have child collections, you might try to ensure that you have eagerly loaded them on the server side. Sometimes, because of lazy loading, the objects being returned are not populated and may cause the behavior you are seeing where the request is sent to the service method multiple times.

If you have solved this problem, I'd love to hear how because I'm stuck with it too. I have verified that my issue is not serialization so I'm at a loss.

UPDATE: I'm not sure if it will help you any but the Service Trace Viewer Tool just solved my problem after 5 days of very similar experience to yours. By setting up tracing and then looking at the raw XML, I found the exceptions that were causing my serialization problems. It was related to Linq-to-SQL objects that occasionally had more child objects than could be successfully serialized. Adding the following to your web.config file should enable tracing:

<sharedListeners>
    <add name="sharedListener"
         type="System.Diagnostics.XmlWriterTraceListener"
         initializeData="c:\Temp\servicetrace.svclog" />
  </sharedListeners>
  <sources>
    <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" >
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
  </sources>

The resulting file can be opened with the Service Trace Viewer Tool or just in IE to examine the results.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

You would mostly be using COUNT to summarize over a UID. Therefore

COUNT([uid]) will produce the warning:

Warning: Null value is eliminated by an aggregate or other SET operation.

whilst being used with a left join, where the counted object does not exist.

Using COUNT(*) in this case would also render incorrect results, as you would then be counting the total number of results (ie parents) that exist.

Using COUNT([uid]) IS a valid way of counting, and the warning is nothing more than a warning. However if you are concerned, and you want to get a true count of uids in this case then you could use:

SUM(CASE WHEN [uid] IS NULL THEN 0 ELSE 1 END) AS [new_count]

This would not add a lot of overheads to your query. (tested mssql 2008)

How to iterate through an ArrayList of Objects of ArrayList of Objects?

for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);

Implementing multiple interfaces with Java - is there a way to delegate?

Unfortunately: NO.

We're all eagerly awaiting the Java support for extension methods

Access Enum value using EL with JSTL

Add a method to the enum like:

public String getString() {
    return this.name();
}

For example

public enum MyEnum {
    VALUE_1,
    VALUE_2;
    public String getString() {
        return this.name();
    }
}

Then you can use:

<c:if test="${myObject.myEnumProperty.string eq 'VALUE_2'}">...</c:if>

Trigger css hover with JS

I know what you're trying to do, but why not simply do this:

$('div').addClass('hover');

The class is already defined in your CSS...

As for you original question, this has been asked before and it is not possible unfortunately. e.g. http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover

However, your desired functionality may be possible if your Stylesheet is defined in Javascript. see: http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/

Hope this helps!

How to set HttpResponse timeout for Android in Java

An option is to use the OkHttp client, from Square.

Add the library dependency

In the build.gradle, include this line:

compile 'com.squareup.okhttp:okhttp:x.x.x'

Where x.x.x is the desired library version.

Set the client

For example, if you want to set a timeout of 60 seconds, do this way:

final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES. So, you can simply use:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);

For more details about the units, see TimeUnit.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

The JDK has switched locations of java.exe between 1.6 and 1.7!!!

In my case I found that the JAVA_HOME for the JDK had to add the \jre on the end. The mvn bat file is looking for java.exe and it looks for it in JAVA_HOME\bin. Its not there for JDK 1.7; it is in JAVA_HOME\jre\bin. In JDK 1.6 such it IS in JAVA_HOME\bin.

Hope this helps somebody.

Transparent CSS background color

yes, thats possible. just use the rgba-syntax for your background-color.

.menue{
  background-color: rgba(255, 0, 0, 0.5); //semi-transparent red
}

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

Solution: Edit and save the file!

From VisualStudio go to the View and expand to see it's resx file

Right-click menu select OpenWith... XML (Text) Editor.

Just add a space at the end and save.

What is "pom" packaging in maven?

To simply answer your question when you do a mvn:install, maven will create a packaged artifact based on (packaging attribute in pom.xml), After you run your maven install you can find the file with .package extension

  • In target directory of the project workspace
  • Also where your maven 2 local repository is search for (.m2/respository) on your box, Your artifact is listed in .m2 repository under (groupId/artifactId/artifactId-version.packaging) directory
  • If you look under the directory you will find packaged extension file and also pom extension (pom extension is basically the pom.xml used to generate this package)
  • If your maven project is multi-module each module will two files as described above except for the top level project that will only have a pom

Adding a simple spacer to twitter bootstrap

In Bootstrap 4 you can use classes like mt-5, mb-5, my-5, mx-5 (y for both top and bottom, x for both left and right).

According to their site:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Link: https://getbootstrap.com/docs/4.0/utilities/spacing/

How to convert PDF files to images

As for 2018 there is still not a simple answer to the question of how to convert a PDF document to an image in C#; many libraries use Ghostscript licensed under AGPL and in most cases an expensive commercial license is required for production use.

A good alternative might be using the popular 'pdftoppm' utility which has a GPL license; it can be used from C# as command line tool executed with System.Diagnostics.Process. Popular tools are well known in the Linux world, but a windows build is also available.

If you don't want to integrate pdftoppm by yourself, you can use my PdfRenderer popular wrapper (supports both classic .NET Framework and .NET Core) - it is not free, but pricing is very affordable.

How can I represent an infinite number in Python?

In python2.x there was a dirty hack that served this purpose (NEVER use it unless absolutely necessary):

None < any integer < any string

Thus the check i < '' holds True for any integer i.

It has been reasonably deprecated in python3. Now such comparisons end up with

TypeError: unorderable types: str() < int()

How can I get the current directory name in Javascript?

window.location.pathname will get you the directory, as well as the page name. You could then use .substring() to get the directory:

var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));

Hope this helps!

Stylesheet not updating

Most probably the file is just being cached by the server. You could either disable cache (but remember to enable it when the site goes live), or modify href of your link tag, so the server will not load it from cache.

If your page is created dynamically by some language like php, you could add some variable at the end of the href value, like:

    <link rel="stylesheet" type="text/css" href="css/yourStyles.css?<?php echo time(); ?>" />

That will add the current timestamp on the end of a file path, so it will always be unique and never loaded from cache.

If your page is static, you have to manage those variables yourself, so use something like:

    <link rel="stylesheet" type="text/css" href="css/yourStyles.css?version=1" />

after doing some changes in the file content, change version=1 to version=2 and so on.

If you wish to disable the cache from caching css files, refer to your server type documentation (it's done differently on apache, IIS, nginx etc.) or ask/search for a question on https://serverfault.com/

Assuming IIS - adding the key under with the right settings in the root or the relevant folder does the trick.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <caching enabled="false" enableKernelCache="false" /> <!-- This one -->
    </system.webServer>
</configuration>

That said sometimes one still has to recycle the Application Pool to "bump" the CSS. Therefore: Disabling IIS caching alone is not a 100% guaranteed solution.

For the browser: There are some notes on fine-grain controlling the local cache on FF over on SuperUser for the interested.

How to Consume WCF Service with Android

If I were doing this I would probably use WCF REST on the server and a REST library on the Java/Android client.

How to add a vertical Separator?

This should do exactly what the author wanted:

<StackPanel Orientation="Horizontal">
    <Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />            
</StackPanel>

if you want a horizontal separator, change the Orientation of the StackPanel to Vertical.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

You can also change the pop-up options themselves, to be more convenient for your normal use. Summary:

  1. Run the SQL Management Studio Express 2008
  2. Click the Tools -> Options
  3. Select SQL Server Object Explorer . Now you should be able to see the options

    • Value for Edit Top Rows Command
    • Value for Select Top Rows Command
  4. Give the Values 0 here to select/ Edit all the Records

Full Instructions with screenshots are here: http://m-elshazly.blogspot.com/2011/01/sql-server-2008-change-edit-top-200.html

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

Given final block not properly padded

This can also be a issue when you enter wrong password for your sign key.

How to use bootstrap datepicker

I believe you have to reference bootstrap.js before bootstrap-datepicker.js

Disable button in WPF?

This should do it:

<StackPanel>
    <TextBox x:Name="TheTextBox" />
    <Button Content="Click Me">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="IsEnabled" Value="True" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

How to convert a Map to List in Java?

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("java", 20);
    map.put("C++", 45);

    Set <Entry<String, Integer>> set = map.entrySet();

    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);

we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

Maybe this might help you. I added Shell32.lib to my Linker --> Input --> Additional Dependencies and it stopped this error. I found out about it from this post: https://discourse.libsdl.org/t/windows-build-fails-with-missing-symbol-imp-commandlinetoargvw/27256/3

What is the maximum value for an int32?

It's about 2.1 * 10^9. No need to know the exact 2^{31} - 1 = 2,147,483,647.

C

You can find it in C like that:

#include <stdio.h>
#include <limits.h>

main() {
    printf("max int:\t\t%i\n", INT_MAX);
    printf("max unsigned int:\t%u\n", UINT_MAX);
}

gives (well, without the ,)

max int:          2,147,483,647
max unsigned int: 4,294,967,295

C++ 11

std::cout << std::numeric_limits<int>::max() << "\n";
std::cout << std::numeric_limits<unsigned int>::max() << "\n";

Java

You can get this with Java, too:

System.out.println(Integer.MAX_VALUE);

But keep in mind that Java integers are always signed.

Python 2

Python has arbitrary precision integers. But in Python 2, they are mapped to C integers. So you can do this:

import sys
sys.maxint
>>> 2147483647
sys.maxint + 1
>>> 2147483648L

So Python switches to long when the integer gets bigger than 2^31 -1

gcc-arm-linux-gnueabi command not found

fixed, using:

sudo apt-get install gcc-arm*

How to run ssh-add on windows?

If you are trying to setup a key for using git with ssh, there's always an option to add a configuration for the identity file.

vi ~/.ssh/config

Host example.com
IdentityFile ~/.ssh/example_key

How to get directory size in PHP

Thanks to Jonathan Sampson, Adam Pierce and Janith Chinthana I did this one checking for most performant way to get the directory size. Should work on Windows and Linux Hosts.

static function getTotalSize($dir)
{
    $dir = rtrim(str_replace('\\', '/', $dir), '/');

    if (is_dir($dir) === true) {
        $totalSize = 0;
        $os        = strtoupper(substr(PHP_OS, 0, 3));
        // If on a Unix Host (Linux, Mac OS)
        if ($os !== 'WIN') {
            $io = popen('/usr/bin/du -sb ' . $dir, 'r');
            if ($io !== false) {
                $totalSize = intval(fgets($io, 80));
                pclose($io);
                return $totalSize;
            }
        }
        // If on a Windows Host (WIN32, WINNT, Windows)
        if ($os === 'WIN' && extension_loaded('com_dotnet')) {
            $obj = new \COM('scripting.filesystemobject');
            if (is_object($obj)) {
                $ref       = $obj->getfolder($dir);
                $totalSize = $ref->size;
                $obj       = null;
                return $totalSize;
            }
        }
        // If System calls did't work, use slower PHP 5
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir));
        foreach ($files as $file) {
            $totalSize += $file->getSize();
        }
        return $totalSize;
    } else if (is_file($dir) === true) {
        return filesize($dir);
    }
}

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

The number of possible binary search tree with n nodes (elements,items) is

=(2n C n) / (n+1) = ( factorial (2n) / factorial (n) * factorial (2n - n) ) / ( n + 1 ) 

where 'n' is number of nodes  (elements,items ) 

Example :

for 
n=1 BST=1,
n=2 BST 2,
n=3 BST=5,
n=4 BST=14 etc

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Target WSGI script cannot be loaded as Python module

I had similar issue eg apache log error "wsgi.py cannot be loaded as Python module."

It turned out I had to stop and then start apache instead of just restarting it.

UML diagram shapes missing on Visio 2013

Microsoft Visio 2013 Standard Edition does not provide UML shapes, you have to upgrade to Microsoft Visio 2013 Professional.

Visio 2013 Professional

Eloquent - where not equal to

Use where with a != operator in combination with whereNull

Code::where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id')->get()

python: order a list of numbers without built-in sort, min, max function

l = [64, 25, 12, 22, 11, 1,2,44,3,122, 23, 34]

for i in range(len(l)):
    for j in range(i + 1, len(l)):

        if l[i] > l[j]:
           l[i], l[j] = l[j], l[i]

print l

Output:

[1, 2, 3, 11, 12, 22, 23, 25, 34, 44, 64, 122]

Return a value if no rows are found in Microsoft tSQL

SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value]

FROM Sites S

WHERE S.Id = @SiteId and S.Status = 1 AND 
      (S.WebUserId = @WebUserId OR S.AllowUploads = 1)

Colorizing text in the console with C++

On Windows 10 you may use escape sequences this way:

#ifdef _WIN32
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
// print in red and restore colors default
std::cout << "\033[32m" << "Error!" << "\033[0m" << std::endl;

Nodejs cannot find installed module on Windows

I ran into this issue on Windows 7, running

npm install -g gulp

as administrator while being logged on as a normal user.

Solution: When executing the same installation as normal user (not "run as admin" for cmd) all was fine. I guess it is related to the default install and search path.

iFrame src change event detection?

If you have no control over the page and wish to watch for some kind of change then the modern method is to use MutationObserver

An example of its use, watching for the src attribute to change of an iframe

_x000D_
_x000D_
new MutationObserver(function(mutations) {_x000D_
  mutations.some(function(mutation) {_x000D_
    if (mutation.type === 'attributes' && mutation.attributeName === 'src') {_x000D_
      console.log(mutation);_x000D_
      console.log('Old src: ', mutation.oldValue);_x000D_
      console.log('New src: ', mutation.target.src);_x000D_
      return true;_x000D_
    }_x000D_
_x000D_
    return false;_x000D_
  });_x000D_
}).observe(document.body, {_x000D_
  attributes: true,_x000D_
  attributeFilter: ['src'],_x000D_
  attributeOldValue: true,_x000D_
  characterData: false,_x000D_
  characterDataOldValue: false,_x000D_
  childList: false,_x000D_
  subtree: true_x000D_
});_x000D_
_x000D_
setTimeout(function() {_x000D_
  document.getElementsByTagName('iframe')[0].src = 'http://jsfiddle.net/';_x000D_
}, 3000);
_x000D_
<iframe src="http://www.google.com"></iframe>
_x000D_
_x000D_
_x000D_

Output after 3 seconds

MutationRecord {oldValue: "http://www.google.com", attributeNamespace: null, attributeName: "src", nextSibling: null, previousSibling: null…}
Old src:  http://www.google.com
New src:  http://jsfiddle.net/ 

On jsFiddle

Posted answer here as original question was closed as a duplicate of this one.

INSERT VALUES WHERE NOT EXISTS

You could do this using an IF statement:

IF NOT EXISTS 
    (   SELECT  1
        FROM    tblSoftwareTitles 
        WHERE   Softwarename = @SoftwareName 
        AND     SoftwareSystemType = @Softwaretype
    )
    BEGIN
        INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
        VALUES (@SoftwareName, @SoftwareType) 
    END;

You could do it without IF using SELECT

INSERT  tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
SELECT  @SoftwareName,@SoftwareType
WHERE   NOT EXISTS 
        (   SELECT  1
            FROM    tblSoftwareTitles 
            WHERE   Softwarename = @SoftwareName 
            AND     SoftwareSystemType = @Softwaretype
        );

Both methods are susceptible to a race condition, so while I would still use one of the above to insert, but you can safeguard duplicate inserts with a unique constraint:

CREATE UNIQUE NONCLUSTERED INDEX UQ_tblSoftwareTitles_Softwarename_SoftwareSystemType
    ON tblSoftwareTitles (SoftwareName, SoftwareSystemType);

Example on SQL-Fiddle


ADDENDUM

In SQL Server 2008 or later you can use MERGE with HOLDLOCK to remove the chance of a race condition (which is still not a substitute for a unique constraint).

MERGE tblSoftwareTitles WITH (HOLDLOCK) AS t
USING (VALUES (@SoftwareName, @SoftwareType)) AS s (SoftwareName, SoftwareSystemType) 
    ON s.Softwarename = t.SoftwareName 
    AND s.SoftwareSystemType = t.SoftwareSystemType
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (SoftwareName, SoftwareSystemType) 
    VALUES (s.SoftwareName, s.SoftwareSystemType);

Example of Merge on SQL Fiddle

Change the background color in a twitter bootstrap modal?

It gets a little bit more complicated if you want to add the background to a specific modal. One way of solving that is to add and call something like this function instead of showing the modal directly:

function showModal(selector) {
    $(selector).modal('show');
    $('.modal-backdrop').addClass('background-backdrop');
}

Any css can then be applied to the background-backdrop class.

Pass user defined environment variable to tomcat

You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:

-DAPP_MASTER_PASSWORD=foo

and in your code, write

System.getProperty("APP_MASTER_PASSWORD");

You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.

cmake and libpthread

target_compile_options solution above is wrong, it won't link the library.

Use:

SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

OR

target_link_libraries(XXX PUBLIC pthread)

OR

set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

Where is Python language used?

All the languages you've mentioned are Turing Complete, so in theory there is nothing one can do and another can't. In practice of course, there are differences, especially in productivity and efficiency. Compared to C, C++ and Java, which are static typed, Python is a dynamic language and can help you write the same code in significantly fewer lines. Python has a moto "batteries included", which means that the standard library offers all the things needed to build a complex application. Other languages would need external libraries for this. On top of this, since Python is an old and mature language (older than Java), many external libraries (for game development and scientific calculations just to mention a few) have been evolved. So Python can be used to program desktop applications and in fact in some cases more efficiently than other traditional languages.

Python is also a scripting language. This means that you can easily and quickly write scripts and simple tests with it.

More recently python is also used for web frameworks. Since there is a big code base and many python programmers, this was a logical thing to do. These web frameworks follow the practice mainly introduced by Ruby on Rails.

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

How do I read the source code of shell commands?

Direct links to source for some popular programs in coreutils:

Full list here.

MySQL dump by query

Dump a table using a where query:

mysqldump mydatabase mytable --where="mycolumn = myvalue" --no-create-info > data.sql

Dump an entire table:

mysqldump mydatabase mytable > data.sql

Notes:

  • Replace mydatabase, mytable, and the where statement with your desired values.
  • By default, mysqldump will include DROP TABLE and CREATE TABLE statements in its output. Therefore, if you wish to not delete all the data in your table when restoring from the saved data file, make sure you use the --no-create-info option.
  • You may need to add the appropriate -h, -u, and -p options to the example commands above in order to specify your desired database host, user, and password, respectively.

HTML5 Number Input - Always show 2 decimal places

This is the correct answer:

_x000D_
_x000D_
<input type="number" step="0.01" min="-9999999999.99" max="9999999999.99"/>
_x000D_
_x000D_
_x000D_

change the date format in laravel view page

You can use Carbon::createFromTimestamp

BLADE

{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}

:before and background-image... should it work?

@michi; define height in your before pseudo class

CSS:

#videos-part:before{
    width: 16px;
    content: " ";
    background-image: url(/img/border-left3.png);
    position: absolute;
    left: -16px;
    top: -6px;
    height:20px;
}

Dynamic classname inside ngClass in angular 2

more elegant solution is to use && (using NgFor and its first, its free to use ur own matching tho):

    <div 
        *ngFor="let day of days;
                let first = first;"
        class="day"
        [ngClass]="first && ('day--' + day)"
    </div>

will turn out as:

class="day day--monday"

Postgres integer arrays as parameters?

You can always use a properly formatted string. The trick is the formatting.

command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));

Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value)) or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.

In my case, my enumerated type has some values like 'value1', 'value2', 'value3', and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}'), and this works.

How do I access ViewBag from JS

ViewBag is server side code.
Javascript is client side code.

You can't really connect them.

You can do something like this:

var x = $('#' + '@(ViewBag.CC)').val();

But it will get parsed on the server, so you didn't really connect them.

Batch file to perform start, run, %TEMP% and delete all

del won't trigger any dialogs or message boxes. You have a few problems, though:

  1. start will just open Explorer which would be useless. You need cd to change the working directory of your batch file (the /D is there so it also works when run from a different drive):

    cd /D %temp%
    
  2. You may want to delete directories as well:

    for /d %%D in (*) do rd /s /q "%%D"
    
  3. You need to skip the question for del and remove read-only files too:

    del /f /q *
    

so you arrive at:

@echo off
cd /D %temp%
for /d %%D in (*) do rd /s /q "%%D"
del /f /q *

Spring RestTemplate GET with parameters

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

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

instead of

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

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

One way to implement the first behavior is the following:

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

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

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

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

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

Making a Simple Ajax call to controller in asp.net mvc

It's for your UPDATE question.

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

UPDATE:

[HttpGet]
public ActionResult FirstAjax()
{
    Some Code--Some Code---Some Code
    return View();
}

[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
    Some Code--Some Code---Some Code
    return View();
}

And please refer this link for further reference of how a method becomes an action. Very good reference though.

Convert String[] to comma separated string in java

Android developers are probably looking for TextUtils.join

Android docs: http://developer.android.com/reference/android/text/TextUtils.html

Code:

String[] name = {"amit", "rahul", "surya"};
TextUtils.join(",",name)

Load local javascript file in chrome for testing?

To load local resources in Chrome when just using your local computer and not using a webserver you need to add the --allow-file-access-from-files flag.

You can have a shortcut to Chrome that allows files access and one that does not.

Create a shortcut for Chrome on the desktop, right click on shortcut, select properties. In the dialog box that opens find the target for the short cut and add the parameter after chrome.exe leaving a space

eg C:\PATH TO\chrome.exe --allow-file-access-from-files

This shortcut will allow access to files without affecting any other shortcut to Chrome you have.

When you open Chrome with this shortcut it should allow local resources to be loaded using HTML5 and the filesystem api

what does "dead beef" mean?

It's a made up expression using only the letters A-F, often used when a recognisable hexadecimal number is required. Some systems use it for various purposes such as showing memory which has been freed and should not be referenced again. In a debugger this value showing up could be a sign that you have made an error. From Wikipedia:

0xDEADBEEF ("dead beef") is used by IBM RS/6000 systems, Mac OS on 32-bit PowerPC processors and the Commodore Amiga as a magic debug value. On Sun Microsystems' Solaris, it marks freed kernel memory. On OpenVMS running on Alpha processors, DEAD_BEEF can be seen by pressing CTRL-T.

The number 0xDEADBEEF is equal to the less recognisable decimal number 3735928559 (unsigned) or -559038737 (signed).

How to do a SUM() inside a case statement in SQL server

You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.

WITH PercentageOfTotal (Id, Percentage) 
AS 
(
    SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT 
    CASE
        WHEN o.TotalType = 'Average' THEN r.avgscore
        WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
        ELSE o.cnt
    END AS [displayscore]
FROM PercentageOfTotal pt
    JOIN dbo.MyTable t ON pt.Id = t.Id

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

Parsing a CSV file using NodeJS

You can convert csv to json format using csv-to-json module and then you can easily use json file in your program

Converting HTML string into DOM elements?

You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:

var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><a href="#"></a><span></span></div>';
var div= wrapper.firstChild;

If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.

But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.

How can I apply a function to every row/column of a matrix in MATLAB?

Stumbled upon this question/answer while seeking how to compute the row sums of a matrix.

I would just like to add that Matlab's SUM function actually has support for summing for a given dimension, i.e a standard matrix with two dimensions.

So to calculate the column sums do:

colsum = sum(M) % or sum(M, 1)

and for the row sums, simply do

rowsum = sum(M, 2)

My bet is that this is faster than both programming a for loop and converting to cells :)

All this can be found in the matlab help for SUM.

Merge, update, and pull Git branches without using checkouts

You can simply git pull origin branchB into your branchA and git will do the trick for you.

How to download excel (.xls) file from API in postman?

You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image postman save response

For more Details check this

https://learning.getpostman.com/docs/postman/sending_api_requests/responses/

Angularjs dynamic ng-pattern validation

This is an interesting problem, complex Angular validation. The following fiddle implements what you want:

http://jsfiddle.net/2G8gA/1/

Details

I created a new directive, rpattern, that is a mix of Angular's ng-required and the ng-pattern code from input[type=text]. What it does is watch the required attribute of the field and take that into account when validating with regexp, i.e. if not required mark field as valid-pattern.

Notes

  • Most of the code is from Angular, tailored to the needs of this.
  • When the checkbox is checked, the field is required.
  • The field is not hidden when the required checkbox is false.
  • The regular expression is simplified for the demo (valid is 3 digits).

A dirty (but smaller) solution, if you do not want a new directive, would be something like:

$scope.phoneNumberPattern = (function() {
    var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
    return {
        test: function(value) {
            if( $scope.requireTel === false ) {
                return true;
            }
            return regexp.test(value);
        }
    };
})();

And in HTML no changes would be required:

<input type="text" ng-model="..." ng-required="requireTel"
    ng-pattern="phoneNumberPattern" />

This actually tricks angular into calling our test() method, instead of RegExp.test(), that takes the required into account.

psql: FATAL: role "postgres" does not exist

The \du command return:

Role name = postgres@implicit_files

And that command postgres=# \password postgres return error:

ERROR: role "postgres" does not exist.

But that postgres=# \password postgres@implicit_files run fine.

Also after sudo -u postgres createuser -s postgres the first variant also work.

Equivalent of jQuery .hide() to set visibility: hidden

There isn't one built in but you could write your own quite easily:

(function($) {
    $.fn.invisible = function() {
        return this.each(function() {
            $(this).css("visibility", "hidden");
        });
    };
    $.fn.visible = function() {
        return this.each(function() {
            $(this).css("visibility", "visible");
        });
    };
}(jQuery));

You can then call this like so:

$("#someElem").invisible();
$("#someOther").visible();

Here's a working example.

IF EXISTS before INSERT, UPDATE, DELETE for optimization

IF EXISTS....UPDATE

Don't do it. It forces two scans/seeks instead of one.

If update doesn't find a match on the WHERE clause, the cost of the update statement is just a seek/scan.

If it does find a match, and if you preface it w/ IF EXISTS, it has to find the same match twice. And in a concurrent environment, what was true for the EXISTS may not be true any longer for the UPDATE.

This is precisely why UPDATE/DELETE/INSERT statements allow a WHERE clause. Use it!

Disabling SSL Certificate Validation in Spring RestTemplate

Java code example for HttpClient > 4.3

package com.example.teocodownloader;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class Example {
    public static void main(String[] args) {
        CloseableHttpClient httpClient
                = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
    }
}

By the way, don't forget to add the following dependencies to the pom file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

You could find Java code example for HttpClient < 4.3 as well.

Transactions in .net

if you just need it for db-related stuff, some OR Mappers (e.g. NHibernate) support transactinos out of the box per default.

Creating a list of dictionaries results in a list of copies of the same dictionary

If you want one line:

list_of_dict = [{} for i in range(list_len)]

Java synchronized method lock on object, or method?

The lock accessed is on the object, not on the method. Which variables are accessed within the method is irrelevant.

Adding "synchronized" to the method means the thread running the code must acquire the lock on the object before proceeding. Adding "static synchronized" means the thread running the code must acquire the lock on the class object before proceeding. Alternatively you can wrap code in a block like this:

public void addA() {
    synchronized(this) {
        a++;
    }
}

so that you can specify the object whose lock must be acquired.

If you want to avoid locking on the containing object you can choose between:

How to specify different Debug/Release output directories in QMake .pro file

Old question, but still worth an up-to-date answer. Today it's common to do what Qt Creator does when shadow builds are used (they are enabled by default when opening a new project).

For each different build target and type, the right qmake is run with right arguments in a different build directory. Then that is just built with simple make.

So, imaginary directory structure might look like this.

/
|_/build-mylib-qt5-mingw32-debug
|_/build-mylib-qt5-mingw32-release
|_/build-mylib-qt4-msvc2010-debug
|_/build-mylib-qt4-msvc2010-release
|_/build-mylib-qt5-arm-debug
|_/build-mylib-qt5-arm-release
|_/mylib
  |_/include
  |_/src
  |_/resources

And the improtant thing is, a qmake is run in the build directory:

cd build-mylib-XXXX
/path/to/right/qmake ../mylib/mylib.pro CONFIG+=buildtype ...

Then it generates makefiles in build directory, and then make will generate files under it too. There is no risk of different versions getting mixed up, as long as qmake is never run in the source directory (if it is, better clean it up well!).

And when done like this, the .pro file from currently accepted answer is even simpler:

HEADERS += src/dialogs.h
SOURCES += src/main.cpp \
           src/dialogs.cpp

How to determine if object is in array

Why don't you use the indexOf method of javascript arrays?

Check this out: MDN indexOf Arrays

Simply do:

carBrands.indexOf(car1);

It will return you the index (position in the array) of car1. It will return -1 if car1 was not found in the array.

http://jsfiddle.net/Fraximus/r154cd9o

Edit: Note that in the question, the requirements are to check for the same object referenced in the array, and NOT a new object. Even if the new object is identical in content to the object in the array, it is still a different object. As mentioned in the comments, objects are passed by reference in JS and the same object can exist multiple times in multiple structures.
If you want to create a new object and check if the array contains objects identical to your new one, this answer won't work (Julien's fiddle below), if you want to check for that same object's existence in the array, then this answer will work. Check out the fiddles here and in the comments.

Application Crashes With "Internal Error In The .NET Runtime"

Had the same exact error on WinXP box with latest build of my .NET 4 code. Checked previous builds - now they crash too! Ok, so it's not me :). No suggestions here/above helped.

Much more recent (2018-05-09) report of the same problem: Application Crash with exit code 80131506.

A: We were receiving a similar error, but we believe ours was caused by the Citrix memory optimizer.
The resolution was to force a regeneration of the .Net core libraries on the host(s) where the issue was occurring:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe update /force

Root cause is still unknown (machine is not being updated and has little use), but that did it for me!

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

One liner for If string is not null or empty else

Old question, but thought I'd add this to help out,

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif

How to send parameters from a notification-click to an activity?

After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.

like this:

   Intent notificationIntent = new Intent(Main.this, Main.class);
   notificationIntent.putExtra("sport_id", "sport"+id);
   notificationIntent.putExtra("game_url", "gameURL"+id);

   notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime()))); 

I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...

git ignore exception

Just add ! before an exclusion rule.

According to the gitignore man page:

Patterns have the following format:

...

  • An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

Extracting numbers from vectors of strings

I think that substitution is an indirect way of getting to the solution. If you want to retrieve all the numbers, I recommend gregexpr:

matches <- regmatches(years, gregexpr("[[:digit:]]+", years))
as.numeric(unlist(matches))

If you have multiple matches in a string, this will get all of them. If you're only interested in the first match, use regexpr instead of gregexpr and you can skip the unlist.

getting the difference between date in days in java

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

Use Device Login on Smart TV / Console

i've been researching for that too but unfortunately the facebook device auth is still on experimental and they didn't give new keys (partner) to use the device auth.

You can find the working example here: http://oauth-device-demo.appspot.com/ Just look at the website source and you can have the appID that works with it.

The other one is twitter PIN oauth it's working and publicly available (i'm using it) https://dev.twitter.com/docs/auth/pin-based-authorization

How to reload the current route with the angular 2 router

Import Router and ActivatedRoute from @angular/router

import { ActivatedRoute, Router } from '@angular/router';

Inject Router and ActivatedRoute (in case you need anything from the URL)

constructor(
    private router: Router,
    private route: ActivatedRoute,
) {}

Get any parameter if needed from URL.

const appointmentId = this.route.snapshot.paramMap.get('appointmentIdentifier');

Using a trick by navigating to a dummy or main url then to the actual url will refresh the component.

this.router.navigateByUrl('/appointments', { skipLocationChange: true }).then(() => {
    this.router.navigate([`appointment/${appointmentId}`])
});

In your case

const id= this.route.snapshot.paramMap.get('id');
this.router.navigateByUrl('/departments', { skipLocationChange: true }).then(() => {
    this.router.navigate([`departments/${id}/employees`]);
});

If you use a dummy route then you will see a title blink 'Not Found' if you have implemented a not found url in case does not match any url.

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

Today I got this error, and I just did a small workaround which was too simple.

  1. Close all of your chrome instances, that you might have opened before you opened Visual Studio.
  2. Now stop debugging and run your application again.

You will not get the error again and if the debugger doesn't hit, refresh the browser again.

Update (12-Dec-2018):

I just tested this bug in Visual Studio 2019 preview, it seems like the bug is fixed now.

Hope this helps.

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

By default, Elasticsearch installed goes into read-only mode when you have less than 5% of free disk space. If you see errors similar to this:

Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"error":{"root_cause":[{"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"}],"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"},"status":403}

Or in /usr/local/var/log/elasticsearch.log you can see logs similar to:

flood stage disk watermark [95%] exceeded on [nCxquc7PTxKvs6hLkfonvg][nCxquc7][/usr/local/var/lib/elasticsearch/nodes/0] free: 15.3gb[4.1%], all indices on this node will be marked read-only

Then you can fix it by running the following commands:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

How can I assign the output of a function to a variable using bash?

You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:

VAR=$(scan)

Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.

Preserving trailing Newlines:

One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.

function scan2 () {
    local nl=$'\x0a';  # that's just \n
    echo "output${nl}${nl}" # 2 in the string + 1 by echo
}

# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"

echo "${VAR}---"

prints (3 newlines kept):

output


---

Use an output parameter: avoiding the subshell (and preserving newlines)

If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.

function scan3() {
    local -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}

VAR="some prior value which will get overwritten"

# you pass the name of the variable. VAR will be modified.
scan3 VAR

# newlines are also preserved.
echo "${VAR}==="

prints:

output

===

This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.

Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"

This is relevant. https://stackoverflow.com/a/38997681/5556676

Get java.nio.file.Path object from java.io.File

Yes, you can get it from the File object by using File.toPath(). Keep in mind that this is only for Java 7+. Java versions 6 and below do not have it.

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

Make sure the Find Implicit Dependencies checkbox is checked.

(Product -> Scheme -> Edit Scheme -> Build -> Find Implicit Dependencies)

How can I get a list of locally installed Python modules?

I ran into a custom installed python 2.7 on OS X. It required X11 to list modules installed (both using help and pydoc).

To be able to list all modules without installing X11 I ran pydoc as http-server, i.e.:

pydoc -p 12345

Then it's possible to direct Safari to http://localhost:12345/ to see all modules.

What's the difference between “mod” and “remainder”?

In C and C++ and many languages, % is the remainder NOT the modulus operator.

For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this

_x000D_
_x000D_
console.log(-21 % 4 == -1);
_x000D_
_x000D_
_x000D_

The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.

Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.

how to set ul/li bullet point color?

A couple ways this can be done:

This will make it a square

ul
{
  list-style-type: square;
}

This will make it green

li
{
  color: #0F0;
}

This will prevent the text from being green

li p
{
  color: #000;
}

However that will require that all text within lists be in paragraphs so that the color is not overridden.

A better way is to make an image of a green square and use:

ul
{
  list-style: url(green-square.png);
}

Lowercase and Uppercase with jQuery

If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:

.myclass {
    text-transform: lowercase;
}

See https://developer.mozilla.org/en/CSS/text-transform for more info.

However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.

Can't find out where does a node.js app running and can't kill it

If all those kill process commands don't work for you, my suggestion is to check if you were using any other packages to run your node process.

I had the similar issue, and it was due to I was running my node process using PM2(a NPM package). The kill [processID] command disables the process but keeps the port occupied. Hence I had to go into PM2 and dump all node process to free up the port again.

XSL if: test with multiple test conditions

Try to use the empty() function:

<xsl:if test="empty(node/ABC/node()) and empty(node/DEF/node())">
    <xsl:text>This should work</xsl:text>
</xsl:if>

This identifies ABC and DEF as empty in the sense that they do not have any child nodes (no elements, no text nodes, no processing instructions, no comments).

But, as pointed out by @Ian, your elements might not be empty really or that might not be your actual problem - you did not show what your input XML looks like.

Another cause of error could be your relative position in the tree. This way of testing conditions only works if the surrounding template matches the parent element of node or if you iterate over the parent element of node.

Conditional WHERE clause in SQL Server

To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!

Here:

WHERE 
    DateDropped = 0
    AND CASE
            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'
            WHEN DateAppr != 0 THEN 'True'
            ELSE 'False'
        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.

jQuery: how to change title of document during .ready()?

<script type="text/javascript">
$(document).ready(function() {

    $(this).attr("title", "sometitle");

});
</script>

awk without printing newline

awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls

print will insert a newline by default. You dont want that to happen, hence use printf instead.

How to create a simple map using JavaScript/JQuery

function Map() {
    this.keys = new Array();
    this.data = new Object();

    this.put = function (key, value) {
        if (this.data[key] == null) {
            this.keys.push(key);
        }
        this.data[key] = value;
    };

    this.get = function (key) {
        return this.data[key];
    };

    this.remove = function (key) {
        this.keys.remove(key);
        this.data[key] = null;
    };

    this.each = function (fn) {
        if (typeof fn != 'function') {
            return;
        }
        var len = this.keys.length;
        for (var i = 0; i < len; i++) {
            var k = this.keys[i];
            fn(k, this.data[k], i);
        }
    };

    this.entrys = function () {
        var len = this.keys.length;
        var entrys = new Array(len);
        for (var i = 0; i < len; i++) {
            entrys[i] = {
                key: this.keys[i],
                value: this.data[i]
            };
        }
        return entrys;
    };

    this.isEmpty = function () {
        return this.keys.length == 0;
    };

    this.size = function () {
        return this.keys.length;
    };
}

Appending a vector to a vector

std::copy (b.begin(), b.end(), std::back_inserter(a));

This can be used in case the items in vector a have no assignment operator (e.g. const member).

In all other cases this solution is ineffiecent compared to the above insert solution.

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

How do I use arrays in cURL POST requests

    $ch = curl_init();

    $data = array(
        'client_id' => 'xx',
        'client_secret' => 'xx',
        'redirect_uri' => $x,
        'grant_type' => 'xxx',
        'code' => $xx,
    );

    $data = http_build_query($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, "https://example.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $output = curl_exec($ch);

How to change default install location for pip

Open Terminal and type:

pip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages

except instead of

/Users/Bob/Library/Python/3.8/lib/python/site-packages

you would use whatever directory you want.

JavaScript: IIF like statement

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

How to put scroll bar only for modal-body?

If you're only supporting IE 9 or higher, you can use this CSS that will smoothly scale to the size of the window. You may need to tweak the "200px" though, depending on the height of your header or footer.

.modal-body{
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}