Programs & Examples On #Mismatch

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Invalid hook call. Hooks can only be called inside of the body of a function component

Yesterday, I shortened the code (just added <Provider store={store}>) and still got this invalid hook call problem. This made me suddenly realized what mistake I did: I didn't install the react-redux software in that folder.

I had installed this software in the other project folder, so I didn't realize this one also needed it. After installing it, the error is gone.

How to style components using makeStyles and still have lifecycle methods in Material UI?

What we ended up doing is stopped using the class components and created Functional Components, using useEffect() from the Hooks API for lifecycle methods. This allows you to still use makeStyles() with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.

Example:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: theme.spacing(1)
  },
  highlight: {
    backgroundColor: 'red',
  }
}));

// Highlight is a bool
const Welcome = ({highlight}) => { 
  const [userName, setUserName] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  useEffect(() => {
    axios.get('example.com/api/username/12')
         .then(res => setUserName(res.userName));
  }, []);

  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
   </Container>
   );
  }
}

export default Welcome;

React Native version mismatch

I also had this issue using Expo and iOS Simulator. What worked for me was erasing the Simulator in Hardware > Erase All Content and Settings...

NVIDIA NVML Driver/library version mismatch

As @etal said, rebooting can solve this problem, but I think a procedure without rebooting will help.

For Chinese, check my blog -> ???

The error message

NVML: Driver/library version mismatch

tell us the Nvidia driver kernel module (kmod) have a wrong version, so we should unload this driver, and then load the correct version of kmod

How to do that ?

First, we should know which drivers are loaded.

lsmod | grep nvidia

you may get

nvidia_uvm            634880  8
nvidia_drm             53248  0
nvidia_modeset        790528  1 nvidia_drm
nvidia              12312576  86 nvidia_modeset,nvidia_uvm

our final goal is to unload nvidia mod, so we should unload the module depend on nvidia

sudo rmmod nvidia_drm
sudo rmmod nvidia_modeset
sudo rmmod nvidia_uvm

then, unload nvidia

sudo rmmod nvidia

Troubleshooting

if you get an error like rmmod: ERROR: Module nvidia is in use, which indicates that the kernel module is in use, you should kill the process that using the kmod:

sudo lsof /dev/nvidia*

and then kill those process, then continue to unload the kmods

Test

confirm you successfully unload those kmods

lsmod | grep nvidia

you should get nothing, then confirm you can load the correct driver

nvidia-smi

you should get the correct output

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

I had the same issue and deleted the complete schema from the database, yet the issue remained.

I solved this by running the repair() command of flyway:

flyway.repair();

Alternatively with Flyway Maven plugin:

mvn flyway:repair

Maven plugin addition into pom.xml:

<plugin>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-maven-plugin</artifactId>
    <version>5.2.4</version>
</plugin>

BTW: I did not find what exactly went wrong.

With Gradle (as per comment from Raf):

./gradlew flywayRepair

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

Check if the file path is correct and the file exists - in my case that was the issue - as I fixed it, the error disappeared

How to get Tensorflow tensor dimensions (shape) as int values?

Another simple solution is to use map() as follows:

tensor_shape = map(int, my_tensor.shape)

This converts all the Dimension objects to int

FCM getting MismatchSenderId

Actually there are many reasons for this issue. Mine was because of Invalid token passed. I was passing same token generated from one app and using same token in another app. Once token updated , it work for me.

TokenMismatchException in VerifyCsrfToken.php Line 67

You need to have this line of code in the section of your HTML document, you could do that by default , it won't do any harm:

<meta name="csrf-token" content="{{ csrf_token() }}" />

And in your form you need to add this hidden input field:

<input type="hidden" name="_token" value="{{ csrf_token() }}">

Thats it, worked for me.

Laravel csrf token mismatch for ajax POST Request

In case your session expires, you can use this, to login again

$(document).ajaxComplete(function(e, xhr, opt){
  if(xhr.status===419){
    if(xhr.responseJSON && xhr.responseJSON.message=='CSRF token mismatch.') window.location.reload();
  }
});

Adding form action in html in laravel

Use action="{{ action('WelcomeController@log_in') }}"

however TokenMismatchException means that you are missing a CSRF token in your form.

You can add this by using <input name="_token" type="hidden" value="{{ csrf_token() }}">

How to convert interface{} to string?

You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)

Latest version of Docopt returns Opts object that has methods for conversion:

host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

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

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

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

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

I had the same problem and finally resolved it by changing the order of pem blocks in certificate file.

The cert block should be put in the beginning of the file, then intermediate blocks, then root block.

I realized this problem by comparing a problematic certificate file with a working certificate file.

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

The answer I have finally found is that the SMTP service on the server is not using the same certificate as https.

The diagnostic steps I had read here make the assumption they use the same certificate and every time I've tried this in the past they have done and the diagnostic steps are exactly what I've done to solve the problem several times.

In this case those steps didn't work because the certificates in use were different, and the possibility of this is something I had never come across.

The solution is either to export the actual certificate from the server and then install it as a trusted certificate on my machine, or to get a different valid/trusted certificate for the SMTP service on the server. That is currently with our IT department who administer the servers to decide which they want to do.

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This can be caused by a full disk (Ubuntu/Nginx).

My situation:

Selecting specific rows and columns from NumPy array

Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

That is of course a pain to write, so you can let broadcasting help you:

>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

This is much simpler to do if you index with arrays, not lists:

>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

I Don't know why, but in my case, even if I remove bin folder from project, when I build project it copies old version of newtonsoft.json, I copied new version's dll from packages folder and It solves for now.

How to fill color in a cell in VBA?

Non VBA Solution:

Use Conditional Formatting rule with formula: =ISNA(A1) (to highlight cells with all errors - not only #N/A, use =ISERROR(A1))

enter image description here

VBA Solution:

Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16) and .SpecialCells(xlCellTypeConstants, 16)to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then)

Sub ColorCells()
    Dim Data As Range, Data2 As Range, cell As Range
    Dim currentsheet As Worksheet

    Set currentsheet = ActiveWorkbook.Sheets("Comparison")

    With currentsheet.Range("A2:AW" & Rows.Count)
        .Interior.Color = xlNone
        On Error Resume Next
        'select only cells with errors
        Set Data = .SpecialCells(xlCellTypeFormulas, 16)
        Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
        On Error GoTo 0
    End With

    If Not Data2 Is Nothing Then
        If Not Data Is Nothing Then
            Set Data = Union(Data, Data2)
        Else
            Set Data = Data2
        End If
    End If

    If Not Data Is Nothing Then
        For Each cell In Data
            If cell.Text = "#N/A" Then
               cell.Interior.ColorIndex = 4
            End If
        Next
    End If
End Sub

Note, to highlight cells witn any error (not only "#N/A"), replace following code

If Not Data Is Nothing Then
   For Each cell In Data
       If cell.Text = "#N/A" Then
          cell.Interior.ColorIndex = 3
       End If
   Next
End If

with

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3

UPD: (how to add CF rule through VBA)

Sub test()
    With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
        .Delete
        .Add Type:=xlExpression, Formula1:="=ISNA(A1)"
        .Item(1).Interior.ColorIndex = 3
    End With
End Sub

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

I encountered this error once after omitting this statement from my transaction.

COMMIT TRANSACTION [MyTransactionName]

how to set mongod --dbpath

sudo mongod --dbpath ~/data

This made it work for me.

How to pass ArrayList<CustomeObject> from one activity to another?

you need implements Parcelable in your ContactBean class, I put one example for you:

public class ContactClass implements Parcelable {

private String id;
private String photo;
private String firstname;
private String lastname;

public ContactClass()
{

}

private ContactClass(Parcel in) {
    firstname = in.readString();
    lastname = in.readString();
    photo = in.readString();
    id = in.readString();

}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(firstname);
    dest.writeString(lastname);
    dest.writeString(photo);
    dest.writeString(id);

}

 public static final Parcelable.Creator<ContactClass> CREATOR = new Parcelable.Creator<ContactClass>() {
        public ContactClass createFromParcel(Parcel in) {
            return new ContactClass(in);
        }

        public ContactClass[] newArray(int size) {
            return new ContactClass[size];

        }
    };

   // all get , set method 
 }

and this get and set for your code:

Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", ContactLis);
startActivity(intent);

second class:

ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");

Convert Text to Date?

This code is working for me

Dim N As Long, r As Range
N = Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To N
    Set r = Cells(i, "B")
    r.Value = CDate(r.Value)
Next i

Try it changing the columns to suit your sheet

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

In Linux Kernel, present pages are physical pages of RAM which kernel can see. Literally, present pages is total size of RAM in 4KB unit.

grep present /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

The 'MemTotal' form /proc/meminfo is the total size of memory managed by buddy system.And we can also compute it like this:

grep managed /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 

or

static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);
}

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I could solve similar problem with System.Net.HTTP by adding assembly reference in app.config of main application.

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.1.1" newVersion="4.0.0.0" />
      </dependentAssembly></runtime>

Cannot overwrite model once compiled Mongoose

This may give a hit for some, but I got the error as well and realized that I just misspelled the user model on importing.

wrong: const User = require('./UserModel'); correct: const User = require('./userModel');

Unbelievable but consider it.

Excel Validation Drop Down list using VBA

This worked on my test file (note the index in VBA starts from zero):

Sub DV_Test()
    Dim ValidationList(5) As Variant, i As Integer

    For i = 0 To UBound(ValidationList)
        ValidationList(i) = i + 1
    Next

    With Range("A1").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
            Operator:=xlEqual, Formula1:=Join(ValidationList, ",")
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End Sub

I used xlEqual because that's what I think you are trying to get people to select one of the list.

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

It seems that you have a bunch of describes that never have ends keywords, starting with describe "when email format is invalid" do until describe "when email address is already taken" do

Put an end on those guys and you're probably done =)

Android Studio - local path doesn't exist

When I look at my file system I see that the apk is generated but in a different folder and with a different name.

However, this is not where it needs to be. After some time I gound that there is an option in the “.iml” file that you can configure to fix it.

There are multiple “.iml” files, one for the master project, one for the module that contains that produces the apk. If you edit the “.iml” file for the module and add the following option with path respective to your project

<option name="APK_PATH" value="/build/apk/desiredname-debug-unaligned.apk" />

Set Matplotlib colorbar size to match graph

You can do this easily with a matplotlib AxisDivider.

The example from the linked page also works without using subplots:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

enter image description here

Which JDK version (Language Level) is required for Android Studio?

Normally, I would go with what the documentation says but if the instructor explicitly said to stick with JDK 6, I'd use JDK 6 because you would want your development environment to be as close as possible to the instructors. It would suck if you ran into an issue and having the thought in the back of your head that maybe it's because you're on JDK 7 that you're having the issue. Btw, I haven't touched Android recently but I personally never ran into issues when I was on JDK 7 but mind you, I only code Android apps casually.

How to read strings from a Scanner in a Java console application?

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

Hope this helps.

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

How to multiply duration by integer?

You have to cast it to a correct format Playground.

yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)

If you will check documentation for sleep, you see that it requires func Sleep(d Duration) duration as a parameter. Your rand.Int31n returns int32.

The line from the example works (time.Sleep(100 * time.Millisecond)) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

ByRef argument type mismatch in Excel VBA

I changed a few things to work with Option Explicit, and the code ran fine against a cell containing "abc.123", which returned "abc.12,". There were no compile errors.

Option Explicit ' This is new

Public Function ProcessString(input_string As String) As String
    ' The temp string used throughout the function
    Dim temp_string As String
    Dim i As Integer ' This is new
    Dim return_string As String ' This is new
    For i = 1 To Len(input_string)
        temp_string = Mid(input_string, i, 1)
        If temp_string Like "[A-Z, a-z, 0-9, :, -]" Then
            return_string = return_string & temp_string
        End If
    Next i
    return_string = Mid(return_string, 1, (Len(return_string) - 1))
    ProcessString = return_string & ", "
End Function

I'll suggest you post more of your relevant code (that calls this function). You've stated that last_name is a String, but it appears that may not be the case. Step through your code line by line and ensure that this is actually the case.

How to split a string and assign it to variables

What you are doing is, you are accepting split response in two different variables, and strings.Split() is returning only one response and that is an array of string. you need to store it to single variable and then you can extract the part of string by fetching the index value of an array.

example :

 var hostAndPort string
    hostAndPort = "127.0.0.1:8080"
    sArray := strings.Split(hostAndPort, ":")
    fmt.Println("host : " + sArray[0])
    fmt.Println("port : " + sArray[1])

Jar mismatch! Fix your dependencies

Use a Library Project just for the Support Library

As of ADT 22, using Eclipse Juno

I don't think any of the above are really the best answers. I also don't think it is recommended to use the external jar function in Eclipse anymore (AFAIK).

Rather, what worked for me is to create a separate empty library project.

Then use Android tools > Add Support Library to get the latest version you need or want.

Then remove the support lib jar from all other projects.

Finally, for every project that requires it, add a reference to your new Library project

(project properties) > Android > (Library box) > Add...

Then all your projects will have a single source to use and update the support library. This also makes javadocs easier to get working.

For info on how to setup the javadocs see:

How to attach javadoc or sources to jars in libs folder?

Convert string to JSON array

if the response is like this

"GetDataResult": "[{\"UserID\":1,\"DeviceID\":\"d1254\",\"MobileNO\":\"056688\",\"Pak1\":true,\"pak2\":true,\"pak3\":false,\"pak4\":true,\"pak5\":true,\"pak6\":false,\"pak7\":false,\"pak8\":true,\"pak9\":false,\"pak10\":true,\"pak11\":false,\"pak12\":false}]"

you can parse like this

JSONObject jobj=new JSONObject(response);
        String c = jobj.getString("GetDataResult");         
        JSONArray jArray = new JSONArray(c);
        deviceId=jArray.getJSONObject(0).getString("DeviceID");

here the JsonArray size is 1.Otherwise you should use for loop for getting values.

Content Type application/soap+xml; charset=utf-8 was not supported by service

I also came across the same problem. In my case, I was using transfermode = streaming with Mtom. As it turns out, I had named one of my variables (for a structure), "HEADER". This conflicted with the message element [http://tempuri.org/:HEADER] as part of the http service download. Clearly, one must avoid using "reserved" words as parameter name.

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

Start an activity from a fragment

You should use getActivity() to launch activities from fragments

Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
startActivity(intent);

Also, you should be naming classes with caps: MFragmentActivity instead of mFragmentActivity.

Iterator over HashMap in Java

  1. Using EntrySet() and for each loop

       for(Map.Entry<String, String> entry: hashMap.entrySet()) {
         System.out.println("Key Of map = "+ entry.getKey() + 
                          " , value of map = " + entry.getValue() );
     }
    
  2. Using keyset() and for each loop

             for(String key : hashMap.keySet()) {
                System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
               }
    
  3. Using EntrySet() and java Iterator

          for(String key : hashMap.keySet()) {
            System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
            }
    
  4. Using keyset() and java Iterator

         Iterator<String> keysIterator = keySet.iterator();
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
       }
    

Reference : How to iterate over Map or HashMap in java

@Value annotation type casting to Integer from String

I had the exact same situation. It was caused by not having a PropertySourcesPlaceholderConfigurer in the Spring context, which resolves values against the @Value annotation inside of classes.

Include a property placeholder to solve the problem, no need to use Spring expressions for integers (the property file does not have to exist if you use ignore-resource-not-found="true"):

<context:property-placeholder location="/path/to/my/app.properties"
    ignore-resource-not-found="true" />

Mismatched anonymous define() module

I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.

To get rid of the error, include all your other js files by using requirejs.

How to convert list data into json in java

Try these simple steps:

ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Mismatch Detected for 'RuntimeLibrary'

Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

How to specify function types for void (not Void) methods in Java8?

When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like

  public interface Thunk { void apply(); }

somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.

In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.

cannot convert data (type interface {}) to type string: need type assertion

According to the Go specification:

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.

A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.

In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.

If you were unsure if it was a string or not, you could test using the two return syntax.

str, ok := data.(string)

If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:

if str, ok := data.(string); ok {
    /* act on str */
} else {
    /* not string */
}

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

Set custom HTML5 required field validation message

You can add this script for showing your own message.

 <script>
     input = document.getElementById("topicName");

            input.addEventListener('invalid', function (e) {
                if(input.validity.valueMissing)
                {
                    e.target.setCustomValidity("Please enter topic name");
                }
//To Remove the sticky error message at end write


            input.addEventListener('input', function (e) {
                e.target.setCustomValidity('');
            });
        });

</script>

For other validation like pattern mismatch you can add addtional if else condition

like

else if (input.validity.patternMismatch) 
{
  e.target.setCustomValidity("Your Message");
}

there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid

Difference between number and integer datatype in oracle dictionary views

Integer is only there for the sql standard ie deprecated by Oracle.

You should use Number instead.

Integers get stored as Number anyway by Oracle behind the scenes.

Most commonly when ints are stored for IDs and such they are defined with no params - so in theory you could look at the scale and precision columns of the metadata views to see of no decimal values can be stored - however 99% of the time this will not help.

As was commented above you could look for number(38,0) columns or similar (ie columns with no decimal points allowed) but this will only tell you which columns cannot take decimals, and not what columns were defined so that INTS can be stored.

Suggestion: do a data profile on the number columns. Something like this:

 select max( case when trunc(column_name,0)=column_name then 0 else 1 end ) as has_dec_vals
 from table_name

COALESCE with Hive SQL

From [Hive Language Manual][1]:

COALESCE (T v1, T v2, ...)

Will return the first value that is not NULL, or NULL if all values's are NULL

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-ConditionalFunctions

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.

In my c# application, when preparing for the bulk insert command,

string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).

I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:

Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)

So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And now it inserts successfully.

Bulk Insert SQL -   --->  BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful...  --->  clsDatase.PerformBulkInsert

Postgresql 9.2 pg_dump version mismatch

You can just locate pg_dump and use the full path in command

locate pg_dump

/usr/bin/pg_dump
/usr/bin/pg_dumpall
/usr/lib/postgresql/9.3/bin/pg_dump
/usr/lib/postgresql/9.3/bin/pg_dumpall
/usr/lib/postgresql/9.6/bin/pg_dump
/usr/lib/postgresql/9.6/bin/pg_dumpall

Now just use the path of the desired version in the command

/usr/lib/postgresql/9.6/bin/pg_dump books > books.out

try/catch with InputMismatchException creates infinite loop

As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.

Try using it this way by using hasNextInt()

catch (Exception e) {
            System.out.println("Error!");
           input.hasNextInt();         
        }

Or try using nextLine() coupled with Integer.parseInt() for taking input....

Scanner scan = new Scanner(System.in);

int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

I had the same issue with google sign in.

I had correctly entered my callbacks in google Credential panel at google developer console here was my redirect urls :

https://www.example.com/signin-google

https://www.example.com/signin-google/

https://www.example.com/oauth2callback

https://www.example.com/oauth2callback/

Everything seems fine right? But it still didn't work until I added one more magical Url I added signin-google URL (which is default google callback) without www and problem solved.

Take it into account (depending on your domain) you may or may not need to add both with and without www URLs

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

Why do I get "MismatchSenderId" from GCM server side?

Mismatch happens when you don't use the numeric ID. Project ID IS NOT SENDER ID!! It took me 9 hours to figure this out. For all the confusion created by google, check the following link to get numeric id.

https://console.cloud.google.com

instead of

https://console.developers.google.com

Hope it helps!!

Update:- Things have changed again. Now the sender id is with firebase.

Go to https://console.firebase.google.com and select your project. Under settings -> cloud messaging, you can find the sender id.

And it works!

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I also received this error and tried everything I could find online and it wouldn't go away. In the end, I just downgraded MVC from 5.2.3 to 4.0.40804. I don't like this solution because eventually I'll need to use MVC 5, but it works for now. Hope this helps others.

BULK INSERT with identity (auto-increment) column

You have to do bulk insert with format file:

   BULK INSERT Employee FROM 'path\tempFile.csv ' 
   WITH (FORMATFILE = 'path\tempFile.fmt');

where format file (tempFile.fmt) looks like this:

11.0
2
1 SQLCHAR 0 50 "\t"  2  Name   SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 50 "\r\n" 3  Address  SQL_Latin1_General_CP1_CI_AS

more details here - http://msdn.microsoft.com/en-us/library/ms179250.aspx

Headers and client library minor version mismatch

I got same php warring in my wordpress site...

Err: Warning: mysql_connect(): Headers and client library minor version mismatch. Headers:50547 Library:50628 in /home/lhu/public_html/innovacarrentalschennai.com/wp-includes/wp-db.php on line 1515

Cause: I updated wp 4.2 to 4.5 version (PHP and MySql mismatch )

I changed wp-db.php on line 1515

$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );

to

if ( WP_DEBUG ) {
    $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
} else {
    $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
}

Its got without warring err on my wordpress site

Convert List<String> to List<Integer> directly

You can use the Lambda functions of Java 8 to achieve this without looping

    String string = "1, 2, 3, 4";
    List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

How to transform currentTimeMillis to a readable date format?

It will work.

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

SVN - Checksum mismatch while updating

1.'update to reversion' check 'only this item' under the directory 2.update again check 'Fully recursive'

Convert Java Array to Iterable

Integer foo[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

List<Integer> list = Arrays.asList(foo);
// or
Iterable<Integer> iterable = Arrays.asList(foo);

Though you need to use an Integer array (not an int array) for this to work.

For primitives, you can use guava:

Iterable<Integer> fooBar = Ints.asList(foo);
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>15.0</version>
    <type>jar</type>
</dependency>

For Java8: (from Jin Kwon's answer)

final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

I had a very similar warning in my build. My projects were set to target .NET 4.5, on the build server the Windows 8.1 SDK (for .NET 4.5.1) was installed. After updating my projects to target .NET 4.5.1 (wasn't a problem for me, was for a completely new application), I didn't receive the warning anymore...

Deserialize JSON to ArrayList<POJO> using Jackson

Another way is to use an array as a type, e.g.:

ObjectMapper objectMapper = new ObjectMapper();
MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:

List<MyPojo> pojoList = Arrays.asList(pojos);

IMHO this is much more readable.

And to make it be an actual list (that can be modified, see limitations of Arrays.asList()) then just do the following:

List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos));

continuing execution after an exception is thrown in java

If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.

try {

    //Dangerous code: could throw an error

} catch (Exception e) {

    //Cleanup: make sure that this methods variables and such are in the desired state

    throw e;
}

This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.

An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

If file exists then delete the file

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

I saw this answer and it worked for me. https://msdn.microsoft.com/en-us/library/ms712362%28v=vs.85%29.aspx

After you have installed an ODBC driver from the driver's setup program, you can define one or more data sources for it. The data source name (DSN) should provide a unique description of the data; for example, Payroll or Accounts Payable. The user and system data sources that are defined for all currently installed drivers are listed in the User DSN or System DSN tabs of the ODBC Data Source Administrator dialog box. The file data sources in a given directory are listed in the File DSN tab; the directory to be shown is entered in the Look in box in the File DSN tab. System_CAPS_noteNote

To manage a data source that connects to a 32-bit driver under 64-bit platform, use c:\windows\sysWOW64\odbcad32.exe. To manage a data source that connects to a 64-bit driver, use c:\windows\system32\odbcad32.exe. In Administrative Tools on a 64-bit Windows 8 operating system, there are icons for both the 32-bit and 64-bit ODBC Data Source Administrator dialog box.

If you use the 64-bit odbcad32.exe to configure or remove a DSN that connects to a 32-bit driver, for example, Driver do Microsoft Access (*.mdb), you will receive the following error message:

The specified DSN contains an architecture mismatch between the Driver and Application

To resolve this error, use the 32-bit odbcad32.exe to configure or remove the DSN.

A data source associates a particular ODBC driver with the data you want to access through that driver. For example, you might create a data source to use the ODBC dBASE driver to access one or more dBASE files found in a specific directory on your hard disk or a network drive. Using the ODBC Data Source Administrator, you can add, modify, and delete data sources, as described in the following table.

Excel VBA - select multiple columns not in sequential order

Range("A:B,D:E,G:H").Select can help

Edit note: I just saw you have used different column sequence, I have updated my answer

Excel VBA Run-time error '13' Type mismatch

Sub HighlightSpecificValue()

'PURPOSE: Highlight all cells containing a specified values


Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range

'What value do you want to find?
  fnd = InputBox("I want to hightlight cells containing...", "Highlight")

    'End Macro if Cancel Button is Clicked or no Text is Entered
      If fnd = vbNullString Then Exit Sub

Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)

enter code here
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)

'Test to see if anything was found
  If Not FoundCell Is Nothing Then
    FirstFound = FoundCell.Address

  Else
    GoTo NothingFound
  End If

Set rng = FoundCell

'Loop until cycled through all unique finds
  Do Until FoundCell Is Nothing
    'Find next cell with fnd value
      Set FoundCell = myRange.FindNext(after:=FoundCell)







    'Add found cell to rng range variable
      Set rng = Union(rng, FoundCell)

    'Test to see if cycled through to first found cell
      If FoundCell.Address = FirstFound Then Exit Do


  Loop

'Highlight Found cells yellow

  rng.Interior.Color = RGB(255, 255, 0)

  Dim fnd1 As String
  fnd1 = "Rah"
  'Condition highlighting

  Set FoundCell = myRange.FindNext(after:=FoundCell)



  If FoundCell.Value("rah") Then
      rng.Interior.Color = RGB(255, 0, 0)

  ElseIf FoundCell.Value("Nav") Then

    rng.Interior.Color = RGB(0, 0, 255)



    End If





'Report Out Message
  MsgBox rng.Cells.Count & " cell(s) were found containing: " & fnd

Exit Sub

'Error Handler
NothingFound:
  MsgBox "No cells containing: " & fnd & " were found in this worksheet"

End Sub

Content Type text/xml; charset=utf-8 was not supported by service

In my case, I had to specify messageEncoding to Mtom in app.config of the client application like that:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="IntegrationServiceSoap" messageEncoding="Mtom"/>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:29495/IntegrationService.asmx"
                binding="basicHttpBinding" bindingConfiguration="IntegrationServiceSoap"
                contract="IntegrationService.IntegrationServiceSoap" name="IntegrationServiceSoap" />
        </client>
    </system.serviceModel>
</configuration>

Both my client and server use basicHttpBinding. I hope this helps the others :)

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

The following should be the most correct today. Note, junit 4.11 depends on hamcrest-core, so you shouldn't need to specify that at all, mockito-all cannot be used since it includes (not depends on) hamcrest 1.1

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.8</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Java compiler level does not match the version of the installed Java project facet

I changed the configuration inside workspace/project/.setting/org.eclipse.wst.common.project.facet.core to :

installed facet="jst.web" version="2.5"
installed facet="jst.java" version="1.7"

Before changing config, remove project from IDE. This worked for me.

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

In VS2010 iterator debug level defaults to 2 in debug and is disabled in release. One of the dlls you are using probably has iterator debugging turned off in debug either because it was built in an older version of visual studio or they explicitly added the defines to the project.

Search for _ITERATOR_DEBUG_LEVEL and _SECURE_SCL remove them or set them appropriately in all projects and sources and rebuild everything.

_ITERATOR_DEBUG_LEVEL = 0 // disabled (for release builds)
_ITERATOR_DEBUG_LEVEL = 1 // enabled (if _SECURE_SCL is defined)
_ITERATOR_DEBUG_LEVEL = 2 // enabled (for debug builds)

In short you are probably mixing release and debug dlls. Don't linked release dlls in debug or vice versa!

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

I will give you a better idea

for(decltype(things.size()) i = 0; i < things.size(); i++){
                   //...
}

decltype is

Inspects the declared type of an entity or the type and value category of an expression.

So, It deduces type of things.size() and i will be a type as same as things.size(). So, i < things.size() will be executed without any warning

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Frequently we deal with other fellow java programmers work which create these Stored Procedure. and we do not want to mess around with it. but there is possibility you get the result set where these exec sample return 0 (almost Stored procedure call returning zero).

check this sample :

public void generateINOUT(String USER, int DPTID){

    try {


        conUrl = JdbcUrls + dbServers +";databaseName="+ dbSrcNames+";instance=MSSQLSERVER";

        con = DriverManager.getConnection(conUrl,dbUserNames,dbPasswords);
        //stat = con.createStatement();
        con.setAutoCommit(false); 
        Statement st = con.createStatement(); 

        st.executeUpdate("DECLARE @RC int\n" +
                "DECLARE @pUserID nvarchar(50)\n" +
                "DECLARE @pDepartmentID int\n" +
                "DECLARE @pStartDateTime datetime\n" +
                "DECLARE @pEndDateTime datetime\n" +
                "EXECUTE [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] \n" +
                ""+USER +
                "," +DPTID+
                ",'"+STARTDATE +
                "','"+ENDDATE+"'");

        ResultSet rs = st.getGeneratedKeys();

        while (rs.next()){
              String userID = rs.getString("UserID");
              Timestamp timeIN = rs.getTimestamp("timeIN");
              Timestamp timeOUT = rs.getTimestamp ("timeOUT");
              int totTime = rs.getInt ("totalTime");
              int pivot = rs.getInt ("pivotvalue");

              timeINS = sdz.format(timeIN);
              userIN.add(timeINS);

              timeOUTS = sdz.format(timeOUT);
              userOUT.add(timeOUTS);

              System.out.println("User : "+userID+" |IN : "+timeIN+" |OUT : "+timeOUT+"| Total Time : "+totTime+" | PivotValue : "+pivot);
        }

        con.commit();

    }catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);
        if (e.getCause() != null) {
        e.getCause().printStackTrace();}
    }  
}

I came to this solutions after few days trial and error, googling and get confused ;) it execute below Stored Procedure :

USE [AccessManager]
GO
/****** Object:  StoredProcedure [dbo].[SP_GenerateInOutDetailReportSimple]    
Script Date: 04/05/2013 15:54:11 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [dbo].[SP_GenerateInOutDetailReportSimple]
(
@pUserID nvarchar(50),
@pDepartmentID int,
@pStartDateTime datetime,
@pEndDateTime datetime
)
AS


Declare @ErrorCode int
Select @ErrorCode = @@Error

Declare @TransactionCountOnEntry int
If @ErrorCode = 0
Begin
    Select @TransactionCountOnEntry = @@TranCount
    BEGIN TRANSACTION
End


If @ErrorCode = 0
Begin       

    -- Create table variable instead of SQL temp table because report wont pick up the temp table
    DECLARE @tempInOutDetailReport TABLE
    (
        UserID nvarchar(50),
        LogDate datetime,   
        LogDay varchar(20), 
        TimeIN datetime,
        TimeOUT datetime,
        TotalTime int,
        RemarkTimeIn nvarchar(100),
        RemarkTimeOut nvarchar(100),
        TerminalIPTimeIn varchar(50),
        TerminalIPTimeOut varchar(50),
        TerminalSNTimeIn nvarchar(50),
        TerminalSNTimeOut nvarchar(50),
        PivotValue int
    )           

    -- Declare variables for the while loop
    Declare @LogUserID nvarchar(50)
    Declare @LogEventID nvarchar(50)
    Declare @LogTerminalSN nvarchar(50)
    Declare @LogTerminalIP nvarchar(50)
    Declare @LogRemark nvarchar(50)
    Declare @LogTimestamp datetime  
    Declare @LogDay nvarchar(20)

    -- Filter off userID, departmentID, StartDate and EndDate if specified, only process the remaining logs
    -- Note: order by user then timestamp
    Declare LogCursor Cursor For 
    Select distinct access_event_logs.USERID, access_event_logs.EVENTID, 
        access_event_logs.TERMINALSN, access_event_logs.TERMINALIP,
        access_event_logs.REMARKS, access_event_logs.LOCALTIMESTAMP, Datename(dw,access_event_logs.LOCALTIMESTAMP) AS WkDay
    From access_event_logs
        Left Join access_user on access_user.User_ID = access_event_logs.USERID
        Left Join access_user_dept on access_user.User_ID = access_user_dept.User_ID
    Where ((Dept_ID = @pDepartmentID) OR (@pDepartmentID IS NULL))
        And ((access_event_logs.USERID LIKE '%' + @pUserID + '%') OR (@pUserID IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP >= @pStartDateTime ) OR (@pStartDateTime IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP < DATEADD(day, 1, @pEndDateTime) ) OR (@pEndDateTime IS NULL)) 
        And (access_event_logs.USERID != 'UNKNOWN USER') -- Ignore UNKNOWN USER
    Order by access_event_logs.USERID, access_event_logs.LOCALTIMESTAMP

    Open LogCursor

    Fetch Next 
    From LogCursor
    Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay

    -- Temp storage for IN event details
    Declare @InEventUserID nvarchar(50)
    Declare @InEventDay nvarchar(20)
    Declare @InEventTimestamp datetime
    Declare @InEventRemark nvarchar(100)
    Declare @InEventTerminalIP nvarchar(50)
    Declare @InEventTerminalSN nvarchar(50)

    -- Temp storage for OUT event details
    Declare @OutEventUserID nvarchar(50)        
    Declare @OutEventTimestamp datetime
    Declare @OutEventRemark nvarchar(100)
    Declare @OutEventTerminalIP nvarchar(50)
    Declare @OutEventTerminalSN nvarchar(50)

    Declare @CurrentUser varchar(50) -- used to indicate when we change user group
    Declare @CurrentDay varchar(50) -- used to indicate when we change day
    Declare @FirstEvent int -- indicate the first event we received     
    Declare @ReceiveInEvent int -- indicate we have received an IN event
    Declare @PivotValue int -- everytime we change user or day - we reset it (reporting purpose), if same user..keep increment its value
    Declare @CurrTrigger varchar(50) -- used to keep track of the event of the current event log trigger it is handling 
    Declare @CurrTotalHours int -- used to keep track of total hours of the day of the user

    Declare @FirstInEvent datetime
    Declare @FirstInRemark nvarchar(100)
    Declare @FirstInTerminalIP nvarchar(50)
    Declare @FirstInTerminalSN nvarchar(50)
    Declare @FirstRecord int -- indicate another day of same user

    Set @PivotValue = 0 -- initialised
    Set @CurrentUser = '' -- initialised
    Set @FirstEvent = 1 -- initialised
    Set @ReceiveInEvent = 0 -- initialised  
    Set @CurrTrigger = '' -- Initialised    
    Set @CurrTotalHours = 0 -- initialised
    Set @FirstRecord = 1 -- initialised
    Set @CurrentDay = '' -- initialised

    While @@FETCH_STATUS = 0
    Begin
        -- use to track current log trigger
        Set @CurrTrigger =LOWER(@LogEventID)

        If (@CurrentUser != '' And @CurrentUser != @LogUserID) -- new batch of user
        Begin
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
            Begin
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day                    
                    Set @PivotValue = 0 -- Reset                        

                Else -- same day
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day

                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                                                         
            End                 

            Set @FirstEvent = 1 -- Reset flag (we are having a new user group)
            Set @ReceiveInEvent = 0 -- Reset
            Set @PivotValue = 0 -- Reset
            --Set @CurrentDay = '' -- Reset
        End

        If LOWER(@LogEventID) = 'in' -- IN event
        Begin           
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
            Begin
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day
                Begin
                    Set @PivotValue = 0 -- Reset

                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
                    --  @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  
                End
                Else
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day


                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                     
            End         

            If((@CurrentDay != @LogDay And @CurrentDay != '') Or (@CurrentUser != @LogUserID And @CurrentUser != '') )
            Begin

                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                        LogDate)
                    values( @CurrentUser, @CurrentDay, @FirstInEvent, @OutEventTimestamp, @CurrTotalHours,
                        @FirstInRemark, @OutEventRemark, @FirstInTerminalIP, @OutEventTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))      

                Set @FirstRecord = 1
            End
            -- Save it
            Set @InEventUserID = @LogUserID                         
            Set @InEventDay = @LogDay
            Set @InEventTimestamp = @LogTimeStamp
            Set @InEventRemark = @LogRemark
            Set @InEventTerminalIP = @LogTerminalIP
            Set @InEventTerminalSN = @LogTerminalSN

            If (@FirstRecord = 1) -- save for first in event record of the day
            Begin
                Set @FirstInEvent = @LogTimestamp
                Set @FirstInRemark = @LogRemark
                Set @FirstInTerminalIP = @LogTerminalIP
                Set @FirstInTerminalSN = @LogTerminalSN
                Set @CurrTotalHours = 0 --initialise total hours for another day
            End

            Set @FirstRecord = 0 -- no more first record of the day
            Set @ReceiveInEvent = 1 -- indicate we have received an "IN" event
            Set @FirstEvent = 0  -- no more "first" event
        End
        Else If LOWER(@LogEventID) = 'out' -- OUT event
        Begin
            If @FirstEvent = 1 -- the first OUT record when change users 
            Begin
                -- Check day
                If (@CurrentDay != @LogDay) -- change to another day
                    Set @PivotValue = 0 -- Reset
                Else
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @LogDay -- update the day

                -- Only an OUT event (no IN event) - invalid record but we show it anyway
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                    PivotValue, LogDate )
                values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                    DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)))                                              

                Set @FirstEvent = 0 -- not "first" anymore
            End
            Else -- Not first event
            Begin       

                If @ReceiveInEvent = 1 -- if there are IN event previously
                Begin           
                    -- Check day
                    If (@CurrentDay != @InEventDay) -- change to another day                        
                        Set @PivotValue = 0 -- Reset                        
                    Else
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @InEventDay -- update the day     
                    Set @CurrTotalHours = @CurrTotalHours +  DATEDIFF(second,@InEventTimestamp, @LogTimeStamp) -- update total time             

                    Set @OutEventRemark = @LogRemark
                    Set @OutEventTerminalIP = @LogTerminalIP
                    Set @OutEventTerminalSN = @LogTerminalSN
                    Set @OutEventTimestamp = @LogTimestamp          
                    -- valid row
                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @InEventDay, @InEventTimestamp, @LogTimestamp,  Datediff(second, @InEventTimestamp, @LogTimeStamp),
                    --  @InEventRemark, @LogRemark, @InEventTerminalIP, @LogTerminalIP, @InEventTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                      

                    Set @ReceiveInEvent = 0 -- Reset
                End
                Else -- no IN event previously
                Begin
                    -- Check day
                    If (@CurrentDay != @LogDay) -- change to another day
                        Set @PivotValue = 0 -- Reset
                    Else
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @LogDay -- update the day                         

                    -- invalid row (only has OUT event)
                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                        PivotValue, LogDate )
                    values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)) )             
                End             
            End         
        End

        Set @CurrentUser = @LogUserID -- update user        

        Fetch Next 
        From LogCursor
        Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
    End 

    -- Need to handle the last log if its IN log as it will not be processed by the while loop
    if @CurrTrigger='in'
    Begin 
    -- Check day
            If (@CurrentDay != @InEventDay) -- change to another day
                Set @PivotValue = 0 -- Reset
            Else -- same day
                Set @PivotValue = @PivotValue + 1 -- increment
            Set @CurrentDay = @InEventDay -- update the day

            -- invalid row (only has IN event)
            Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                TerminalSNTimeIn, PivotValue, LogDate )
            values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))     
    End
    else if @CurrTrigger = 'out'
    Begin
        Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
        LogDate)
        values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
        @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  
    End

    Close LogCursor
    Deallocate LogCursor

    Select * 
    From @tempInOutDetailReport tempTable
        Left Join access_user on access_user.User_ID = tempTable.UserID
    Order By tempTable.UserID, LogDate


End



If @@TranCount > @TransactionCountOnEntry
Begin
     If @ErrorCode = 0
            COMMIT TRANSACTION
     Else
            ROLLBACK TRANSACTION
End

return @ErrorCode

you will get the "java SQL Code" by right click on stored procedure in your database. something like this :

DECLARE @RC int
DECLARE @pUserID nvarchar(50)
DECLARE @pDepartmentID int
DECLARE @pStartDateTime datetime
DECLARE @pEndDateTime datetime

-- TODO: Set parameter values here.

EXECUTE @RC = [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] 
@pUserID,@pDepartmentID,@pStartDateTime,@pEndDateTime
GO

check the query String I've done, that is your homework ;) so sorry answering this long, this is my first answer since I register few weeks ago to get answer.

how to read a text file using scanner in Java?

This should help you..:

import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
    find(Recipe);
}
public void find(String Name){
    String newRecipe= Name+".txt";
    try{
        FileReader fr= new FileReader(newRecipe);
        BufferedReader br= new BufferedReader(fr);

        String str;


    while ((str=br.readLine()) != null){
            out.println(str + "\n");
        }
        br.close();

    }catch (IOException e){
        out.println("File Not Found!");
    }
}

}

ContractFilter mismatch at the EndpointDispatcher exception

As mentioned in other answers, such as @chinto, this happens when the SOAP:Action header element does not match the Endpoint.

You can find the correct URI to use by looking at the server's WSDL. You will see an operation element with an input child that has an "Action" attribute. That is what your SOAP:Action needs to be on the client request.

<wsdl:operation name="MethodName">
<wsdl:input wsaw:Action="http://tempuri.org/IInterface/MethodName" message="tns:IInterface_MethodName_InputMessage"/>
<wsdl:output wsaw:Action="http://tempuri.org/IInterface/MethodNameResponse" message="tns:IInterface_MethodName_OutputMessage"/>
</wsdl:operation>

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;

How to add items into a numpy array

import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
b = np.array([10,20,30])
c = np.hstack((a, np.atleast_2d(b).T))

returns c:

array([[ 1,  3,  4, 10],
       [ 1,  2,  3, 20],
       [ 1,  2,  1, 30]])

Comparing arrays in JUnit assertions, concise built-in way?

Use org.junit.Assert's method assertArrayEquals:

import org.junit.Assert;
...

Assert.assertArrayEquals( expectedResult, result );

If this method is not available, you may have accidentally imported the Assert class from junit.framework.

How can I use a for each loop on an array?

what about this simple inArray function:

Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function

.Net picking wrong referenced assembly version

I had the same message when switching between two versions of an application that referenced different versions of the same DLL. Although I was testing in different folders I accidentally copied the newer version over the older version.

So the first thing to check is the version of the referenced DLL in the application's folder. Just in case.

How to capitalize the first letter of a String in Java?

if you use SPRING:

import static org.springframework.util.StringUtils.capitalize;
...


    return capitalize(name);

IMPLEMENTATION: https://github.com/spring-projects/spring-framework/blob/64440a5f04a17b3728234afaa89f57766768decb/spring-core/src/main/java/org/springframework/util/StringUtils.java#L535-L555

REF: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html#capitalize-java.lang.String-


NOTE: If you already have Apache Common Lang dependency, then consider using their StringUtils.capitalize as other answers suggest.

Compiling C++ on remote Linux machine - "clock skew detected" warning

The other answers here do a good job of explaining the issue, so I won't repeat that here. But there is one solution that can resolve it that isn't listed yet: simply run make clean, then rerun make.

Having make remove any already compiled files will prevent make from having any files to compare the timestamps of, resolving the warning.

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

Why maven? What are the benefits?

Maven advantages over ant are quite a few. I try to summarize them here.

Convention over Configuration
Maven uses a distinctive approach for the project layout and startup, that makes easy to just jump in a project. Usually it only takes the checkount and the maven command to get the artifacts of the project.

Project Modularization
Project conventions suggest (or better, force) the developer to modularize the project. Instead of a monolithic project you are often forced to divide your project in smaller sub components, which make it easier debug and manage the overall project structure

Dependency Management and Project Lifecycle
Overall, with a good SCM configuration and an internal repository, the dependency management is quite easy, and you are again forced to think in terms of Project Lifecycle - component versions, release management and so on. A little more complex than the ant something, but again, an improvement in quality of the project.

What is wrong with maven?
Maven is not easy. The build cycle (what gets done and when) is not so clear within the POM. Also, some issue arise with the quality of components and missing dependencies in public repositories.
The best approach (to me) is to have an internal repository for caching (and keeping) dependencies around, and to apply to release management of components. For projects bigger than the sample projects in a book, you will thank maven before or after

Using custom std::set comparator

You can use a function comparator without wrapping it like so:

bool comparator(const MyType &lhs, const MyType &rhs)
{
    return [...];
}

std::set<MyType, bool(*)(const MyType&, const MyType&)> mySet(&comparator);

which is irritating to type out every time you need a set of that type, and can cause issues if you don't create all sets with the same comparator.

QR Code encoding and decoding using zxing

this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters

package com.mypackage.qr;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;

public class CreateQR {

public static void main(String[] args)
{
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
        // Convert a string to UTF-8 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data;
    try {
        data = new String(b, "UTF-8");
        // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 100;
        int w = 100;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            matrix = writer.encode(data,
            com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
        } catch (com.google.zxing.WriterException e) {
            System.out.println(e.getMessage());
        }

        // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
                String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }
}

}

Java: how do I get a class literal from a generic type?

You can't due to type erasure.

Java generics are little more than syntactic sugar for Object casts. To demonstrate:

List<Integer> list1 = new ArrayList<Integer>();
List<String> list2 = (List<String>)list1;
list2.add("foo"); // perfectly legal

The only instance where generic type information is retained at runtime is with Field.getGenericType() if interrogating a class's members via reflection.

All of this is why Object.getClass() has this signature:

public final native Class<?> getClass();

The important part being Class<?>.

To put it another way, from the Java Generics FAQ:

Why is there no class literal for concrete parameterized types?

Because parameterized type has no exact runtime type representation.

A class literal denotes a Class object that represents a given type. For instance, the class literal String.class denotes the Class object that represents the type String and is identical to the Class object that is returned when method getClass is invoked on a String object. A class literal can be used for runtime type checks and for reflection.

Parameterized types lose their type arguments when they are translated to byte code during compilation in a process called type erasure . As a side effect of type erasure, all instantiations of a generic type share the same runtime representation, namely that of the corresponding raw type . In other words, parameterized types do not have type representation of their own. Consequently, there is no point in forming class literals such as List<String>.class , List<Long>.class and List<?>.class , since no such Class objects exist. Only the raw type List has a Class object that represents its runtime type. It is referred to as List.class.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Following up on David's answer...

Using SHOW SLAVE STATUS\G will give human-readable output.

"Faceted Project Problem (Java Version Mismatch)" error message

I encountered this issue while running an app on Java 1.6 while I have all three versions of Java 6,7,8 for different apps.I accessed the Navigator View and manually removed the unwanted facet from the facet.core.xml .Clean build and wallah!

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

<fixed facet="jst.java"/>

<fixed facet="jst.web"/>

<installed facet="jst.web" version="2.4"/>

<installed facet="jst.java" version="6.0"/>

<installed facet="jst.utility" version="1.0"/>

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

I Had the same issue on a service running on IIS 7 the service connects to multiple suppliers servers (some SSL some not) when adding a new one of these (this new supplier was TLS 1.2) I would get the error after a few requests were made to the original servers (SSL).

To confirm this I simply logged the System.Net.ServicePointManager.SecurityProtocol before each request to each supplier.

Low and behold after restarting the service (or restarting the application pool) I would get the output Ssl3, Tls but after a few requests to the original supplier servers this changed to Ssl3 and requests to the TLS service gave the error.

To fix I simply did what user369142 suggested. Before each request to the new server:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

and no more errors.

Ruby/Rails: converting a Date to a UNIX timestamp

The suggested options of using to_utc or utc to fix the local time offset does not work. For me I found using Time.utc() worked correctly and the code involves less steps:

> Time.utc(2016, 12, 25).to_i
=> 1482624000 # correct

vs

> Date.new(2016, 12, 25).to_time.utc.to_i
=> 1482584400 # incorrect

Here is what happens when you call utc after using Date....

> Date.new(2016, 12, 25).to_time
=> 2016-12-25 00:00:00 +1100 # This will use your system's time offset
> Date.new(2016, 12, 25).to_time.utc
=> 2016-12-24 13:00:00 UTC

...so clearly calling to_i is going to give the wrong timestamp.

How to recover Git objects damaged by hard disk failure?

The solution by Daniel Fanjul looked promissing. I was able to find that blob file and extracted it ("git fsck --full --no-dangling", "git cat-file -t {hash}", "git show {hash} > file.tmp") but when I tried to update pack file with "git hash-object -w file.tmp", it displayed correct hash BUT the error remained.

So I decided to try different approach. I could simply delete local repository and download everything from remote but some branches in local repository were 8 commits ahead and I did not want to lose those changes. Since that tiny, 6kb mp3 file, I decided to delete it completely. I tried many ways but the best was from here: https://itextpdf.com/en/blog/technical-notes/how-completely-remove-file-git-repository

I got the file name by running this command "git rev-list --objects --all | grep {hash}". Then I did a backup (strongly recommend to do so because I failed 3 times) and then run the command:

"java -jar bfg.jar --delete-files {filename} --no-blob-protection ."

You can get bfg.jar file from here https://rtyley.github.io/bfg-repo-cleaner/ so according to documentation I should run this command next:

"git reflog expire --expire=now --all && git gc --prune=now --aggressive"

When I did so, I got errors on last step. So I recovered everything from backup and this time, after removing file, I checkout to the branch (which was causing that error), then check out back to main and only after run the command one after each other:

"git reflog expire --expire=now --all" "git gc --prune=now --aggressive"

Then I added my file back to its location and comit. However, since many local commits were changed, I was not able to push anything to server. So I backup everything on server (in case I screw it), check out to the branch which was affected and run the command "git push --force".

What I understood from this case? GIT is great but so senstive... I should have an option to simply disregard one f... 6kb file I know what I am doing. I have no clude why "git hash-object -w" did not work either =( Lessons learnt, push all commits, do not wait, do backup of repository time to time. Also I know how to remove files from repository, if I ever need =)

I hope this saves someone's time

Ship an application with a database

Finally I did it!! I have used this link help Using your own SQLite database in Android applications, but had to change it a little bit.

  1. If you have many packages you should put the master package name here:

    private static String DB_PATH = "data/data/masterPakageName/databases";

  2. I changed the method which copies the database from local folder to emulator folder! It had some problem when that folder didn't exist. So first of all, it should check the path and if it's not there, it should create the folder.

  3. In the previous code, the copyDatabase method was never called when the database didn't exist and the checkDataBase method caused exception. so I changed the code a little bit.

  4. If your database does not have a file extension, don't use the file name with one.

it works nice for me , i hope it whould be usefull for u too

    package farhangsarasIntroduction;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import android.util.Log;


    public class DataBaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH = "data/data/com.example.sample/databases";

    private static String DB_NAME = "farhangsaraDb";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    /**
      * Constructor
      * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
      * @param context
      */
    public DataBaseHelper(Context context) {

        super(context, DB_NAME, null, 1);
            this.myContext = context;

    }   

    /**
      * Creates a empty database on the system and rewrites it with your own database.
      * */
    public void createDataBase() {

        boolean dbExist;
        try {

             dbExist = checkDataBase();


        } catch (SQLiteException e) {

            e.printStackTrace();
            throw new Error("database dose not exist");

        }

        if(dbExist){
        //do nothing - database already exist
        }else{

            try {

                copyDataBase();


            } catch (IOException e) {

                e.printStackTrace();
                throw new Error("Error copying database");

            }
    //By calling this method and empty database will be created into the default system path
    //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();


    }

    }

    /**
      * Check if the database already exist to avoid re-copying the file each time you open the application.
      * @return true if it exists, false if it doesn't
      */
    private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH +"/"+ DB_NAME;

        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }catch(SQLiteException e){

    //database does't exist yet.
        throw new Error("database does't exist yet.");

    }

    if(checkDB != null){

    checkDB.close();

    }

    return checkDB != null ? true : false;
    }

    /**
      * Copies your database from your local assets-folder to the just created empty database in the
      * system folder, from where it can be accessed and handled.
      * This is done by transfering bytestream.
      * */
    private void copyDataBase() throws IOException{



            //copyDataBase();
            //Open your local db as the input stream
            InputStream myInput = myContext.getAssets().open(DB_NAME);

            // Path to the just created empty db
            String outFileName = DB_PATH +"/"+ DB_NAME;
            File databaseFile = new File( DB_PATH);
             // check if databases folder exists, if not create one and its subfolders
            if (!databaseFile.exists()){
                databaseFile.mkdir();
            }

            //Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
            }

            //Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();



    }



    @Override
    public synchronized void close() {

        if(myDataBase != null)
        myDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

     you to create adapters for your views.

}

UTF-8 all the way through

if you want a mysql solution, I had similar issues with 2 of my projects, after a server migration. After searching and trying a lot of solutions i came across with this one /nothing before this one worked):

mysqli_set_charset($con,"utf8");

After adding this line to my config file everything works fine!

I found this solution https://www.w3schools.com/PHP/func_mysqli_set_charset.asp when i was looking to solve a insert from html query

good luck!

Find where java class is loaded from

getClass().getProtectionDomain().getCodeSource().getLocation();

Most efficient way to check for DBNull and then assign to a variable?

I always use :

if (row["value"] != DBNull.Value)
  someObject.Member = row["value"];

Found it short and comprehensive.

How do I format a Microsoft JSON date?

If you say in JavaScript,

var thedate = new Date(1224043200000);
alert(thedate);

you will see that it's the correct date, and you can use that anywhere in JavaScript code with any framework.

Hive cast string to date dd-MM-yyyy

try:

from_unixtime(unix_timestamp('12-03-2010' , 'dd-MM-yyyy'))

Disable single warning error

Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push), #pragma warning (disable) and a matching #pragma warning (pop), as shown here.

Although there are some other options, including #pramga warning (once).

Read data from a text file using Java

public class FilesStrings {

public static void main(String[] args) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream("input.txt");
    InputStreamReader input = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(input);
    String data;
    String result = new String();

    while ((data = br.readLine()) != null) {
        result = result.concat(data + " ");
    }

    System.out.println(result);

With Spring can I make an optional path variable?

Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false now:

  @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
  public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
    if (type != null) {
      // ...
    }
    return new TestBean();
  }

Can't ignore UserInterfaceState.xcuserstate

In case that the ignored file kept showing up in the untracked list, you may use git clean -f -d to clear things up.

1.

git rm --cached {YourProjectFolderName}.xcodeproj/project.xcworkspace/xcuserdata/{yourUserName}.xcuserdatad/UserInterfaceState.xcuserstate

2.

git commit -m "Removed file that shouldn't be tracked"

3. WARNING first try git clean -f -d --dry-run, otherwise you may lose uncommited changes.

Then: git clean -f -d

Putting GridView data in a DataTable

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    DataTable _datatable = new DataTable();
    for (int i = 0; i < grdReport.Columns.Count; i++)
    {
        _datatable.Columns.Add(grdReport.Columns[i].ToString());
    }
    foreach (GridViewRow row in grdReport.Rows)
    {
        DataRow dr = _datatable.NewRow();
        for (int j = 0; j < grdReport.Columns.Count; j++)
        {
            if (!row.Cells[j].Text.Equals("&nbsp;"))
                dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
        }

        _datatable.Rows.Add(dr);
    }
    ExportDataTableToExcel(_datatable);
}

extract column value based on another column pandas dataframe

Use df[df['B']==3]['A'].values if you just want item itself without the brackets

Difference between PCDATA and CDATA in DTD

  • PCDATA is text that will be parsed by a parser. Tags inside the text will be treated as markup and entities will be expanded.
  • CDATA is text that will not be parsed by a parser. Tags inside the text will not be treated as markup and entities will not be expanded.

By default, everything is PCDATA. In the following example, ignoring the root, <bar> will be parsed, and it'll have no content, but one child.

<?xml version="1.0"?>
<foo>
<bar><test>content!</test></bar>
</foo>

When we want to specify that an element will only contain text, and no child elements, we use the keyword PCDATA, because this keyword specifies that the element must contain parsable character data – that is , any text except the characters less-than (<) , greater-than (>) , ampersand (&), quote(') and double quote (").

In the next example, <bar> contains CDATA. Its content will not be parsed and is thus <test>content!</test>.

<?xml version="1.0"?>
<foo>
<bar><![CDATA[<test>content!</test>]]></bar>
</foo>

There are several content models in SGML. The #PCDATA content model says that an element may contain plain text. The "parsed" part of it means that markup (including PIs, comments and SGML directives) in it is parsed instead of displayed as raw text. It also means that entity references are replaced.

Another type of content model allowing plain text contents is CDATA. In XML, the element content model may not implicitly be set to CDATA, but in SGML, it means that markup and entity references are ignored in the contents of the element. In attributes of CDATA type however, entity references are replaced.

In XML, #PCDATA is the only plain text content model. You use it if you at all want to allow text contents in the element. The CDATA content model may be used explicitly through the CDATA block markup in #PCDATA, but element contents may not be defined as CDATA per default.

In a DTD, the type of an attribute that contains text must be CDATA. The CDATA keyword in an attribute declaration has a different meaning than the CDATA section in an XML document. In a CDATA section all characters are legal (including <,>,&,' and " characters), except the ]]> end tag.

#PCDATA is not appropriate for the type of an attribute. It is used for the type of "leaf" text.

#PCDATA is prepended by a hash in the content model to distinguish this keyword from an element named PCDATA (which would be perfectly legal).

comparing strings in vb

If String.Compare(string1,string2,True) Then

    'perform operation

EndIf

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

How do I load an HTML page in a <div> using JavaScript?

showhide.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript">
        function showHide(switchTextDiv, showHideDiv)
        {
          var std = document.getElementById(switchTextDiv);
          var shd = document.getElementById(showHideDiv);
          if (shd.style.display == "block")
          {
            shd.style.display = "none";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
          }
          else
          {
            if (shd.innerHTML.length <= 0)
            {
              shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
            }
            shd.style.display = "block";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
          }
        }
      </script>
    </head>
    <body>
      <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
        <span style="display: block; background-color: yellow">Show</span>
      </a>
      <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
    </body>
</html>

showhide_embedded.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript"> 
        function load()
        {
          var ts = document.getElementById("theString");
          ts.scrollIntoView(true);
        }
      </script>
    </head>
    <body onload="load()">
      <pre>
        some text 1
        some text 2
        some text 3
        some text 4
        some text 5
        <span id="theString" style="background-color: yellow">some text 6 highlight</span>
        some text 7
        some text 8
        some text 9
      </pre>
    </body>
</html>

How to save DataFrame directly to Hive?

Saving to Hive is just a matter of using write() method of your SQLContext:

df.write.saveAsTable(tableName)

See https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/DataFrameWriter.html#saveAsTable(java.lang.String)

From Spark 2.2: use DataSet instead DataFrame.

Hosting a Maven repository on github

Don't use GitHub as a Maven Repository.

Edit: This option gets a lot of down votes, but no comments as to why. This is the correct option regardless of the technical capabilities to actually host on GitHub. Hosting on GitHub is wrong for all the reasons outlined below and without comments I can't improve the answer to clarify your issues.

Best Option - Collaborate with the Original Project

The best option is to convince the original project to include your changes and stick with the original.

Alternative - Maintain your own Fork

Since you have forked an open source library, and your fork is also open source, you can upload your fork to Maven Central (read Guide to uploading artifacts to the Central Repository) by giving it a new groupId and maybe a new artifactId.

Only consider this option if you are willing to maintain this fork until the changes are incorporated into the original project and then you should abandon this one.

Really consider hard whether a fork is the right option. Read the myriad Google results for 'why not to fork'

Reasoning

Bloating your repository with jars increases download size for no benefit

A jar is an output of your project, it can be regenerated at any time from its inputs, and your GitHub repo should contain only inputs.

Don't believe me? Then check Google results for 'dont store binaries in git'.

GitHub's help Working with large files will tell you the same thing. Admittedly jar's aren't large but they are larger than the source code and once a jar has been created by a release they have no reason to be versioned - that is what a new release is for.

Defining multiple repos in your pom.xml slows your build down by Number of Repositories times Number of Artifacts

Stephen Connolly says:

If anyone adds your repo they impact their build performance as they now have another repo to check artifacts against... It's not a big problem if you only have to add one repo... But the problem grows and the next thing you know your maven build is checking 50 repos for every artifact and build time is a dog.

That's right! Maven needs to check every artifact (and its dependencies) defined in your pom.xml against every Repository you have defined, as a newer version might be available in any of those repositories.

Try it out for yourself and you will feel the pain of a slow build.

The best place for artifacts is in Maven Central, as its the central place for jars, and this means your build will only ever check one place.

You can read some more about repositories at Maven's documentation on Introduction to Repositories

IntelliJ IDEA generating serialVersionUID

After spending some time on Serialization, I find that, we should not generate serialVersionUID with some random value, we should give it a meaningful value.

Here is a details comment on this. I am coping the comment here.

Actually, you should not be "generating" serial version UIDs. It is a dumb "feature" that stems from the general misunderstanding of how that ID is used by Java. You should be giving these IDs meaningful, readable values, e.g. starting with 1L, and incrementing them each time you think the new version of the class should render all previous versions (that might be previously serialized) obsolete. All utilities that generate such IDs basically do what the JVM does when the ID is not defined: they generate the value based on the content of the class file, hence coming up with unreadable meaningless long integers. If you want each and every version of your class to be distinct (in the eyes of the JVM) then you should not even specify the serialVersionUID value isnce the JVM will produce one on the fly, and the value of each version of your class will be unique. The purpose of defining that value explicitly is to tell the serialization mechanism to treat different versions of the class that have the same SVUID as if they are the same, e.g. not to reject the older serialized versions. So, if you define the ID and never change it (and I assume that's what you do since you rely on the auto-generation, and you probably never re-generate your IDs) you are ensuring that all - even absolutely different - versions of your class will be considered the same by the serialization mechanism. Is that what you want? If not, and if you indeed want to have control over how your objects are recognized, you should be using simple values that you yourself can understand and easily update when you decide that the class has changed significantly. Having a 23-digit value does not help at all.

Hope this helps. Good luck.

Can Linux apps be run in Android?

You can get an ARM cross compiler that runs on Linux here. You can also download the Android NDK and compile some command line apps. I do not have any personal experience with using C++ with either solution, but I have compiled a few simple things with both. It is my understanding that the NDK is not a full C++ compiler as there have been complaints that it will not compile some common C++ code.

Note that since I am a new user, I cannot post the NDK link... :/

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

For CentOS users (at least), one will also get a 404 error trying to access the server on port 8080 on a fresh install if the tomcat-webapps package is not installed.

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

Turn off axes in subplots

You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.

Rather than using plt.axis('off') you should use ax.axis('off') where ax is a matplotlib.axes object. To do this for your code you simple need to add axarr[0,0].axis('off') and so on for each of your subplots.

The code below shows the result (I've removed the prune_matrix part because I don't have access to that function, in the future please submit fully working code.)

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm

img = mpimg.imread("stewie.jpg")

f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')

axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')

axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')

axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')

plt.show()

Stewie example

Note: To turn off only the x or y axis you can use set_visible() e.g.:

axarr[0,0].xaxis.set_visible(False) # Hide only x axis

Automatically start forever (node) on system restart

An alternative crontab method inspired by this answer and this blog post.

1. Create a bash script file (change bob to desired user).

vi /home/bob/node_server_init.sh

2. Copy and paste this inside the file you've just created.

#!/bin/sh

export NODE_ENV=production
export PATH=/usr/local/bin:$PATH
forever start /node/server/path/server.js > /dev/null

Make sure to edit the paths above according to your config!

3. Make sure the bash script can be executed.

chmod 700 /home/bob/node_server_init.sh

4. Test the bash script.

sh /home/bob/node_server_init.sh

5. Replace "bob" with the runtime user for node.

crontab -u bob -e

6. Copy and paste (change bob to desired user).

@reboot /bin/sh /home/bob/node_server_init.sh

Save the crontab.

You've made it to the end, your prize is a reboot (to test) :)

How to convert FormData (HTML5 object) to JSON

FormData method .entries and the for of expression is not supported in IE11 and Safari.

Here is a simplier version to support Safari, Chrome, Firefox and Edge

function formDataToJSON(formElement) {    
    var formData = new FormData(formElement),
        convertedJSON = {};

    formData.forEach(function(value, key) { 
        convertedJSON[key] = value;
    });

    return convertedJSON;
}

Warning: this answer doesn't work in IE11.
FormData doesn't have a forEach method in IE11.
I'm still searching for a final solution to support all major browsers.

String escape into XML

WARNING: Necromancing

Still Darin Dimitrov's answer + System.Security.SecurityElement.Escape(string s) isn't complete.

In XML 1.1, the simplest and safest way is to just encode EVERYTHING.
Like &#09; for \t.
It isn't supported at all in XML 1.0.
For XML 1.0, one possible workaround is to base-64 encode the text containing the character(s).

//string EncodedXml = SpecialXmlEscape("?????? ???");
//Console.WriteLine(EncodedXml);
//string DecodedXml = XmlUnescape(EncodedXml);
//Console.WriteLine(DecodedXml);
public static string SpecialXmlEscape(string input)
{
    //string content = System.Xml.XmlConvert.EncodeName("\t");
    //string content = System.Security.SecurityElement.Escape("\t");
    //string strDelimiter = System.Web.HttpUtility.HtmlEncode("\t"); // XmlEscape("\t"); //XmlDecode("&#09;");
    //strDelimiter = XmlUnescape("&#59;");
    //Console.WriteLine(strDelimiter);
    //Console.WriteLine(string.Format("&#{0};", (int)';'));
    //Console.WriteLine(System.Text.Encoding.ASCII.HeaderName);
    //Console.WriteLine(System.Text.Encoding.UTF8.HeaderName);


    string strXmlText = "";

    if (string.IsNullOrEmpty(input))
        return input;


    System.Text.StringBuilder sb = new StringBuilder();

    for (int i = 0; i < input.Length; ++i)
    {
        sb.AppendFormat("&#{0};", (int)input[i]);
    }

    strXmlText = sb.ToString();
    sb.Clear();
    sb = null;

    return strXmlText;
} // End Function SpecialXmlEscape

XML 1.0:

public static string Base64Encode(string plainText)
{
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}

public static string Base64Decode(string base64EncodedData)
{
    var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
    return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Wordpress keeps redirecting to install-php after migration

I experienced a similar issue. None of the suggestions above helped me, though.

Eventually I realized that the Wordpress MySQL-user on my production environment had not been assigned sufficient privileges.

How to set recurring schedule for xlsm file using Windows Task Scheduler

Three important steps - How to Task Schedule an excel.xls(m) file

simply:

  1. make sure the .vbs file is correct
  2. set the Action tab correctly in Task Scheduler
  3. don't turn on "Run whether user is logged on or not"

IN MORE DETAIL...

  1. Here is an example .vbs file:

`

'   a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt  to .vbs

'Write Excel.xls  Sheet's full path here
strPath = "C:\RodsData.xlsm" 

'Write the macro name - could try including module name
strMacro = "Update" '    "Sheet1.Macro2" 

'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application") 
objApp.Visible = True   '   or False 

'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath) 
objApp.Run strMacro     '   wbToRun.Name & "!" & strMacro 
wbToRun.Save 
wbToRun.Close 
objApp.Quit 

'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!",         vbInformation 
'

`

  1. In the Action tab (Task Scheduler):

set Program/script: = C:\Windows\System32\cscript.exe

set Add arguments (optional): = C:\MyVbsFile.vbs

  1. Finally, don't turn on "Run whether user is logged on or not".

That should work.

Let me know!

Rod Bowen

Custom header to HttpClient request

var request = new HttpRequestMessage {
    RequestUri = new Uri("[your request url string]"),
    Method = HttpMethod.Post,
    Headers = {
        { "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
        { HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
        { HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
    },
    Content = new MultipartContent { // Just example of request sending multipart request
        new ObjectContent<[YOUR JSON OBJECT TYPE]>(
            new [YOUR JSON OBJECT TYPE INSTANCE](...){...}, 
            new JsonMediaTypeFormatter(), 
            "application/json"), // this will add 'Content-Type' header for the first part of request
        new ByteArrayContent([BINARY DATA]) {
            Headers = { // this will add headers for the second part of request
                { "Content-Type", "application/Executable" },
                { "Content-Disposition", "form-data; filename=\"test.pdf\"" },
            },
        },
    },
};

C#: Dynamic runtime cast

Try a generic:

public static T CastTo<T>(this dynamic obj, bool safeCast) where T:class
{
   try
   {
      return (T)obj;
   }
   catch
   {
      if(safeCast) return null;
      else throw;
   }
}

This is in extension method format, so its usage would be as if it were a member of dynamic objects:

dynamic myDynamic = new Something();
var typedObject = myDynamic.CastTo<Something>(false);

EDIT: Grr, didn't see that. Yes, you could reflectively close the generic, and it wouldn't be hard to hide in a non-generic extension method:

public static dynamic DynamicCastTo(this dynamic obj, Type castTo, bool safeCast)
{
   MethodInfo castMethod = this.GetType().GetMethod("CastTo").MakeGenericMethod(castTo);
   return castMethod.Invoke(null, new object[] { obj, safeCast });
}

I'm just not sure what you'd get out of this. Basically you're taking a dynamic, forcing a cast to a reflected type, then stuffing it back in a dynamic. Maybe you're right, I shouldn't ask. But, this'll probably do what you want. Basically when you go into dynamic-land, you lose the need to perform most casting operations as you can discover what an object is and does through reflective methods or trial and error, so there aren't many elegant ways to do this.

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

For properties configuration

# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.

How to make background of table cell transparent

Just set the opacity for the inner table. You can do inline CSS if you want it just for a specific table element, so it doesn't apply to the entire table.

style="opacity: 0%;"

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:

public List<Book> list() {
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from book").list();
    return list;
}

The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.

public List<Book> list() {                                                                               
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from Book").list();
    return list;
}

Index of duplicates items in a python list

I made a benchmark of all solutions suggested here and also added another solution to this problem (described in the end of the answer).

Benchmarks

First, the benchmarks. I initialize a list of n random ints within a range [1, n/2] and then call timeit over all algorithms

The solutions of @Paul McGuire and @Ignacio Vazquez-Abrams works about twice as fast as the rest on the list of 100 ints:

Testing algorithm on the list of 100 items using 10000 loops
Algorithm: dupl_eat
Timing: 1.46247477189
####################
Algorithm: dupl_utdemir
Timing: 2.93324529055
####################
Algorithm: dupl_lthaulow
Timing: 3.89198786645
####################
Algorithm: dupl_pmcguire
Timing: 0.583058259784
####################
Algorithm: dupl_ivazques_abrams
Timing: 0.645062989076
####################
Algorithm: dupl_rbespal
Timing: 1.06523873786
####################

If you change the number of items to 1000, the difference becomes much bigger (BTW, I'll be happy if someone could explain why) :

Testing algorithm on the list of 1000 items using 1000 loops
Algorithm: dupl_eat
Timing: 5.46171654555
####################
Algorithm: dupl_utdemir
Timing: 25.5582547323
####################
Algorithm: dupl_lthaulow
Timing: 39.284285326
####################
Algorithm: dupl_pmcguire
Timing: 0.56558489513
####################
Algorithm: dupl_ivazques_abrams
Timing: 0.615980005148
####################
Algorithm: dupl_rbespal
Timing: 1.21610942322
####################

On the bigger lists, the solution of @Paul McGuire continues to be the most efficient and my algorithm begins having problems.

Testing algorithm on the list of 1000000 items using 1 loops
Algorithm: dupl_pmcguire
Timing: 1.5019953958
####################
Algorithm: dupl_ivazques_abrams
Timing: 1.70856155898
####################
Algorithm: dupl_rbespal
Timing: 3.95820421595
####################

The full code of the benchmark is here

Another algorithm

Here is my solution to the same problem:

def dupl_rbespal(c):
    alreadyAdded = False
    dupl_c = dict()
    sorted_ind_c = sorted(range(len(c)), key=lambda x: c[x]) # sort incoming list but save the indexes of sorted items

    for i in xrange(len(c) - 1): # loop over indexes of sorted items
        if c[sorted_ind_c[i]] == c[sorted_ind_c[i+1]]: # if two consecutive indexes point to the same value, add it to the duplicates
            if not alreadyAdded:
                dupl_c[c[sorted_ind_c[i]]] = [sorted_ind_c[i], sorted_ind_c[i+1]]
                alreadyAdded = True
            else:
                dupl_c[c[sorted_ind_c[i]]].append( sorted_ind_c[i+1] )
        else:
            alreadyAdded = False
    return dupl_c

Although it's not the best it allowed me to generate a little bit different structure needed for my problem (i needed something like a linked list of indexes of the same value)

Trying to get property of non-object - Laravel 5

I had also this problem. Add code like below in the related controller (e.g. UserController)

$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

Concatenating bits in VHDL

Here is an example of concatenation operator:

architecture EXAMPLE of CONCATENATION is
   signal Z_BUS : bit_vector (3 downto 0);
   signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
   Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;

Determine a string's encoding in C#

The code below has the following features:

  1. Detection or attempted detection of UTF-7, UTF-8/16/32 (bom, no bom, little & big endian)
  2. Falls back to the local default codepage if no Unicode encoding was found.
  3. Detects (with high probability) unicode files with the BOM/signature missing
  4. Searches for charset=xyz and encoding=xyz inside file to help determine encoding.
  5. To save processing, you can 'taste' the file (definable number of bytes).
  6. The encoding and decoded text file is returned.
  7. Purely byte-based solution for efficiency

As others have said, no solution can be perfect (and certainly one can't easily differentiate between the various 8-bit extended ASCII encodings in use worldwide), but we can get 'good enough' especially if the developer also presents to the user a list of alternative encodings as shown here: What is the most common encoding of each language?

A full list of Encodings can be found using Encoding.GetEncodings();

// Function to detect the encoding for UTF-7, UTF-8/16/32 (bom, no bom, little
// & big endian), and local default codepage, and potentially other codepages.
// 'taster' = number of bytes to check of the file (to save processing). Higher
// value is slower, but more reliable (especially UTF-8 with special characters
// later on may appear to be ASCII initially). If taster = 0, then taster
// becomes the length of the file (for maximum reliability). 'text' is simply
// the string with the discovered encoding applied to the file.
public Encoding detectTextEncoding(string filename, out String text, int taster = 1000)
{
    byte[] b = File.ReadAllBytes(filename);

    //////////////// First check the low hanging fruit by checking if a
    //////////////// BOM/signature exists (sourced from http://www.unicode.org/faq/utf_bom.html#bom4)
    if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); }  // UTF-32, big-endian 
    else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; }    // UTF-32, little-endian
    else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; }     // UTF-16, big-endian
    else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; }              // UTF-16, little-endian
    else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8
    else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b,3,b.Length-3); return Encoding.UTF7; } // UTF-7


    //////////// If the code reaches here, no BOM/signature was found, so now
    //////////// we need to 'taste' the file to see if can manually discover
    //////////// the encoding. A high taster value is desired for UTF-8
    if (taster == 0 || taster > b.Length) taster = b.Length;    // Taster size can't be bigger than the filesize obviously.


    // Some text files are encoded in UTF8, but have no BOM/signature. Hence
    // the below manually checks for a UTF8 pattern. This code is based off
    // the top answer at: https://stackoverflow.com/questions/6555015/check-for-invalid-utf8
    // For our purposes, an unnecessarily strict (and terser/slower)
    // implementation is shown at: https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
    // For the below, false positives should be exceedingly rare (and would
    // be either slightly malformed UTF-8 (which would suit our purposes
    // anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot).
    int i = 0;
    bool utf8 = false;
    while (i < taster - 4)
    {
        if (b[i] <= 0x7F) { i += 1; continue; }     // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks.
        if (b[i] >= 0xC2 && b[i] <= 0xDF && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; }
        if (b[i] >= 0xE0 && b[i] <= 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; }
        if (b[i] >= 0xF0 && b[i] <= 0xF4 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; }
        utf8 = false; break;
    }
    if (utf8 == true) {
        text = Encoding.UTF8.GetString(b);
        return Encoding.UTF8;
    }


    // The next check is a heuristic attempt to detect UTF-16 without a BOM.
    // We simply look for zeroes in odd or even byte places, and if a certain
    // threshold is reached, the code is 'probably' UF-16.          
    double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10%
    int count = 0;
    for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++;
    if (((double)count) / taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; }
    count = 0;
    for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++;
    if (((double)count) / taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian)


    // Finally, a long shot - let's see if we can find "charset=xyz" or
    // "encoding=xyz" to identify the encoding:
    for (int n = 0; n < taster-9; n++)
    {
        if (
            ((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) ||
            ((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '='))
            )
        {
            if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9;
            if (b[n] == '"' || b[n] == '\'') n++;
            int oldn = n;
            while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z')))
            { n++; }
            byte[] nb = new byte[n-oldn];
            Array.Copy(b, oldn, nb, 0, n-oldn);
            try {
                string internalEnc = Encoding.ASCII.GetString(nb);
                text = Encoding.GetEncoding(internalEnc).GetString(b);
                return Encoding.GetEncoding(internalEnc);
            }
            catch { break; }    // If C# doesn't recognize the name of the encoding, break.
        }
    }


    // If all else fails, the encoding is probably (though certainly not
    // definitely) the user's local codepage! One might present to the user a
    // list of alternative encodings as shown here: https://stackoverflow.com/questions/8509339/what-is-the-most-common-encoding-of-each-language
    // A full list can be found using Encoding.GetEncodings();
    text = Encoding.Default.GetString(b);
    return Encoding.Default;
}

What does {0} mean when found in a string in C#?

It's a placeholder for the first parameter, which in your case evaluates to "wordpad.exe".

If you had an additional parameter, you'd use {1}, etc.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Use Rescue mode with cd and mount the filesystem. Try to check if any binary files or folder are deleted. If deleted you will have to manually install the rpms to get those files back.

https://askubuntu.com/questions/92946/cannot-boot-because-kernel-panic-not-syncing-attempted-to-kill-init

Regular expression to match a word or its prefix

I test examples in js. Simplest solution - just add word u need inside / /:

var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result

Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:

var reg = /\bcat\b/
reg.test('acatb');//1 test 
false // result
reg.test('have cat here');//2 test
true // result

We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.

var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5

If we need get all matched words in string/sentence/text, we can use g modifier (global match):

"cat good cat good cat".match(/\bcat\b/g).length
// 3 

Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.

"bad dog bad".match(/\bcat|dog\b/g).length
// 1

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Some special characters give this type of error, so use

$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";

Applying an ellipsis to multiline text

After looking all over the internet and trying a lot of these options, the only way to make sure that it is covered correctly with support for i.e is through javascript, i created a loop function to go over post items that require multi line truncation.

*note i used Jquery, and requires your post__items class to have a fixed max-height.

// loop over post items
$('.post__items').each(function(){
    var textArray = $(this).text().split(' ');
    while($(this).prop('scrollHeight') > $(this).prop('offsetHeight')) {
        textArray.pop();
        $(this).text(textArray.join(' ') + '...');
     }
});

Move SQL Server 2008 database files to a new folder location

You can use Detach/Attach Option in SQL Server Management Studio.

Check this: Move a Database Using Detach and Attach

Fastest method of screen capturing on Windows

I realize the following suggestion doesn't answer your question, but the simplest method I have found to capture a rapidly-changing DirectX view, is to plug a video camera into the S-video port of the video card, and record the images as a movie. Then transfer the video from the camera back to an MPG, WMV, AVI etc. file on the computer.

'POCO' definition

To add the the other answers, the POxx terms all appear to stem from POTS (Plain old telephone services).

The POX, used to define simple (plain old) XML, rather than the complex multi-layered stuff associated with REST, SOAP etc, was a useful, and vaguely amusing, term. PO(insert language of choice)O terms have rather worn the joke thin.

How do I convert from a money datatype in SQL server?

You can try like this:

SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)

Matplotlib scatter plot with different text at each data point

This might be useful when you need individually annotate in different time (I mean, not in a single for loop)

ax = plt.gca()
ax.annotate('your_lable', (x,y)) 

where x and y are the your target coordinate and type is float/int.

shorthand If Statements: C#

To use shorthand to get the direction:

int direction = column == 0
                ? 0
                : (column == _gridSize - 1 ? 1 : rand.Next(2));

To simplify the code entirely:

if (column == gridSize - 1 || rand.Next(2) == 1)
{
}
else
{
}

Input text dialog Android

How about this EXAMPLE? It seems straightforward.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
  .setTitle("Moustachify Link")
  .setMessage("Paste in the link of an image to moustachify!")
  .setView(txtUrl)
  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String url = txtUrl.getText().toString();
      moustachify(null, url);
    }
  })
  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    }
  })
  .show(); 

Use string in switch case in java

String value = someMethod();
switch(0) {
default:
    if ("apple".equals(value)) {
        method1();
        break;
    }
    if ("carrot".equals(value)) {
        method2();
        break;
    }
    if ("mango".equals(value)) {
        method3();
        break;
    }
    if ("orance".equals(value)) {
        method4();
        break;
    }
}

Saving any file to in the database, just convert it to a byte array?

What database are you using? normally you don't save files to a database but i think sql 2008 has support for it...

A file is binary data hence UTF 8 does not matter here..

UTF 8 matters when you try to convert a string to a byte array... not a file to byte array.

Error on line 2 at column 1: Extra content at the end of the document

On each loop of the result set, you're appending a new root element to the document, creating an XML document like this:

<?xml version="1.0"?>
<mycatch>...</mycatch>
<mycatch>...</mycatch>
...

An XML document can only have one root element, which is why the error is stating there is "extra content". Create a single root element and add all the mycatch elements to that:

$root = $dom->createElement("root");
$dom->appendChild($root);
// ...
while ($row = @mysql_fetch_assoc($result)){
  $node = $dom->createElement("mycatch");
  $root->appendChild($node);

Excel - extracting data based on another list

New Excel versions

=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)

Older Excel versions

=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)

That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

How to $http Synchronous call with AngularJS

I have worked with a factory integrated with google maps autocomplete and promises made??, I hope you serve.

http://jsfiddle.net/the_pianist2/vL9nkfe3/1/

you only need to replace the autocompleteService by this request with $ http incuida being before the factory.

app.factory('Autocomplete', function($q, $http) {

and $ http request with

 var deferred = $q.defer();
 $http.get('urlExample').
success(function(data, status, headers, config) {
     deferred.resolve(data);
}).
error(function(data, status, headers, config) {
     deferred.reject(status);
});
 return deferred.promise;

<div ng-app="myApp">
  <div ng-controller="myController">
  <input type="text" ng-model="search"></input>
  <div class="bs-example">
     <table class="table" >
        <thead>
           <tr>
              <th>#</th>
              <th>Description</th>
           </tr>
        </thead>
        <tbody>
           <tr ng-repeat="direction in directions">
              <td>{{$index}}</td>
              <td>{{direction.description}}</td>
           </tr>
        </tbody>
     </table>
  </div>

'use strict';
 var app = angular.module('myApp', []);

  app.factory('Autocomplete', function($q) {
    var get = function(search) {
    var deferred = $q.defer();
    var autocompleteService = new google.maps.places.AutocompleteService();
    autocompleteService.getPlacePredictions({
        input: search,
        types: ['geocode'],
        componentRestrictions: {
            country: 'ES'
        }
    }, function(predictions, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            deferred.resolve(predictions);
        } else {
            deferred.reject(status);
        }
    });
    return deferred.promise;
};

return {
    get: get
};
});

app.controller('myController', function($scope, Autocomplete) {
$scope.$watch('search', function(newValue, oldValue) {
    var promesa = Autocomplete.get(newValue);
    promesa.then(function(value) {
        $scope.directions = value;
    }, function(reason) {
        $scope.error = reason;
    });
 });

});

the question itself is to be made on:

deferred.resolve(varResult); 

when you have done well and the request:

deferred.reject(error); 

when there is an error, and then:

return deferred.promise;

What is web.xml file and what are all things can I do with it?

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

How to get UTF-8 working in Java webapps?

I'm with a similar problem, but, in filenames of a file I'm compressing with apache commons. So, i resolved it with this command:

convmv --notest -f cp1252 -t utf8 * -r

it works very well for me. Hope it help anyone ;)

iOS: Convert UTC NSDate to local Timezone

Swift 3+: UTC to Local and Local to UTC

extension Date {

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }
}

Swift: Convert enum value to String?

In swift 3, you can use this

var enumValue = Customer.Physics
var str = String(describing: enumValue)

from Swift how to use enum to get string value

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

This can also depend on the way you are invoking the SP from your C# code. If the SP returns some table type value then invoke the SP with ExecuteStoreQuery, and if the SP doesn't returns any value invoke the SP with ExecuteStoreCommand

How to add a set path only for that batch file executing?

There is an important detail:

set PATH="C:\linutils;C:\wingit\bin;%PATH%"

does not work, while

set PATH=C:\linutils;C:\wingit\bin;%PATH%

works. The difference is the quotes!

UPD also see the comment by venimus

Use Font Awesome icon as CSS content

You should have font-weight set to 900 for Font Awesome 5 Free font-family to work.

This is the working one:

.css-selector::before {
   font-family: 'Font Awesome 5 Free';
   content: "\f101";
   font-weight: 900;
}

How to Reload ReCaptcha using JavaScript?

For reCaptcha v2, use:

grecaptcha.reset();

If you're using reCaptcha v1 (probably not):

Recaptcha.reload();

This will do if there is an already loaded Recaptcha on the window.

(Updated based on @SebiH's comment below.)

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

How to run java application by .bat file

It's the same way you run it from command line. Just put that "command line" into a ".bat" file.

So, if you use java -cp .;foo.jar Bar, put that into a .bat file as

@echo off

java -cp .;foo.jar Bar

How remove border around image in css?

I usually use this on the top of css file.

img {
   border: none;
}

app-release-unsigned.apk is not signed

signingConfigs should be before buildTypes

signingConfigs {
        debug {
            storeFile file("debug.keystore")
        }

        myConfig {
            storeFile file("other.keystore")
            storePassword "android"
            keyAlias "androidotherkey"
            keyPassword "android"
        }
    }

    buildTypes {
        bar {
            debuggable true
            jniDebugBuild true
            signingConfig signingConfigs.debug
        }
        foo {
            debuggable false
            jniDebugBuild false
            signingConfig signingConfigs.myConfig
        }
    }

How To Raise Property Changed events on a Dependency Property?

I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.

public static readonly DependencyProperty CustomerProperty = 
    DependencyProperty.Register("Customer", typeof(Customer),
        typeof(CustomerDetailView),
        new PropertyMetadata(OnCustomerChangedCallBack));

public Customer Customer {
    get { return (Customer)GetValue(CustomerProperty); }
    set { SetValue(CustomerProperty, value); }
}

private static void OnCustomerChangedCallBack(
        DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    CustomerDetailView c = sender as CustomerDetailView;
    if (c != null) {
        c.OnCustomerChanged();
    }
}

protected virtual void OnCustomerChanged() {
    // Grab related data.
    // Raises INotifyPropertyChanged.PropertyChanged
    OnPropertyChanged("Customer");
}

Webpack not excluding node_modules

If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true in your tsconfig.json file.

ClassNotFoundException com.mysql.jdbc.Driver

In netbean Right click on your project, then you click on Libraries, then Run tab, add library, then select mysql connector

non static method cannot be referenced from a static context

In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.

Here's something you might want to do:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.

Run PHP Task Asynchronously

If you don't want the full blown ActiveMQ, I recommend to consider RabbitMQ. RabbitMQ is lightweight messaging that uses the AMQP standard.

I recommend to also look into php-amqplib - a popular AMQP client library to access AMQP based message brokers.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

How can I mock the JavaScript window object using Jest?

In your Jest configuration, add setupFilesAfterEnv: ["./setupTests.js"], create that file, and add the code you want to run before the tests:

// setupTests.js
window.crypto = {
   .....
};

Reference: setupFilesAfterEnv [array]

How to scroll HTML page to given anchor?

the easiest way to to make the browser to scroll the page to a given anchor is to type in your style.css *{scroll-behavior: smooth;} and in your html navigation use #NameOfTheSection

_x000D_
_x000D_
*{scroll-behavior: smooth;}
_x000D_
<a href="#scroll-to">Home<a/>

<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>

<section id="scroll-to">
<p>it will scroll down to this section</p>
</section>
_x000D_
_x000D_
_x000D_

Update Git branches from master

@cmaster made the best elaborated answer. In brief:

git checkout master #
git pull # update local master from remote master
git checkout <your_branch>
git merge master # solve merge conflicts if you have`

You should not rewrite branch history instead keep them in actual state for future references. While merging to master, it creates one extra commit but that is cheap. Commits does not cost.

Understanding repr( ) function in Python

When you say

foo = 'bar'
baz(foo)

you are not passing foo to the baz function. foo is just a name used to represent a value, in this case 'bar', and that value is passed to the baz function.

What does "fatal: bad revision" mean?

Why are you specifying myFile there?

Git revert reverts the commit(s) that you specify.

git revert HEAD~2

reverts the HEAD~2 commit

git revert HEAD~2 myfile

reverts HEAD~2 AND myFile

I take myFile is a file that you want to revert? In that case use

git checkout HEAD~2 -- myFile

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

MySQL error: key specification without a key length

Another excellent way of dealing with this is to create your TEXT field without the unique constraint and add a sibling VARCHAR field that is unique and contains a digest (MD5, SHA1, etc.) of the TEXT field. Calculate and store the digest over the entire TEXT field when you insert or update the TEXT field then you have a uniqueness constraint over the entire TEXT field (rather than some leading portion) that can be searched quickly.

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

It happens when referring an interface as well.

Changing interface for class fixed it, working with and without @Inject.

How do you sort an array on multiple columns?

String Appending Method

You can sort by multiple values simply by appending the values into a string and comparing the strings. It is helpful to add a split key character to prevent runoff from one key to the next.

Example

_x000D_
_x000D_
const arr = [ 
    { a: 1, b: 'a', c: 3 },
    { a: 2, b: 'a', c: 5 },
    { a: 1, b: 'b', c: 4 },
    { a: 2, b: 'a', c: 4 }
]


function sortBy (arr, keys, splitKeyChar='~') {
    return arr.sort((i1,i2) => {
        const sortStr1 = keys.reduce((str, key) => str + splitKeyChar+i1[key], '')
        const sortStr2 = keys.reduce((str, key) => str + splitKeyChar+i2[key], '')
        return sortStr1.localeCompare(sortStr2)
    })
}

console.log(sortBy(arr, ['a', 'b', 'c']))
_x000D_
_x000D_
_x000D_

Recursion Method

You can also use Recursion to do this. It is a bit more complex than the String Appending Method but it allows you to do ASC and DESC on the key level. I'm commenting on each section as it is a bit more complex.

There are a few commented out tests to show and verify the sorting works with a mixture of order and default order.

Example

const arr = [ 
    { a: 1, b: 'a', c: 3 },
    { a: 2, b: 'a', c: 5 },
    { a: 1, b: 'b', c: 4 },
    { a: 2, b: 'a', c: 4 }
]


function sortBy (arr, keys) {
    return arr.sort(function sort (i1,i2, sKeys=keys) {
        // Get order and key based on structure
        const compareKey = (sKeys[0].key) ? sKeys[0].key : sKeys[0];
        const order = sKeys[0].order || 'ASC'; // ASC || DESC
        // Calculate compare value and modify based on order
        let compareValue = i1[compareKey].toString().localeCompare(i2[compareKey].toString())
        compareValue = (order.toUpperCase() === 'DESC') ? compareValue * -1 : compareValue
        // See if the next key needs to be considered 
        const checkNextKey = compareValue === 0 && sKeys.length !== 1
        // Return compare value
        return (checkNextKey) ? sort(i1, i2, sKeys.slice(1)): compareValue;
    })
}

// console.log(sortBy(arr, ['a', 'b', 'c']))
console.log(sortBy(arr, [{key:'a',order:'desc'}, 'b', 'c']))
// console.log(sortBy(arr, ['a', 'b', {key:'c',order:'desc'}]))
// console.log(sortBy(arr, ['a', {key:'b',order:'desc'}, 'c']))
// console.log(sortBy(arr, [{key:'a',order:'asc'}, {key:'b',order:'desc'}, {key:'c',order:'desc'}]))

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

For Jest 24.9+ we just need to add --testTimeout in the command line

--testTimeout= 10000 // timeout of 10s

The default timeout value is 5000. This will be applicable for all test cases.

or if you want to give timeout to particular function only then you can use this syntax while declaring the test case.

test(name, fn, timeout)

example

test('example', async () => {
  

}, 10000); // timeout of 10s (default is 5000)

Save text file UTF-8 encoded with VBA

Here is another way to do this - using the API function WideCharToMultiByte:

Option Explicit

Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
  ByVal CodePage As Long, _
  ByVal dwFlags As Long, _
  ByVal lpWideCharStr As Long, _
  ByVal cchWideChar As Long, _
  ByVal lpMultiByteStr As Long, _
  ByVal cbMultiByte As Long, _
  ByVal lpDefaultChar As Long, _
  ByVal lpUsedDefaultChar As Long) As Long

Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
  Erase b
  len_s = Len(s)
  If len_s = 0 Then _
    Err.Raise 30030, , "Len(WideChars) = 0"
  ptr_s = StrPtr(s)
  size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
  If size = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte() = 0"
  ReDim b(0 To size - 1)
  If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub

Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
  s = "äöüßµ@€|~{}[]²³\ .." & _
    " OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
    ", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
  file = FreeFile
  Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
  getUtf8 s, b
  Put #file, , b
  Close #file
End Sub

How to get index of object by its property in JavaScript?

Since the sort part is already answered. I'm just going to propose another elegant way to get the indexOf of a property in your array

Your example is:

var Data = [
    {id_list:1, name:'Nick',token:'312312'},
    {id_list:2,name:'John',token:'123123'}
]

You can do:

var index = Data.map(function(e) { return e.name; }).indexOf('Nick');

Array.prototype.map is not available on IE7 or IE8. ES5 Compatibility

And here it is with ES6 and arrow syntax, which is even simpler:

const index = Data.map(e => e.name).indexOf('Nick');

Scheduled run of stored procedure on SQL server

I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:

  1. We have some console programs that need to run every night as well. This way all scheduled tasks can be in one place. Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
  2. The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes. It makes logging from withing the sql jobs much simpler.
  3. If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over. Just re-point the application once.

It's a real short VB.Net app: I can post code if any one is interested.

Escape a string for a sed replace pattern

An easier way to do this is simply building the string before hand and using it as a parameter for sed

rpstring="s/KEYWORD/$REPLACE/g"
sed -i $rpstring  test.txt

Set Response Status Code

I don't think you're setting the header correctly, try this:

header('HTTP/1.0 401 Unauthorized');

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

As the other answers said, it's because of the new System Integrity Protection, but I believe the other answers are overcomplicated.

If you're only gonna use that package in the current user, you should be able to install it just fine, without the need to disable the SIP, by using the --user flag. Like this:

sudo pip install --user packagename

Is there a C++ gdb GUI for Linux?

Check out the Eclipse CDT project. It is a plugin for Eclipse geared towards C/C++ development and includes a fairly feature rich debugging perspective (that behind the scenes uses GDB). It is available on a wide variety of platforms.

How can I create a marquee effect?

The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.

Also, the accepted answers demo fiddle has a lot of unnecessary styles.

So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.

http://jsfiddle.net/e8ws12pt/

_x000D_
_x000D_
.marquee {_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    padding: 0;_x000D_
    height: 16px;_x000D_
    display: block;_x000D_
}_x000D_
.marquee span {_x000D_
    display: inline-block;_x000D_
    text-indent: 0;_x000D_
    overflow: hidden;_x000D_
    -webkit-transition: 15s;_x000D_
    transition: 15s;_x000D_
    -webkit-animation: marquee 15s linear infinite;_x000D_
    animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
    100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
_x000D_
_x000D_

ant warning: "'includeantruntime' was not set"

Ant Runtime

Simply set includeantruntime="false":

<javac includeantruntime="false" ...>...</javac>

If you have to use the javac-task multiple times you might want to consider using PreSetDef to define your own javac-task that always sets includeantruntime="false".

Additional Details

From http://www.coderanch.com/t/503097/tools/warning-includeantruntime-was-not-set:

That's caused by a misfeature introduced in Ant 1.8. Just add an attribute of that name to the javac task, set it to false, and forget it ever happened.

From http://ant.apache.org/manual/Tasks/javac.html:

Whether to include the Ant run-time libraries in the classpath; defaults to yes, unless build.sysclasspath is set. It is usually best to set this to false so the script's behavior is not sensitive to the environment in which it is run.

Using sed and grep/egrep to search and replace

I couldn't get any of the commands on this page to work for me: the sed solution added a newline to the end of all the files it processed, and the perl solution was unable to accept enough arguments from find. I found this solution which works perfectly:

find . -type f -name '*.[hm]' -print0 
    | xargs -0 perl -pi -e 's/search_regex/replacement_string/g'

This will recurse down the current directory tree and replace search_regex with replacement_string in any files ending in .h or .m.

I have also used rpl for this purpose in the past.

How can I upgrade NumPy?

This works for me:

pip install numpy --upgrade

PHP checkbox set to check based on database value

Use checked="checked" attribute if you want your checkbox to be checked.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

Run the following command to fix this problem.

Start --> Run:

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe –i

If you get an error about ADMIN rights you need to do the following.

1. CTRL+SHIFT+ENTER from the RUN menu will run as ADMIN
2. START --> PROGRAMS --> ACCESSORIES --> Right-click on command prompt and "run as administrator"

Design Patterns web based applications

IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

You could use a new annotation to solve this:

@XXXToXXX(targetEntity = XXXX.class, fetch = FetchType.LAZY)

In fact, fetch's default value is FetchType.LAZY too.

How do you get AngularJS to bind to the title attribute of an A tag?

It looks like ng-attr is a new directive in AngularJS 1.1.4 that you can possibly use in this case.

<!-- example -->
<a ng-attr-title="{{product.shortDesc}}"></a>

However, if you stay with 1.0.7, you can probably write a custom directive to mirror the effect.

Bash if statement with multiple conditions throws an error

Use -a (for and) and -o (for or) operations.

tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Update

Actually you could still use && and || with the -eq operation. So your script would be like this:

my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ] || ([ $my_error_flag -eq 1 ] && [ $my_error_flag_o -eq 2 ]); then
      echo "$my_error_flag"
else
    echo "no flag"
fi

Although in your case you can discard the last two expressions and just stick with one or operation like this:

my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ]; then
      echo "$my_error_flag"
else
    echo "no flag"
fi

Is there an easy way to check the .NET Framework version?

This class allows your application to throw out a graceful notification message rather than crash and burn if it couldn't find the proper .NET version. All you need to do is this in your main code:

[STAThread]
static void Main(string[] args)
{
    if (!DotNetUtils.IsCompatible())
        return;
   . . .
}

By default it takes 4.5.2, but you can tweak it to your liking, the class (feel free to replace MessageBox with Console):

Updated for 4.8:

public class DotNetUtils
{
    public enum DotNetRelease
    {
        NOTFOUND,
        NET45,
        NET451,
        NET452,
        NET46,
        NET461,
        NET462,
        NET47,
        NET471,
        NET472,
        NET48,
    }

    public static bool IsCompatible(DotNetRelease req = DotNetRelease.NET452)
    {
        DotNetRelease r = GetRelease();
        if (r < req)
        {
            MessageBox.Show(String.Format("This this application requires {0} or greater.", req.ToString()));
            return false;
        }
        return true;
    }

    public static DotNetRelease GetRelease(int release = default(int))
    {
        int r = release != default(int) ? release : GetVersion();
        if (r >= 528040) return DotNetRelease.NET48;
        if (r >= 461808) return DotNetRelease.NET472;
        if (r >= 461308) return DotNetRelease.NET471;
        if (r >= 460798) return DotNetRelease.NET47;
        if (r >= 394802) return DotNetRelease.NET462;
        if (r >= 394254) return DotNetRelease.NET461;
        if (r >= 393295) return DotNetRelease.NET46;
        if (r >= 379893) return DotNetRelease.NET452;
        if (r >= 378675) return DotNetRelease.NET451;
        if (r >= 378389) return DotNetRelease.NET45;
        return DotNetRelease.NOTFOUND;
    }

    public static int GetVersion()
    {
        int release = 0;
        using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)
                                            .OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
        {
            release = Convert.ToInt32(key.GetValue("Release"));
        }
        return release;
    }
}

Easily extendable when they add a new version later on. I didn't bother with anything before 4.5 but you get the idea.

Postman: sending nested JSON object

To post a nested object with the key-value interface you can use a similar method to sending arrays. Pass an object key in square brackets after the object index.

Passing a nested item with Postman

"Items": [
      {
        "sku": "9257",
        "Price": "100"
      }
 ]

How to printf long long

  • Your scanf() statement needs to use %lld too.
  • Your loop does not have a terminating condition.
  • There are far too many parentheses and far too few spaces in the expression

    pi += pow(-1.0, e) / (2.0*e + 1.0);
    
  • You add one on the first iteration of the loop, and thereafter zero to the value of 'pi'; this does not change the value much.
  • You should use an explicit return type of int for main().
  • On the whole, it is best to specify int main(void) when it ignores its arguments, though that is less of a categorical statement than the rest.
  • I dislike the explicit licence granted in C99 to omit the return from the end of main() and don't use it myself; I write return 0; to be explicit.

I think the whole algorithm is dubious when written using long long; the data type probably should be more like long double (with %Lf for the scanf() format, and maybe %19.16Lf for the printf() formats.

Black transparent overlay on image hover with only CSS?

Here's a good way using :after on the image div, instead of the extra overlay div: http://jsfiddle.net/Zf5am/576/

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>

.image {position:relative; border:1px solid black; width:200px; height:200px;}
.image img {max-width:100%; max-height:100%;}
.image:hover:after {content:""; position:absolute; top:0; left:0; bottom:0; right:0; background-color: rgba(0,0,0,0.3);}

Remove trailing newline from the elements of a string list

>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']

How do I convert a float to an int in Objective C?

int myInt = (int) myFloat;

Worked fine for me.

int myInt = [[NSNumber numberWithFloat:myFloat] intValue];

Well, that is one option. If you like the detour, I could think of some using NSString. Why easy, when there is a complicated alternative? :)

Remove unused imports in Android Studio

You can do it on the fly. You don't need to call (Ctrl+Shift+O) or "Project/Optimize Imports..." each time.

Just set this checkbox in Settings -> Editor -> General -> Auto Import -> Optimize Imports on the fly.

enter image description here

On OSX: Preferences -> Editor -> General -> Auto Import -> Optimize imports on the fly

How to find Control in TemplateField of GridView?

Try this:

foreach(GridViewRow row in GridView1.Rows) {
    if(row.RowType == DataControlRowType.DataRow) {
        HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
    }
}

If you are handling RowDataBound event, it's like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
    }
}

Angular 4 checkbox change value

try this worked for me :

checkValue(event: any) {
    this.siteSelected.majeur = event;
}

How can I copy columns from one sheet to another with VBA in Excel?

If you have merged cells,

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

that doesn't copy cells as they are, where previous code does copy exactly as they look like (merged).

Check if string ends with certain pattern

This is really simple, the String object has an endsWith method.

From your question it seems like you want either /, , or . as the delimiter set.

So:

String str = "This.is.a.great.place.to.work.";

if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
     // ... 

You can also do this with the matches method and a fairly simple regex:

if (str.matches(".*([.,/])work\\1$"))

Using the character class [.,/] specifying either a period, a slash, or a comma, and a backreference, \1 that matches whichever of the alternates were found, if any.

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

From commons-lang3

org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)

Restricting input to textbox: allowing only numbers and decimal point

Suppose your textbox field name is Income
Call this validate method when you need to validate your field:

function validate() {
    var currency = document.getElementById("Income").value;
      var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
    if (pattern.test(currency)) {
        alert("Currency is in valid format");
        return true;
    } 
        alert("Currency is not in valid format!Enter in 00.00 format");
        return false;
}

onclick="location.href='link.html'" does not load page in Safari

You can try this:

 <a href="link.html">
       <input type="button" value="Visit Page" />
    </a>

This will create button inside a link and it works on any browser

Android Imagebutton change Image OnClick

To switch between different images when the ImageButton is clicked I used a boolean like this:

ImageButton imageButton;
boolean buttonOn;

imageButton.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         if (!buttonOn) {
             buttonOn = true;
             imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_on)); 
         } else {
             buttonOn = false;
             imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_off));
         }
     }
});

Capture the Screen into a Bitmap

Bitmap memoryImage;
//Set full width, height for image
memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                       Screen.PrimaryScreen.Bounds.Height,
                       PixelFormat.Format32bppArgb);
Size s = new Size(memoryImage.Width, memoryImage.Height);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
string str = "";
try
{
    str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
          @"\Screenshot.png");//Set folder to save image
}
catch { };
memoryImage.save(str);

Bootstrap: Open Another Modal in Modal

Twitter docs says custom code is required...

This works with no extra JavaScript, though, custom CSS would be highly recommended...

_x000D_
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<!-- Button trigger modal -->_x000D_
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#modalOneModal">_x000D_
      Launch demo modal_x000D_
    </button> _x000D_
            <!-- Modal -->_x000D_
            <div class="modal fade bg-info" id="modalOneModal" tabindex="-1" role="dialog" aria-labelledby="modalOneLabel" aria-hidden="true">_x000D_
    _x000D_
              <div class="modal-dialog">_x000D_
          _x000D_
                <div class="modal-content  bg-info">_x000D_
                  <div class="modal-header btn-info">_x000D_
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>_x000D_
                    <h4 class="modal-title" id="modalOneLabel">modalOne</h4>_x000D_
                  </div>_x000D_
                  <div id="thismodalOne" class="modal-body bg-info">_x000D_
                _x000D_
                _x000D_
              <!-- Button trigger modal -->_x000D_
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#twoModalsExample">_x000D_
      Launch demo modal_x000D_
    </button>_x000D_
             _x000D_
                    <div class="modal fade bg-info" id="twoModalsExample" style="overflow:auto" tabindex="-1" role="dialog" aria-hidden="true">_x000D_
                <h3>EXAMPLE</h3>_x000D_
            </div>_x000D_
                  </div>_x000D_
                  <div class="modal-footer btn-info" id="woModalFoot">_x000D_
                    <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>_x000D_
                  </div>_x000D_
                </div>_x000D_
              </div>_x000D_
            </div>_x000D_
    <!-- End Form Modals -->
_x000D_
_x000D_
_x000D_

How to check not in array element

$id = $access_data['Privilege']['id']; 

if(!in_array($id,$user_access_arr));
    $user_access_arr[] = $id;
    $this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
    return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));

Conversion of a datetime2 data type to a datetime data type results out-of-range value

for me it was because the datetime was..

01/01/0001 00:00:00

in this case you want to assign null to you EF DateTime Object... using my FirstYearRegistered code as an example

DateTime FirstYearRegistered = Convert.ToDateTime(Collection["FirstYearRegistered"]);
if (FirstYearRegistered != DateTime.MinValue)
{
    vehicleData.DateFirstReg = FirstYearRegistered;
}  

jQuery UI DatePicker to show year only

  $(function() {
    $('#datepicker1').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    });
});?

Style should be

.ui-datepicker-calendar {
    display: none;
    }?

working demo

Switch between two frames in tkinter

Here is another simple answer, but without using classes.

from tkinter import *


def raise_frame(frame):
    frame.tkraise()

root = Tk()

f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)

for frame in (f1, f2, f3, f4):
    frame.grid(row=0, column=0, sticky='news')

Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()

Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()

Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')

Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()

raise_frame(f1)
root.mainloop()

Copying sets Java

Starting from Java 10:

Set<E> oldSet = Set.of();
Set<E> newSet = Set.copyOf(oldSet);

Set.copyOf() returns an unmodifiable Set containing the elements of the given Collection.

The given Collection must not be null, and it must not contain any null elements.

How to close a web page on a button click, a hyperlink or a link button click?

double click the button and add write // this.close();

  private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}

How to use phpexcel to read data and insert into database?

Inci framework you can do download like so:

function clubDownload($clubname)
{

    $this->load->library("excel");

    $object = new PHPExcel();
    $object->setActiveSheetIndex(0);
    $this->load->model('Members_student_model');
    $query = $this->db->query("SELECT * FROM student WHERE $clubname!=''  order by id desc");
    $resultdatanew=$query->result_array();
    $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;

    $object->getActiveSheet()->getStyle("A1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("B1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');


    $object->getActiveSheet()->getStyle("C1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("D1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');


    $object->getActiveSheet()->getStyle("E1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("F1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');
    $object->getActiveSheet()->getStyle("G1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("H1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');
    $object->getActiveSheet()->getStyle("I1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');
    $headerStyle = array(
                'fill' => array(
                        'type' => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb'=>'CCE5FF'),
                ),
                'font' => array(
                        'bold' => true,
                )
        );

    $object->getActiveSheet()->getStyle('A1:'.'I1')->applyFromArray($headerStyle);
    $table_columns = array("id", "studentid", "passport", "lastname", "firstname","university","commencing",$clubname,"added_date");
    $column = 0;
    foreach($table_columns as $field)
    {
    $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
    $column++;
    }
    $excel_row = 2;




    foreach($resultdatanew as $row)
    {


                $id=$row['id'];
                $studentid=$row['studentid'];
                $passport=$row['passport'];
                $lastname=$row['last_name'];
                $firstname=$row['first_name'];
                $passport=$row['university'];
                $commencing=$row['commencing'];
                $email_id=$row['email_id'];
                $added_date=$row['added_date'];


                $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$id);

                $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $studentid);
                $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $passport);
                $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $lastname);
                $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $firstname);
                $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $passport);
                $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row,  $commencing);
                $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $email_id);
                $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $added_date);


                $excel_row++;
}

$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="club' .$clubname.'-'.date('Y-m-d') . '.xls');
$object_writer->save('php://output');

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

Navigation Drawer (Google+ vs. YouTube)

Personally I like the navigationDrawer in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.

If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock and works for pre Honeycomb devices. Check it:

SherlockNavigationDrawer github

Solving "adb server version doesn't match this client" error

I fixed this by doing the following:

  1. going into GenyMotion settings -> ADB tab,
  2. instead of Use Genymotion Android tools (default), I chose Use custom Android SDK Tools and then browsed to my installed SDK.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

There is a single BEXTR (Bit field extract (with register)) x86 instruction on Intel and AMD CPUs and UBFX on ARM. There are intrinsic functions such as _bextr_u32() (link requires sign-in) that allow to invoke this instruction explicitly.

They implement (source >> offset) & ((1 << n) - 1) C code: get n continuous bits from source starting at the offset bit. Here's a complete function definition that handles edge cases:

#include <limits.h>

unsigned getbits(unsigned value, unsigned offset, unsigned n)
{
  const unsigned max_n = CHAR_BIT * sizeof(unsigned);
  if (offset >= max_n)
    return 0; /* value is padded with infinite zeros on the left */
  value >>= offset; /* drop offset bits */
  if (n >= max_n)
    return value; /* all  bits requested */
  const unsigned mask = (1u << n) - 1; /* n '1's */
  return value & mask;
}

For example, to get 3 bits from 2273 (0b100011100001) starting at 5-th bit, call getbits(2273, 5, 3)—it extracts 7 (0b111).

For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?

unsigned first_bits = value & ((1u << 17) - 1); // & 0x1ffff

Assuming CHAR_BIT * sizeof(unsigned) is 32 on your system.

I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits

unsigned last8bitsvalue  = value & ((1u <<  8) - 1); // & 0xff
unsigned last16bitsvalue = value & ((1u << 16) - 1); // & 0xffff

If the offset is always zero as in all your examples in the question then you don't need the more general getbits(). There is a special cpu instruction BLSMSK that helps to compute the mask ((1 << n) - 1).

Simple PowerShell LastWriteTime compare

I can't fault any of the answers here for the OP accepted one of them as resolving their problem. However, I found them flawed in one respect. When you output the result of the assignment to the variable, it contains numerous blank lines, not just the sought after answer. Example:

PS C:\brh> [datetime](Get-ItemProperty -Path .\deploy.ps1 -Name LastWriteTime).LastWriteTime

Friday, December 12, 2014 2:33:09 PM



PS C:\brh> 

I'm a fan of two things in code, succinctness and correctness. brianary has the right of it for succinctness with a tip of the hat to Roger Lipscombe but both miss correctness due to the extra lines in the result. Here's what I think the OP was looking for since it's what got me over the finish line.

PS C:\brh> (ls .\deploy.ps1).LastWriteTime.DateTime
Friday, December 12, 2014 2:33:09 PM

PS C:\brh> 

Note the lack of extra lines, only the one that PowerShell uses to separate prompts. Now this can be assigned to a variable for comparison or, as in my case, stored in a file for reading and comparison in a later session.

Style the first <td> column of a table differently

The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.

The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.

For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

td:nth-child(3n+1) {  
  /* your stuff here */
}

:nth-of-type() works the same, except that it only considers element of the given type ( in the example).

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can also enable multiple GPU cores, like so:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"

Does Eclipse have line-wrap

Ctrl+Shift+F will format a file in Eclipse, breaking long lines into multiple lines and nicely word-wrapping comments. You can also highlight just a section of text and format that.

I realize this is not an automatic soft/hard word wrap like the other answers, but I don't think the question was asking for anything fancy.

Joda DateTime to Timestamp conversion

I've solved this problem in this way.

String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);

In this way you ignore the server TimeZone forcing your chosen TimeZone.

What are the differences between ArrayList and Vector?

Basically both ArrayList and Vector both uses internal Object Array.

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements. ArrayList uses internal Object Array; they are created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15.

Vector: Vector is similar to ArrayList but the differences are, it is synchronized and its default initial size is 10 and when the size exceeds its size increases to double of the original size that means the new size will be 20. Vector is the only class other than ArrayList to implement RandomAccess. Vector is having four constructors out of that one takes two parameters Vector(int initialCapacity, int capacityIncrement) capacityIncrement is the amount by which the capacity is increased when the vector overflows, so it have more control over the load factor.

Some other differences are: enter image description here

What is the use of ObservableCollection in .net?

it is a collection which is used to notify mostly UI to change in the collection , it supports automatic notification.

Mainly used in WPF ,

Where say suppose you have UI with a list box and add button and when you click on he button an object of type suppose person will be added to the obseravablecollection and you bind this collection to the ItemSource of Listbox , so as soon as you added a new item in the collection , Listbox will update itself and add one more item in it.

Align printf output in Java

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.

Installation of SQL Server Business Intelligence Development Studio

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

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

How to get current route in react-router 2.0.0-rc5

If you use the history,then Router put everything into the location from the history,such as:

this.props.location.pathname;
this.props.location.query;

get it?

Could not obtain information about Windows NT group user

Just solved this problem. In my case it was domain controller is not accessible, because both dns servers was google dns.

I just add to checklist for this problem:

  • check domain controller is accessible

Maven2 property that indicates the parent directory

Try setting a property in each pom to find the main project directory.

In the parent:

<properties>
    <main.basedir>${project.basedir}</main.basedir>
</properties>

In the children:

<properties>
    <main.basedir>${project.parent.basedir}</main.basedir>
</properties>

In the grandchildren:

<properties>
    <main.basedir>${project.parent.parent.basedir}</main.basedir>
</properties>

PHP/MySQL insert row then get 'id'

Try this... it worked for me!

$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
    if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    $msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    $msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

Raise warning in Python without interrupting program

You shouldn't raise the warning, you should be using warnings module. By raising it you're generating error, rather than warning.

Integer value comparison

Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.

Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }

How to change the default collation of a table?

It sets the default collation for the table; if you create a new column, that should be collated with latin_general_ci -- I think. Try specifying the collation for the individual column and see if that works. MySQL has some really bizarre behavior in regards to the way it handles this.

How to change working directory in Jupyter Notebook?

  1. list all magic command %lsmagic
  2. show current directory %pwd

How to import Angular Material in project?

You should consider using a SharedModule for the essential material components of your app, and then import every single module you need to use into your feature modules. I wrote an article on medium explaining how to import Angular material, check it out:

https://medium.com/@benmohamehdi/how-to-import-angular-material-angular-best-practices-80d3023118de

If/else else if in Jquery for a condition

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <form name="myform">
    Enter your name
    <input type="text" name="inputbox" id='textBox' value="" />
    <input type="button" name="button" class="member" value="Click1" />
    <input type="button" name="button" value="Click2" onClick="testResults()" />
  </form>
  <script>
    function testResults(n) {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    }
    $(document).on('click', '.member', function () {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    });
  </script>

Bootstrap Modal immediately disappearing

while working with Angular(5) , i face the same issue , but in my case i solved as follows:

component.html

<button type="button" class="btn btn-primary"  data-target="#myModal" 
(click)="showresult()">fff</button>

<div class="modal" id="myModal" role="dialog"  tabindex="-1" data-backdrop="false">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <p>Modal body text goes here.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary">Save changes</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

component.ts

NOTE: need to import jquery in ts file as "declare var $ :any;"

  showresult(){
    debugger
    $('#myModal').modal('show');
  }

Changes i made :

  • removed "data-toggle="modal" from Button tag (thanks to @miCRoSCoPiC_eaRthLinG this answer helps me here) in my case its showing modal so i created (click)="showresult()"

  • inside component.ts need to declare Jquery($) and inside button click method showresult() call " $('#myModal').modal('show');"

android - listview get item view by position

Use this :

public View getViewByPosition(int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

Iterate through dictionary values?

You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items(). Then you have both directly in variables and don't need a lookup at all:

for key, value in PIX0.items():
    NUM = input("What is the Resolution of %s?"  % key)
    if NUM == value:

You can of course use that both ways then.

Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.

Upgrade python without breaking yum

Daniel's answer is probably the most ideal one as it doesn't involve changing OS files. However, I found myself in a situation where I needed a 3rd party program which invoked python by calling usr/bin/python, but required Python 2.7.16, while the default Python was 2.7.5. That meant I had to make usr/bin/python point to a Python version of 2.7.16 version, which meant that yum wouldn't work.

What I ended up doing is editing the file /usr/bin/yum and replacing the shebang there to use to the system default Python (in my case, that meant changing #! /usr/bin/python to #! /usr/bin/python2). However, after that running yum gave me an error:

ImportError: No module named urlgrabber.grabber

I solved that by replacing the shebang in /usr/libexec/urlgrabber-ext-down the same way as in /usr/bin/yum. I.e., #! /usr/bin/python to #! /usr/bin/python2. After that yum worked.

This is a hack and should be used with care. As mentioned in other comments, modifying OS files should be last resort only.

Using --add-host or extra_hosts with docker-compose

Basic docker-compose.yml with extra hosts:

version: '3'
services:
api:
    build: .
    ports:
        - "5003:5003"
    extra_hosts:
        - "your-host.name.com:162.242.195.82" #host and ip
        - "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
        

The content in the /etc/hosts file in the created container:

162.242.195.82  your-host.name.com
50.31.209.229   your-host--1.name.com your-host--2.name.com

You can check the /etc/hosts file with the following commands:

$ docker-compose -f path/to/file/docker-compose.yml run api bash  # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts

How to get the current branch name in Git?

You have also git symbolic-ref HEAD which displays the full refspec.

To show only the branch name in Git v1.8 and later (thank's to Greg for pointing that out):

git symbolic-ref --short HEAD

On Git v1.7+ you can also do:

git rev-parse --abbrev-ref HEAD

Both should give the same branch name if you're on a branch. If you're on a detached head answers differ.

Note:

On an earlier client, this seems to work:

git symbolic-ref HEAD | sed -e "s/^refs\/heads\///"

Darien 26. Mar 2014

strcpy() error in Visual studio 2012

Add this line top of the header

#pragma warning(disable : 4996)

Copy Image from Remote Server Over HTTP

Since you've tagged your question 'php', I'll assume your running php on your server. Your best bet is if you control your own web server, then compile cURL into php. This will allow your web server to make requests to other web servers. This can be quite dangerous from a security point of view, so most basic web hosting providers won't have this option enabled.

Here's the php man page on using cURL. In the comments you can find an example which downloads and image file.

If you don't want to use libcurl, you could code something up using fsockopen. This is built into php (but may be disabled on your host), and can directly read and write to sockets. See Examples on the fsockopen man page.

How to remove a web site from google analytics

What the OP wants to do, is delete additional properties in his Google analytics. Properties that are not his but belong to someone else.

Apparently, the only way to do this, is to contact the owner of that website who is the administrator, and asked them to remove you.

Or you can just create a new Google account, and add your properties to the new account.

None of these are real good solutions. Thank you Google for caring so much about SEO people.

To add insult to injury, if you go over 25 accounts, you must contact Google to get permission to add another.

Lesson learned: Do not add other peoples websites to your Google analytics account. Create a separate account so that if you have to start over, you don't lose any data from your websites. It's also good to have more than one Google analytics account.

generating variable names on fly in python

I got your problem , and here is my answer:

prices = [5, 12, 45]
list=['1','2','3']

for i in range(1,3):
  vars()["prices"+list[0]]=prices[0]
print ("prices[i]=" +prices[i])

so while printing:

price1 = 5 
price2 = 12
price3 = 45

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

Preventing SQL injection in Node.js

The node-mysql library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values

How do I copy items from list to list without foreach?

For a list of elements

List<string> lstTest = new List<string>();

lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");

If you want to copy all the elements

List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);

If you want to copy the first 3 elements

List<string> lstNew = lstTest.GetRange(0, 3);

How do I print colored output with Python 3?

Since Python is interpreted and run in C, it is possible to set colors without a module.

You can define a class for colors like this:

class color:
   PURPLE = '\033[1;35;48m'
   CYAN = '\033[1;36;48m'
   BOLD = '\033[1;37;48m'
   BLUE = '\033[1;34;48m'
   GREEN = '\033[1;32;48m'
   YELLOW = '\033[1;33;48m'
   RED = '\033[1;31;48m'
   BLACK = '\033[1;30;48m'
   UNDERLINE = '\033[4;37;48m'
   END = '\033[1;37;0m'

When writing code, you can simply write:

print(color.BLUE + "hello friends" + color.END)

Note that the color you choose will have to be capitalized like your class definition, and that these are color choices that I personally find satisfying. For a fuller array of color choices and, indeed, background choices as well, please see: https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a.

This is code for C, but can easily be adapted to Python once you realize how the code is written.

Take BLUE for example, since that is what you are wanting to display.

BLUE = '033[1;37;48m'

\033 tells Python to break and pay attention to the following formatting.

1 informs the code to be bold. (I prefer 1 to 0 because it pops more.)

34 is the actual color code. It chooses blue.

48m is the background color. 48m is the same shade as the console window, so it seems there is no background.

How to declare a global variable in JavaScript

Declare the variable outside of functions

function dosomething(){
  var i = 0; // Can only be used inside function
}

var i = '';
function dosomething(){
  i = 0; // Can be used inside and outside the function
}

Nested JSON: How to add (push) new items to an object?

You can achieve this using Lodash _.assign function.

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

_x000D_
_x000D_
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
  "Gold Rush": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
  },_x000D_
  "California": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
  }_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
  // If title already exists, modify item_x000D_
  if (library[title]) {_x000D_
_x000D_
    // override one Object with the values of another (lodash)_x000D_
    library[title] = _.assign({}, {_x000D_
      'foregrounds': foregrounds_x000D_
    }, {_x000D_
      'backgrounds': backgrounds_x000D_
    });_x000D_
    console.log(library[title]);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    // console.log('Changes Saved to <b>' + title + '</b>');_x000D_
  }_x000D_
_x000D_
  // If title does not exist, add new item_x000D_
  else {_x000D_
    // Format it for the JSON object_x000D_
    var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
    // THE PROBLEM SEEMS TO BE HERE??_x000D_
    // Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
    library.push(item);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    console.log('Added: <b>' + title + '</b>');_x000D_
  }_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

MongoDB distinct aggregation

SQL Query: (group by & count of distinct)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

nodemon not found in npm

My nodemon vanished after installing babel (why?).

Tried a lot of stuff. Here is how I solved it:

sudo npm i -g nodemon

Just reinstall it with sudo. Yeah.

Java - get pixel array from image

Mota's answer is great unless your BufferedImage came from a Monochrome Bitmap. A Monochrome Bitmap has only 2 possible values for its pixels (for example 0 = black and 1 = white). When a Monochrome Bitmap is used then the

final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

call returns the raw Pixel Array data in such a fashion that each byte contains more than one pixel.

So when you use a Monochrome Bitmap image to create your BufferedImage object then this is the algorithm you want to use:

/**
 * This returns a true bitmap where each element in the grid is either a 0
 * or a 1. A 1 means the pixel is white and a 0 means the pixel is black.
 * 
 * If the incoming image doesn't have any pixels in it then this method
 * returns null;
 * 
 * @param image
 * @return
 */
public static int[][] convertToArray(BufferedImage image)
{

    if (image == null || image.getWidth() == 0 || image.getHeight() == 0)
        return null;

    // This returns bytes of data starting from the top left of the bitmap
    // image and goes down.
    // Top to bottom. Left to right.
    final byte[] pixels = ((DataBufferByte) image.getRaster()
            .getDataBuffer()).getData();

    final int width = image.getWidth();
    final int height = image.getHeight();

    int[][] result = new int[height][width];

    boolean done = false;
    boolean alreadyWentToNextByte = false;
    int byteIndex = 0;
    int row = 0;
    int col = 0;
    int numBits = 0;
    byte currentByte = pixels[byteIndex];
    while (!done)
    {
        alreadyWentToNextByte = false;

        result[row][col] = (currentByte & 0x80) >> 7;
        currentByte = (byte) (((int) currentByte) << 1);
        numBits++;

        if ((row == height - 1) && (col == width - 1))
        {
            done = true;
        }
        else
        {
            col++;

            if (numBits == 8)
            {
                currentByte = pixels[++byteIndex];
                numBits = 0;
                alreadyWentToNextByte = true;
            }

            if (col == width)
            {
                row++;
                col = 0;

                if (!alreadyWentToNextByte)
                {
                    currentByte = pixels[++byteIndex];
                    numBits = 0;
                }
            }
        }
    }

    return result;
}

Automatically size JPanel inside JFrame

From my experience, I used GridLayout.

    thePanel.setLayout(new GridLayout(a,b,c,d));

a = row number, b = column number, c = horizontal gap, d = vertical gap.


For example, if I want to create panel with:

  • unlimited row (set a = 0)
  • 1 column (set b = 1)
  • vertical gap= 3 (set d = 3)

The code is below:

    thePanel.setLayout(new GridLayout(0,1,0,3));

This method is useful when you want to add JScrollPane to your JPanel. Size of the JPanel inside JScrollPane will automatically changes when you add some components on it, so the JScrollPane will automatically reset the scroll bar.

How to set column widths to a jQuery datatable?

I found this on 456 Bera St. Man is it a lifesaver!!!

http://www.456bereastreet.com/archive/200704/how_to_prevent_html_tables_from_becoming_too_wide/

But - you don't have a lot of room to spare with your data.

CSS FTW:

<style>
table {
    table-layout:fixed;
}
td{
    overflow:hidden;
    text-overflow: ellipsis;
}
</style>

How to format an inline code in Confluence?

I use a combination of Zelphir and Peter Gluck's answers. i.e.

  1. (Mac-speak) Click COMMAND + SHIFT + D
  2. Select Markdown in the dropdown of the model pop-up
  3. Surround your text with the code tag - i.e. <code>bovvered</code>
  4. Click INSERT

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

OnRequestPermissionResult-free and shouldShowRequestPermissionRationale-free method:

public static void requestDangerousPermission(AppCompatActivity activity, String permission) {
        if (hasPermission(activity, permission)) return;
        requestPermission();

        new Handler().postDelayed(() -> {
            if (activity.getLifecycle().getCurrentState() == Lifecycle.State.RESUMED) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                context.startActivity(intent);
            }
        }, 250);
    }

Opens device settings after 250ms if no permission popup happened (which is the case if 'Never ask again' was selected.

Fixing broken UTF-8 encoding

I've had to try to 'fix' a number of UTF8 broken situations in the past, and unfortunately it's never easy, and often rather impossible.

Unless you can determine exactly how it was broken, and it was always broken in that exact same way, then it's going to be hard to 'undo' the damage.

If you want to try to undo the damage, your best bet would be to start writing some sample code, where you attempt numerous variations on calls to mb_convert_encoding() to see if you can find a combination of 'from' and 'to' that fixes your data. In the end, it's often best to not even bother worrying about fixing the old data because of the pain levels involved, but instead to just fix things going forward.

However, before doing this, you need to make sure that you fix everything that is causing this issue in the first place. You've already mentioned that your DB table collation and editors are set properly. But there are more places where you need to check to make sure that everything is properly UTF-8:

  • Make sure that you are serving your HTML as UTF-8:
    • header("Content-Type: text/html; charset=utf-8");
  • Change your PHP default charset to utf-8:
    • ini_set("default_charset", 'utf-8');
  • If your database doesn't ALWAYS talk in utf-8, then you may need to tell it on a per connection basis to ensure it's in utf-8 mode, in MySQL you do that by issuing:
    • charset utf8
  • You may need to tell your webserver to always try to talk in UTF8, in Apache this command is:
    • AddDefaultCharset UTF-8
  • Finally, you need to ALWAYS make sure that you are using PHP functions that are properly UTF-8 complaint. This means always using the mb_* styled 'multibyte aware' string functions. It also means when calling functions such as htmlspecialchars(), that you include the appropriate 'utf-8' charset parameter at the end to make sure that it doesn't encode them incorrectly.

If you miss up on any one step through your whole process, the encoding can be mangled and problems arise. Once you get in the 'groove' of doing utf-8 though, this all becomes second nature. And of course, PHP6 is supposed to be fully unicode complaint from the getgo, which will make lots of this easier (hopefully)

CSS Display an Image Resized and Cropped

In the crop class, place the image size that you want to appear:

.crop {
    width: 282px;
    height: 282px;
    overflow: hidden;
}
.crop span.img {
    background-position: center;
    background-size: cover;
    height: 282px;
    display: block;
}

The html will look like:

<div class="crop">
    <span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

How to start Apache and MySQL automatically when Windows 8 comes up

You can do it via cmd.

For Apache

Open cmd in administrator mode. Change directory to C:/xampp/apache/bin. Run the command as httpd.exe -k install. Your Apache server service will be installed. You can start it from services.

For MySQL

Change directory to C:/xampp/mysql/bin. Run the command as mysqld --install. Your MySQL service will be installed. You can start it from services.

Note: Make sure the selected Apache and MySQL services are set to start automatically.

You're done. There isn't any need to launch the XAMPP control panel

Can I use git diff on untracked files?

Assuming you do not have local commits,

git diff origin/master

Pass a string parameter in an onclick function

It looks like you're building DOM elements from strings. You just need to add some quotes around result.name:

'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'

You should really be doing this with proper DOM methods though.

var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
    gotoNode(result.name);
});

?document.body.appendChild(inputElement);?

Just be aware that if this is a loop or something, result will change before the event fires and you'd need to create an additional scope bubble to shadow the changing variable.

How do I apply the for-each loop to every character in a String?

Another useful solution, you can work with this string as array of String

for (String s : "xyz".split("")) {
    System.out.println(s);
}

How to properly use unit-testing's assertRaises() with NoneType objects?

The usual way to use assertRaises is to call a function:

self.assertRaises(TypeError, test_function, args)

to test that the function call test_function(args) raises a TypeError.

The problem with self.testListNone[:1] is that Python evaluates the expression immediately, before the assertRaises method is called. The whole reason why test_function and args is passed as separate arguments to self.assertRaises is to allow assertRaises to call test_function(args) from within a try...except block, allowing assertRaises to catch the exception.

Since you've defined self.testListNone = None, and you need a function to call, you might use operator.itemgetter like this:

import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))

since

operator.itemgetter(self.testListNone,slice(None,1))

is a long-winded way of saying self.testListNone[:1], but which separates the function (operator.itemgetter) from the arguments.

How to initialize all members of an array to the same value?

int array[1024] = {[0 ... 1023] = 5}; As the above works fine but make sure no spaces between the ... dots

trim left characters in sql server?

use "LEFT"

 select left('Hello World', 5)

or use "SUBSTRING"

 select substring('Hello World', 1, 5)

I need a Nodejs scheduler that allows for tasks at different intervals

I've used node-cron and agenda.

node-cron is a very simple library, which provide very basic and easy to understand api like crontab. It doesn't need any config and just works.

var cronJob = require('cron').CronJob;
var myJob = new cronJob('00 30 11 * * 1-5', function(){...});
myJob.start();

agenda is very powerful and fit for much more complex services. Think about ifttt, you have to run millions of tasks. agenda would be the best choice.

Note: You need Mongodb to use Agenda

var Agenda = require("Agenda");
var agenda = new Agenda({db: { address: 'localhost:27017/agenda-example'}});
agenda.every('*/3 * * * *', 'delete old users');
agenda.start();

How to iterate through a String

Java Strings aren't character Iterable. You'll need:

for (int i = 0; i < examplestring.length(); i++) {
  char c = examplestring.charAt(i);
  ...
}

Awkward I know.

'Use of Unresolved Identifier' in Swift

Once I had this problem after renaming a file. I renamed the file from within Xcode, but afterwards Xcode couldn't find the function in the file. Even a clean rebuild didn't fix the problem, but closing and then re-opening the project got the build to work.

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

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

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

But the method takes a vector<Card>&:

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

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

Error:

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

Paraphrased:

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

Error:

[Note] candidate is:

In file included from main.cpp

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

Paraphrased:

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

Error:

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

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

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

Wrapping your list of objects with another object containing a property that matches the name of the parameter which is expected by the MVC controller works. The important bit being the wrapper around the object list.

$(document).ready(function () {
    var employeeList = [
        { id: 1, name: 'Bob' },
        { id: 2, name: 'John' },
        { id: 3, name: 'Tom' }
    ];      

    var Employees = {
      EmployeeList: employeeList
    }

    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: '/Employees/Process',
        data: Employees,
        success: function () {          
            $('#InfoPanel').html('It worked!');
        },
        failure: function (response) {          
            $('#InfoPanel').html(response);
        }
    }); 
});


public void Process(List<Employee> EmployeeList)
{
    var emps = EmployeeList;
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Counting inversions in an array

Well I have a different solution but I am afraid that would work only for distinct array elements.

//Code
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int i,n;
    cin >> n;
    int arr[n],inv[n];
    for(i=0;i<n;i++){
        cin >> arr[i];
    }
    vector<int> v;
    v.push_back(arr[n-1]);
    inv[n-1]=0;
    for(i=n-2;i>=0;i--){
        auto it = lower_bound(v.begin(),v.end(),arr[i]); 
        //calculating least element in vector v which is greater than arr[i]
        inv[i]=it-v.begin();
        //calculating distance from starting of vector
        v.insert(it,arr[i]);
        //inserting that element into vector v
    }
    for(i=0;i<n;i++){
        cout << inv[i] << " ";
    }
    cout << endl;
    return 0;
}

To explain my code we keep on adding elements from the end of Array.For any incoming array element we find the index of first element in vector v which is greater than our incoming element and assign that value to inversion count of the index of incoming element.After that we insert that element into vector v at it's correct position such that vector v remain in sorted order.

//INPUT     
4
2 1 4 3

//OUTPUT    
1 0 1 0

//To calculate total inversion count just add up all the elements in output array

Change the Arrow buttons in Slick slider

For changing the color

.slick-prev:before {
  color: some-color!important;
}
.slick-next:before {
  color: some-color!important;
}

How can the size of an input text box be defined in HTML?

Try this

<input type="text" style="font-size:18pt;height:420px;width:200px;">

Or else

 <input type="text" id="txtbox">

with the css:

 #txtbox
    {
     font-size:18pt;
     height:420px;
     width:200px;
    }

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

PHP:

$string ='This is the match [more or less]';
preg_match('#\[(.*)\]#', $string, $match);
var_dump($match[1]);

How to insert TIMESTAMP into my MySQL table?

The DEFAULT value of a column in MySql is used only if it isn't provided a value for that column. So if you

INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', '', '$comments')

You are not using the DEFAULT value for the column date, but you are providing an empty string, so you get an error, because you can't store an empty string in a DATETIME column. The same thing apply if you use NULL, because again NULL is a value. However, if you remove the column from the list of the column you are inserting, MySql will use the DEFAULT value specified for that column (or the data type default one)

Spring boot: Unable to start embedded Tomcat servlet container

If you are running on a linux environment, basically your app does not have rights for the default port.

Try 8181 by giving the following option on VM.

-Dserver.port=8181

'mvn' is not recognized as an internal or external command,

Make sure you have your maven bin directory in the path and the JAVA_HOME property set

How to get error information when HttpWebRequest.GetResponse() fails

Is this possible using HttpWebRequest and HttpWebResponse?

You could have your web server simply catch and write the exception text into the body of the response, then set status code to 500. Now the client would throw an exception when it encounters a 500 error but you could read the response stream and fetch the message of the exception.

So you could catch a WebException which is what will be thrown if a non 200 status code is returned from the server and read its body:

catch (WebException ex)
{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

SQL, How to Concatenate results?

This one automatically excludes the trailing comma, unlike most of the other answers.

DECLARE @csv VARCHAR(1000)

SELECT @csv = COALESCE(@csv + ',', '') + ModuleValue
FROM Table_X
WHERE ModuleID = @ModuleID

(If the ModuleValue column isn't already a string type then you might need to cast it to a VARCHAR.)

How to check the differences between local and github before the pull

If you're not interested in the details that git diff outputs you can just run git cherry which will output a list of commits your remote tracking branch has ahead of your local branch.

For example:

git fetch origin
git cherry master origin/master

Will output something like :

+ 2642039b1a4c4d4345a0d02f79ccc3690e19d9b1
+ a4870f9fbde61d2d657e97b72b61f46d1fd265a9

Indicates that there are two commits in my remote tracking branch that haven't been merged into my local branch.

This also works the other way :

    git cherry origin/master master

Will show you a list of local commits that you haven't pushed to your remote repository yet.

Paging UICollectionView by cells, not screen

Partly based on StevenOjo's answer. I've tested this using a horizontal scrolling and no Bounce UICollectionView. cellSize is CollectionViewCell size. You can tweak factor to modify scrolling sensitivity.

override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    targetContentOffset.pointee = scrollView.contentOffset
    var factor: CGFloat = 0.5
    if velocity.x < 0 {
        factor = -factor
    }
    let indexPath = IndexPath(row: (scrollView.contentOffset.x/cellSize.width + factor).int, section: 0)
    collectionView?.scrollToItem(at: indexPath, at: .left, animated: true)
}

Render HTML to an image

All the answers here use third party libraries while rendering HTML to an image can be relatively simple in pure Javascript. There is was even an article about it on the canvas section on MDN.

The trick is this:

  • create an SVG with a foreignObject node containing your XHTML
  • set the src of an image to the data url of that SVG
  • drawImage onto the canvas
  • set canvas data to target image.src

_x000D_
_x000D_
const {body} = document_x000D_
_x000D_
const canvas = document.createElement('canvas')_x000D_
const ctx = canvas.getContext('2d')_x000D_
canvas.width = canvas.height = 100_x000D_
_x000D_
const tempImg = document.createElement('img')_x000D_
tempImg.addEventListener('load', onTempImageLoad)_x000D_
tempImg.src = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml"><style>em{color:red;}</style><em>I</em> lick <span>cheese</span></div></foreignObject></svg>')_x000D_
_x000D_
const targetImg = document.createElement('img')_x000D_
body.appendChild(targetImg)_x000D_
_x000D_
function onTempImageLoad(e){_x000D_
  ctx.drawImage(e.target, 0, 0)_x000D_
  targetImg.src = canvas.toDataURL()_x000D_
}
_x000D_
_x000D_
_x000D_

Some things to note

  • The HTML inside the SVG has to be XHTML
  • For security reasons the SVG as data url of an image acts as an isolated CSS scope for the HTML since no external sources can be loaded. So a Google font for instance has to be inlined using a tool like this one.
  • Even when the HTML inside the SVG exceeds the size of the image it wil draw onto the canvas correctly. But the actual height cannot be measured from that image. A fixed height solution will work just fine but dynamic height will require a bit more work. The best is to render the SVG data into an iframe (for isolated CSS scope) and use the resulting size for the canvas.

Difference between app.use and app.get in express.js

Simply app.use means “Run this on ALL requests”
app.get means “Run this on a GET request, for the given URL”