Programs & Examples On #Umbraco

Umbraco is an open source .NET based content management system. It is released under the MIT license and powers a number of high profile sites, most notably Microsoft's own www.asp.net website.

How do detect Android Tablets in general. Useragent?

Here is what I use:

public static boolean onTablet()
    {
    int intScreenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;

    return (intScreenSize == Configuration.SCREENLAYOUT_SIZE_LARGE) // LARGE
    || (intScreenSize == Configuration.SCREENLAYOUT_SIZE_LARGE + 1); // Configuration.SCREENLAYOUT_SIZE_XLARGE
    }

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

I had the same issue, but I have resolved it the next:

1) Install jdk1.8...

2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.

3) Click Ok.

How to change text transparency in HTML/CSS?

try to play around with mix-blend-mode: multiply;

color: white;
background: black;
mix-blend-mode: multiply;

MDN

tutorial

The best way to remove duplicate values from NSMutableArray in Objective-C?

Using Orderedset will do the trick. This will keep the remove duplicates from the array and maintain order which sets normally doesn't do

Duplicate and rename Xcode project & associated folders

I using Xcode 6+ and I just do:

  • Copy all files in project folders to new Folders (with new name).
  • Open *.xcodeproj or *.xcworkspace
  • Change name of Project.
  • Click on schema and delete current chema and add new one.

Here is done, but name of window Xcode and *.xcodeproj or *.xcworkspace still <old-name>. Then I do:

  • pop install
  • Open <new name>.xcworkspace

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Selenium Webdriver submit() vs click()

The submit() function is there to make life easier. You can use it on any element inside of form tags to submit that form.

You can also search for the submit button and use click().

So the only difference is click() has to be done on the submit button and submit() can be done on any form element.

It's up to you.

http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms

Delayed function calls

private static volatile List<System.Threading.Timer> _timers = new List<System.Threading.Timer>();
        private static object lockobj = new object();
        public static void SetTimeout(Action action, int delayInMilliseconds)
        {
            System.Threading.Timer timer = null;
            var cb = new System.Threading.TimerCallback((state) =>
            {
                lock (lockobj)
                    _timers.Remove(timer);
                timer.Dispose();
                action()
            });
            lock (lockobj)
                _timers.Add(timer = new System.Threading.Timer(cb, null, delayInMilliseconds, System.Threading.Timeout.Infinite));
}

MySQL Orderby a number, Nulls last

MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC:

SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC

It is essentially the inverse of position DESC placing the NULL values last but otherwise the same as position ASC.

A good reference is here http://troels.arvin.dk/db/rdbms#select-order_by

How do I kill a VMware virtual machine that won't die?

Similar, but using WMIC command line to obtain the process ID and path:

WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid

This will create a text file with each process and its parameters. You can search in the file for your VM File Path, and get the correct Process ID to end task with.

Thanks to http://windowsxp.mvps.org/listproc.htm for the correct command line parameters.

What does the @ symbol before a variable name mean in C#?

It allows you to use a C# keyword as a variable. For example:

class MyClass
{
   public string name { get; set; }
   public string @class { get; set; }
}

How to configure welcome file list in web.xml

I guess what you want is your index servlet to act as the welcome page, so change to:

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

So that the index servlet will be used. Note, you'll need a servlet spec 2.4 container to be able to do this.

Note also, @BalusC gets my vote, for your index servlet on its own is superfluous.

How to get the command line args passed to a running process on unix/linux systems?

There are several options:

ps -fp <pid>
cat /proc/<pid>/cmdline | sed -e "s/\x00/ /g"; echo

There is more info in /proc/<pid> on Linux, just have a look.

On other Unixes things might be different. The ps command will work everywhere, the /proc stuff is OS specific. For example on AIX there is no cmdline in /proc.

Capture key press (or keydown) event on DIV element

Here example on plain JS:

_x000D_
_x000D_
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
  console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
  outline: none;_x000D_
}
_x000D_
<div _x000D_
  id="myDiv"_x000D_
  tabindex="0"_x000D_
>_x000D_
  Press me and start typing_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the difference between JavaScript and JScript?

There are some code differences to be aware of.

A negative first parameter to subtr is not supported, e.g. in Javascript: "string".substr(-1) returns "g", whereas in JScript: "string".substr(-1) returns "string"

It's possible to do "string"[0] to get "s" in Javascript, but JScript doesn't support such a construct. (Actually, only modern browsers appear to support the "string"[0] construct.

Changing plot scale by a factor in matplotlib

As you have noticed, xscale and yscale does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

A complete example showing both x and y scaling:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude

# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)

# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)

ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)

ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')

plt.show() 

And finally I have the credits for a picture:

Left: ax1 no scaling, right: ax2 y axis scaled to kilo and x axis scaled to nano

Note that, if you have text.usetex: true as I have, you may want to enclose the labels in $, like so: '${0:g}$'.

How to stop a looping thread in Python?

Depends on what you run in that thread. If that's your code, then you can implement a stop condition (see other answers).

However, if what you want is to run someone else's code, then you should fork and start a process. Like this:

import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()

now, whenever you want to stop that process, send it a SIGTERM like this:

proc.terminate()
proc.join()

And it's not slow: fractions of a second. Enjoy :)

error: RPC failed; curl transfer closed with outstanding read data remaining

can be two reason

  1. Internet is slow (this was in my case)
  2. buffer size is less,in this case you can run command git config --global http.postBuffer 524288000

Paste a multi-line Java String in Eclipse

As far as i know this seems out of scope of an IDE. Copyin ,you can copy the string and then try to format it using ctrl+shift+ F Most often these multiline strings are not used hard coded,rather they shall be used from property or xml files.which can be edited at later point of time without the need for code change

Vagrant stuck connection timeout retrying

I had the same trouble with Vagrant 1.6.5 and Virtual Box 4.3.16. The solution described at https://github.com/mitchellh/vagrant/issues/4470 worked fine for me, I just had to remove VirtualBox 4.3.16 and install the older version 4.3.12.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

There are Following Steps to solve this issue.


1. Go to C:\Users\ ~User Name~ \.gradle\wrapper\dists.
2. Delete all the files and folders from dists folder.
3. If Android Studio is Opened then Close any opened project and Reopen the project. The Android Studio Will automatic download all the required files.


(The required time is as per your Internet Speed (Download Size will be about "89 MB"). To see the progress of the downloading Go to C:\Users\ ~User Name~ \.gradle\wrapper\dists folder and check the size of the folder.)

error: Unable to find vcvarsall.bat

Is Microsoft Visual C++ Compiler for Python 2.7 at http://www.microsoft.com/en-us/download/details.aspx?id=44266 not a solution?

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

In addition to RMT's answer. I also had to modify the code a bit.

  1. Transport.send should be accessed statically
  2. therefor, transport.connect did not do anything for me, I only needed to set the connection info in the initial Properties object.

here is my sample send() methods. The config object is just a dumb data container.

public boolean send(String to, String from, String subject, String text) {
    return send(new String[] {to}, from, subject, text);
}

public boolean send(String[] to, String from, String subject, String text) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", config.host);
    props.put("mail.smtp.user", config.username);
    props.put("mail.smtp.port", config.port);
    props.put("mail.smtp.password", config.password);

    Session session = Session.getInstance(props, new SmtpAuthenticator(config));

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        InternetAddress[] addressTo = new InternetAddress[to.length];
        for (int i = 0; i < to.length; i++) {
            addressTo[i] = new InternetAddress(to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, addressTo);
        message.setSubject(subject);
        message.setText(text);
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

How to append in a json file in Python?

You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.

Creating an Arraylist of Objects

If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.

//here I will create my ArrayList:

ArrayList <Rectangle> rectangles= new ArrayList <>(3); 

int length;
int width;

for(int index =0; index <3;index++)
{JOptionPane.showMessageDialog(null, "Rectangle " + (index + 1));
 length = JOptionPane.showInputDialog("Enter length");
 width = JOptionPane.showInputDialog("Enter width");

 //Now I will create my Rectangle and add it to my rectangles ArrayList:

 rectangles.add(new Rectangle(length,width));

//This passes the length and width values to the rectangle constructor,
  which will create a new Rectangle and add it to the ArrayList.

}

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB is for binary data (videos, images, documents, other)

CLOB is for large text data (text)

Maximum size on MySQL 2GB

Maximum size on Oracle 128TB

Darken background image on hover

You can use opacity:

.image {
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
    width: 58px;
    height: 58px;
    opacity:0.5;
}

.image:hover{
    opacity:1;
}

JSFiddle

string to string array conversion in java

String array = array of characters ?

Or do you have a string with multiple words each of which should be an array element ?

String[] array = yourString.split(wordSeparator);

Create a HTML table where each TR is a FORM

You can use the form attribute id to span a form over multiple elements each using the form attribute with the name of the form as follows:

<table>
     <tr>
          <td>
               <form method="POST" id="form-1" action="/submit/form-1"></form>
               <input name="a" form="form-1">
          </td>
          <td><input name="b" form="form-1"></td>
          <td><input name="c" form="form-1"></td>
          <td><input type="submit" form="form-1"></td>
     </tr>
</table>

How to disable a button when an input is empty?

Another way to check is to inline the function, so that the condition will be checked on every render (every props and state change)

const isDisabled = () => 
  // condition check

This works:

<button
  type="button"
  disabled={this.isDisabled()}
>
  Let Me In
</button>

but this will not work:

<button
   type="button"
   disabled={this.isDisabled}
>
  Let Me In
</button>

XAMPP - Apache could not start - Attempting to start Apache service

I had this issue when I installed under Program Files, which they do not recommend due to write issues. This might only be a problem if you are not logged in as an admin and use a password to install. I just uninstalled and installed in a directory that did not need admin privileges.

Find a row in dataGridView based on column and value

Or you can use like this. This may be faster.

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );

Find duplicate values in R

You could use table, i.e.

n_occur <- data.frame(table(vocabulary$id))

gives you a data frame with a list of ids and the number of times they occurred.

n_occur[n_occur$Freq > 1,]

tells you which ids occurred more than once.

vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]

returns the records with more than one occurrence.

Is there a way to use PhantomJS in Python?

PhantomJS recently dropped Python support altogether. However, PhantomJS now embeds Ghost Driver.

A new project has since stepped up to fill the void: ghost.py. You probably want to use that instead:

from ghost import Ghost
ghost = Ghost()

with ghost.start() as session:
    page, extra_resources = ghost.open("http://jeanphi.me")
    assert page.http_status==200 and 'jeanphix' in ghost.content

How to edit default.aspx on SharePoint site without SharePoint Designer

Go to view all content of the site (http://yourdmain.sharepoint/sitename/_layouts/viewlsts.aspx). Select the document library "Pages" (the "Pages" library are named based on the language you created the site in. I.E. in norwegian the library is named "Sider"). Download the default.aspx to you computer and fix it (remove the web part and the <%Register tag). Save it and upload it back to the library (remember to check in the file).

EDIT:

ahh.. you are not using a publishing site template. Go to site action -> site settings. Under "site administration" select the menu "content and structure" you should now see your default.aspx page. But you cant do much with it...(delete, copy or move)

workaround: Enable publishing feature to the root web. Add the fixed default.aspx file to the Pages library and change the welcome page to this. Disable the publishing feature (this will delete all other list create from this feature but not the Pages library since one page is in use.). You will now have a new default.aspx page for the root web but the url is changed from sitename/default.aspx to sitename/Pages/default.aspx.

workaround II Use a feature to change the default.aspx file. The solution is explained here: http://wssguy.com/blogs/dan/archive/2008/10/29/how-to-change-the-default-page-of-a-sharepoint-site-using-a-feature.aspx

@Nullable annotation usage

This annotation is commonly used to eliminate NullPointerExceptions. @Nullable says that this parameter might be null. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null. If you would try to pass null without an annotation the framework would refuse to do it's job.

What is more @Nullable might be used with @NotNull annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.

How to fix "unable to open stdio.h in Turbo C" error?

Well, I've been working backshift just spent about 6 hours trying to figure this out.

All of the above information led to this conclusion along with a single line in dos prompt screen, when I exited the editor, go to the dos prompt my C: drive is mounted.

I did a dir search and what I found was: the way in which I had mounted the C drive initially looked like this

mount c: /

and my dir did not list all files on the C drive only files within the turboc++ folder. From that I had drawn the conclusion that my directories should look like:

c:\include

not

c:\turboc++\tc\include

or

c:\tc\include

The real problem was the nature in which I had mounted the drive.

Hope this helps someone.

b.mac

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

How to add colored border on cardview?

As the accepted answer requires you to add a Frame Layout, here how you can do it with material design.

Add this if you haven't already

implementation 'com.google.android.material:material:1.0.0'

Now change to Cardview to MaterialCardView

<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"

app:strokeWidth="1dp"
app:strokeColor="@color/black">

Now you need to change the activity theme to Theme.Material. If you are using Theme.Appcompact I will suggest you to move to Theme.Material for future projects for having better material design in you app.

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

Stop mouse event propagation

Nothing worked for IE (Internet Explorer). My testers were able to break my modal by clicking off the popup window on buttons behind it. So, I listened for a click on my modal screen div and forced refocus on a popup button.

<div class="modal-backscreen" (click)="modalOutsideClick($event)">
</div>


modalOutsideClick(event: any) {
   event.preventDefault()
   // handle IE click-through modal bug
   event.stopPropagation()
   setTimeout(() => {
      this.renderer.invokeElementMethod(this.myModal.nativeElement, 'focus')
   }, 100)
} 

Python Matplotlib Y-Axis ticks on Right Side of Plot

For right labels use ax.yaxis.set_label_position("right"), i.e.:

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()

How to correctly display .csv files within Excel 2013?

Taken from https://superuser.com/questions/238944/how-to-force-excel-to-open-csv-files-with-data-arranged-in-columns

The behavior of Excel when opening CSV files heavily depends on your local settings and the selected list separator under Region and language » Formats » Advanced. By default Excel will assume every CSV was saved with that separator. Which is true as long as the CSV doesn't come from another country!

If your customers are in other countries, they may see other results then you think.

For example, here you see that a German Excel will use semicolon instead of comma like in the U.S.

Regional Settings

How do I remove an item from a stl vector with a certain value?

Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.

Documentation links
std::remove http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase http://www.cppreference.com/cppvector/erase.html

std::vector<int> v;
v.push_back(1);
v.push_back(2);

//Vector should contain the elements 1, 2

//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);

//Erase the "removed" elements.
v.erase(newEnd, v.end());

//Vector should now only contain 2

Thanks to Jim Buck for pointing out my error.

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

You can take the SelectedItem and cast it back to your class and access its properties.

 MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);

Edit You can try using DataTextField and DataValueField, I used it with DataSource.

ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";

Insert, on duplicate update in PostgreSQL?

I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.

My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.

This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.

The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.

 #This is pseudo-code - within the application:
 BEGIN TRANSACTION - get transaction lock
 SELECT all current name value pairs where id = $id into a hash record
 create a merge record from the current and update record
  (set intersection where shared keys in new win, and empty values in new are deleted).
 DELETE all name value pairs where id = $id
 COPY/INSERT merged records 
 END TRANSACTION

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

For me (in Angular project) this code helped:

In HTML you should add autoplay muted

In JS/TS

playVideo() {
    const media = this.videoplayer.nativeElement;
    media.muted = true; // without this line it's not working although I have "muted" in HTML
    media.play();
}

Compare 2 arrays which returns difference

/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                    difference.push(array1[i]);
        }
    }

    return difference;
}   

You can then call the function anywhere in your code.

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

Passing a dictionary to a function as keyword parameters

Here ya go - works just any other iterable:

d = {'param' : 'test'}

def f(dictionary):
    for key in dictionary:
        print key

f(d)

How do you access the value of an SQL count () query in a Java program

        <%
        try{
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
            if(con == null) System.out.print("not connected");
            Statement st = con.createStatement();
            String myStatement = "select count(*) as total from locations";
            ResultSet rs = st.executeQuery(myStatement);
            int num = 0;
            while(rs.next()){
                num = (rs.getInt(1));
            }

        }
        catch(Exception e){
            System.out.println(e);  
        }

        %>

Simple URL GET/POST function in Python

You could use this to wrap urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

That will return a Request object that has result data and response codes.

How to change the size of the radio button using CSS?

Directly you can not do this. [As per my knowledge].

You should use images to supplant the radio buttons. You can make them function in the same manner as the radio buttons inmost cases, and you can make them any size you want.

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Implement touch using Python?

For a more low-level solution one can use

os.close(os.open("file.txt", os.O_CREAT))

How to hide a div from code (c#)

The above answers are fine but I would add to be sure the div is defined in the designer.cs file. This doesn't always happen when adding a div to the .aspx file. Not sure why but there are threads concerning this issue in this forum. Eg:

protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

'ssh' is not recognized as an internal or external command

Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy

Install SSH

It seems that ssh is not installed on your computer.

You can install openssh from here : http://openssh.en.softonic.com/download

Generate your key

Than you will have to geneate your ssh-key. There's a good tutorial about this here:

https://help.github.com/articles/generating-ssh-keys#platform-windows

Deploy

To deploy, you just have to push your code over git. Something like this:

git push fort master

If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.

SSH

The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication

Xcode 9 error: "iPhone has denied the launch request"

These simple steps helped me.

  1. Remove your connected iPhone, iPad from the mac.
  2. Restart your device.
  3. Select "Automatically manage signing" in Xcode settings.
  4. Reconnect your iPhone, iPad.

How do I access an access array item by index in handlebars?

The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:

{{people.[1].name}}
{{people.1.name}}

However, the square brackets are required in:

{{#with people.[1]}}
  {{name}}
{{/with}}

In the latter, using the index number without the square brackets would get one:

Error: Parse error on line ...:
...     {{#with people.1}}                
-----------------------^
Expecting 'ID', got 'INTEGER'

As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?

(Tested with Handlebars in YUI.)

2.xx Update

You can now use the get helper for this:

(get people index)

although if you get an error about index needing to be a string, do:

(get people (concat index ""))

How to append new data onto a new line

I had the same issue. And I was able to solve it by using a formatter.

file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()

I hope this helps.

What is the difference between _tmain() and main() in C++?

_tmain does not exist in C++. main does.

_tmain is a Microsoft extension.

main is, according to the C++ standard, the program's entry point. It has one of these two signatures:

int main();
int main(int argc, char* argv[]);

Microsoft has added a wmain which replaces the second signature with this:

int wmain(int argc, wchar_t* argv[]);

And then, to make it easier to switch between Unicode (UTF-16) and their multibyte character set, they've defined _tmain which, if Unicode is enabled, is compiled as wmain, and otherwise as main.

As for the second part of your question, the first part of the puzzle is that your main function is wrong. wmain should take a wchar_t argument, not char. Since the compiler doesn't enforce this for the main function, you get a program where an array of wchar_t strings are passed to the main function, which interprets them as char strings.

Now, in UTF-16, the character set used by Windows when Unicode is enabled, all the ASCII characters are represented as the pair of bytes \0 followed by the ASCII value.

And since the x86 CPU is little-endian, the order of these bytes are swapped, so that the ASCII value comes first, then followed by a null byte.

And in a char string, how is the string usually terminated? Yep, by a null byte. So your program sees a bunch of strings, each one byte long.

In general, you have three options when doing Windows programming:

  • Explicitly use Unicode (call wmain, and for every Windows API function which takes char-related arguments, call the -W version of the function. Instead of CreateWindow, call CreateWindowW). And instead of using char use wchar_t, and so on
  • Explicitly disable Unicode. Call main, and CreateWindowA, and use char for strings.
  • Allow both. (call _tmain, and CreateWindow, which resolve to main/_tmain and CreateWindowA/CreateWindowW), and use TCHAR instead of char/wchar_t.

The same applies to the string types defined by windows.h: LPCTSTR resolves to either LPCSTR or LPCWSTR, and for every other type that includes char or wchar_t, a -T- version always exists which can be used instead.

Note that all of this is Microsoft specific. TCHAR is not a standard C++ type, it is a macro defined in windows.h. wmain and _tmain are also defined by Microsoft only.

Is it possible to move/rename files in Git and maintain their history?

To rename a directory or file (I don't know much about complex cases, so there might be some caveats):

git filter-repo --path-rename OLD_NAME:NEW_NAME

To rename a directory in files that mention it (it's possible to use callbacks, but I don't know how):

git filter-repo --replace-text expressions.txt

expressions.txt is a file filled with lines like literal:OLD_NAME==>NEW_NAME (it's possible to use Python's RE with regex: or glob with glob:).

To rename a directory in messages of commits:

git-filter-repo --message-callback 'return message.replace(b"OLD_NAME", b"NEW_NAME")'

Python's regular expressions are also supported, but they must be written in Python, manually.

If the repository is original, without remote, you will have to add --force to force a rewrite. (You may want to create a backup of your repository before doing this.)

If you do not want to preserve refs (they will be displayed in the branch history of Git GUI), you will have to add --replace-refs delete-no-add.

Could not find main class HelloWorld

I have also faced same problem....

Actually this problem is raised due to the fact that your program .class files are not saved in that directory. Remove your CLASSPATH from your environment variable (you do no need to set classpath for simple Java programs) and reopen cmd prompt, then compile and execute.

If you observe carefully your .class file will save in the same location. (I am not an expert, I am also basic programer if there is any mistake in my sentences please ignore it :-))

Release generating .pdb files, why?

Actually without PDB files and symbolic information they have it would be impossible to create a successful crash report (memory dump files) and Microsoft would not have the complete picture what caused the problem.

And so having PDB improves crash reporting.

The module ".dll" was loaded but the entry-point was not found

I had this problem and

dumpbin /exports mydll.dll

and

depends mydll.dll

showed 'DllRegisterServer'.

The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.

Convert absolute path into relative path given a current directory using Bash

Python's os.path.relpath as a shell function

The goal of this relpath exercise is to mimic Python 2.7's os.path.relpath function (available from Python version 2.6 but only working properly in 2.7), as proposed by xni. As a consequence, some of the results may differ from functions provided in other answers.

(I have not tested with newlines in paths simply because it breaks the validation based on calling python -c from ZSH. It would certainly be possible with some effort.)

Regarding “magic” in Bash, I have given up looking for magic in Bash long ago, but I have since found all the magic I need, and then some, in ZSH.

Consequently, I propose two implementations.

The first implementation aims to be fully POSIX-compliant. I have tested it with /bin/dash on Debian 6.0.6 “Squeeze”. It also works perfectly with /bin/sh on OS X 10.8.3, which is actually Bash version 3.2 pretending to be a POSIX shell.

The second implementation is a ZSH shell function that is robust against multiple slashes and other nuisances in paths. If you have ZSH available, this is the recommended version, even if you are calling it in the script form presented below (i.e. with a shebang of #!/usr/bin/env zsh) from another shell.

Finally, I have written a ZSH script that verifies the output of the relpath command found in $PATH given the test cases provided in other answers. I added some spice to those tests by adding some spaces, tabs, and punctuation such as ! ? * here and there and also threw in yet another test with exotic UTF-8 characters found in vim-powerline.

POSIX shell function

First, the POSIX-compliant shell function. It works with a variety of paths, but does not clean multiple slashes or resolve symlinks.

#!/bin/sh
relpath () {
    [ $# -ge 1 ] && [ $# -le 2 ] || return 1
    current="${2:+"$1"}"
    target="${2:-"$1"}"
    [ "$target" != . ] || target=/
    target="/${target##/}"
    [ "$current" != . ] || current=/
    current="${current:="/"}"
    current="/${current##/}"
    appendix="${target##/}"
    relative=''
    while appendix="${target#"$current"/}"
        [ "$current" != '/' ] && [ "$appendix" = "$target" ]; do
        if [ "$current" = "$appendix" ]; then
            relative="${relative:-.}"
            echo "${relative#/}"
            return 0
        fi
        current="${current%/*}"
        relative="$relative${relative:+/}.."
    done
    relative="$relative${relative:+${appendix:+/}}${appendix#/}"
    echo "$relative"
}
relpath "$@"

ZSH shell function

Now, the more robust zsh version. If you would like it to resolve the arguments to real paths à la realpath -f (available in the Linux coreutils package), replace the :a on lines 3 and 4 with :A.

To use this in zsh, remove the first and last line and put it in a directory that is in your $FPATH variable.

#!/usr/bin/env zsh
relpath () {
    [[ $# -ge 1 ]] && [[ $# -le 2 ]] || return 1
    local target=${${2:-$1}:a} # replace `:a' by `:A` to resolve symlinks
    local current=${${${2:+$1}:-$PWD}:a} # replace `:a' by `:A` to resolve symlinks
    local appendix=${target#/}
    local relative=''
    while appendix=${target#$current/}
        [[ $current != '/' ]] && [[ $appendix = $target ]]; do
        if [[ $current = $appendix ]]; then
            relative=${relative:-.}
            print ${relative#/}
            return 0
        fi
        current=${current%/*}
        relative="$relative${relative:+/}.."
    done
    relative+=${relative:+${appendix:+/}}${appendix#/}
    print $relative
}
relpath "$@"

Test script

Finally, the test script. It accepts one option, namely -v to enable verbose output.

#!/usr/bin/env zsh
set -eu
VERBOSE=false
script_name=$(basename $0)

usage () {
    print "\n    Usage: $script_name SRC_PATH DESTINATION_PATH\n" >&2
    exit ${1:=1}
}
vrb () { $VERBOSE && print -P ${(%)@} || return 0; }

relpath_check () {
    [[ $# -ge 1 ]] && [[ $# -le 2 ]] || return 1
    target=${${2:-$1}}
    prefix=${${${2:+$1}:-$PWD}}
    result=$(relpath $prefix $target)
    # Compare with python's os.path.relpath function
    py_result=$(python -c "import os.path; print os.path.relpath('$target', '$prefix')")
    col='%F{green}'
    if [[ $result != $py_result ]] && col='%F{red}' || $VERBOSE; then
        print -P "${col}Source: '$prefix'\nDestination: '$target'%f"
        print -P "${col}relpath: ${(qq)result}%f"
        print -P "${col}python:  ${(qq)py_result}%f\n"
    fi
}

run_checks () {
    print "Running checks..."

    relpath_check '/    a   b/å/?*/!' '/    a   b/å/?/xäå/?'

    relpath_check '/'  '/A'
    relpath_check '/A'  '/'
    relpath_check '/  & /  !/*/\\/E' '/'
    relpath_check '/' '/  & /  !/*/\\/E'
    relpath_check '/  & /  !/*/\\/E' '/  & /  !/?/\\/E/F'
    relpath_check '/X/Y' '/  & /  !/C/\\/E/F'
    relpath_check '/  & /  !/C' '/A'
    relpath_check '/A /  !/C' '/A /B'
    relpath_check '/Â/  !/C' '/Â/  !/C'
    relpath_check '/  & /B / C' '/  & /B / C/D'
    relpath_check '/  & /  !/C' '/  & /  !/C/\\/Ê'
    relpath_check '/Å/  !/C' '/Å/  !/D'
    relpath_check '/.A /*B/C' '/.A /*B/\\/E'
    relpath_check '/  & /  !/C' '/  & /D'
    relpath_check '/  & /  !/C' '/  & /\\/E'
    relpath_check '/  & /  !/C' '/\\/E/F'

    relpath_check /home/part1/part2 /home/part1/part3
    relpath_check /home/part1/part2 /home/part4/part5
    relpath_check /home/part1/part2 /work/part6/part7
    relpath_check /home/part1       /work/part1/part2/part3/part4
    relpath_check /home             /work/part2/part3
    relpath_check /                 /work/part2/part3/part4
    relpath_check /home/part1/part2 /home/part1/part2/part3/part4
    relpath_check /home/part1/part2 /home/part1/part2/part3
    relpath_check /home/part1/part2 /home/part1/part2
    relpath_check /home/part1/part2 /home/part1
    relpath_check /home/part1/part2 /home
    relpath_check /home/part1/part2 /
    relpath_check /home/part1/part2 /work
    relpath_check /home/part1/part2 /work/part1
    relpath_check /home/part1/part2 /work/part1/part2
    relpath_check /home/part1/part2 /work/part1/part2/part3
    relpath_check /home/part1/part2 /work/part1/part2/part3/part4 
    relpath_check home/part1/part2 home/part1/part3
    relpath_check home/part1/part2 home/part4/part5
    relpath_check home/part1/part2 work/part6/part7
    relpath_check home/part1       work/part1/part2/part3/part4
    relpath_check home             work/part2/part3
    relpath_check .                work/part2/part3
    relpath_check home/part1/part2 home/part1/part2/part3/part4
    relpath_check home/part1/part2 home/part1/part2/part3
    relpath_check home/part1/part2 home/part1/part2
    relpath_check home/part1/part2 home/part1
    relpath_check home/part1/part2 home
    relpath_check home/part1/part2 .
    relpath_check home/part1/part2 work
    relpath_check home/part1/part2 work/part1
    relpath_check home/part1/part2 work/part1/part2
    relpath_check home/part1/part2 work/part1/part2/part3
    relpath_check home/part1/part2 work/part1/part2/part3/part4

    print "Done with checks."
}
if [[ $# -gt 0 ]] && [[ $1 = "-v" ]]; then
    VERBOSE=true
    shift
fi
if [[ $# -eq 0 ]]; then
    run_checks
else
    VERBOSE=true
    relpath_check "$@"
fi

Replace text in HTML page with jQuery

...I have a string "-9o0-9909" and I want to replace it with another string.

The code below will do that.

var str = '-9o0-9909';

str = 'new string';

Jokes aside, replacing text nodes is not trivial with JavaScript.

I've written a post about this: Replacing text with JavaScript.

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.

PyCharm import external library

In my case, the correct menu path was:

File > Default settings > Project Interpreter

What is the cleanest way to ssh and run multiple commands in Bash?

This works well for creating scripts, as you do not have to include other files:

#!/bin/bash
ssh <my_user>@<my_host> "bash -s" << EOF
    # here you just type all your commmands, as you can see, i.e.
    touch /tmp/test1;
    touch /tmp/test2;
    touch /tmp/test3;
EOF

# you can use '$(which bash) -s' instead of my "bash -s" as well
# but bash is usually being found in a standard location
# so for easier memorizing it i leave that out
# since i dont fat-finger my $PATH that bad so it cant even find /bin/bash ..

A 'for' loop to iterate over an enum in Java

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type:

 for (Direction d : Direction.values()) {
     System.out.println(d);
 }

View RDD contents in Python Spark?

You can simply collect the entire RDD (which will return a list of rows) and print said list:

print(wc.collect())

How to read existing text files without defining path

If your application is a web service, Directory.CurrentDirectory doesn't work.

Use System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "yourFileName.txt")) instead.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

enter image description here

Objective C

        [txt.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
        [txt.layer setBorderColor: [[UIColor grayColor] CGColor]];
        [txt.layer setBorderWidth: 0.0];
        [txt.layer setCornerRadius:12.0f];
        [txt.layer setMasksToBounds:NO];
        [txt.layer setShadowRadius:2.0f];
        txt.layer.shadowColor = [[UIColor blackColor] CGColor];
        txt.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
        txt.layer.shadowOpacity = 1.0f;
        txt.layer.shadowRadius = 1.0f;

Swift

        txt.layer.backgroundColor = UIColor.white.cgColor
        txt.layer.borderColor = UIColor.gray.cgColor
        txt.layer.borderWidth = 0.0
        txt.layer.cornerRadius = 5
        txt.layer.masksToBounds = false
        txt.layer.shadowRadius = 2.0
        txt.layer.shadowColor = UIColor.black.cgColor
        txt.layer.shadowOffset = CGSize.init(width: 1.0, height: 1.0)
        txt.layer.shadowOpacity = 1.0
        txt.layer.shadowRadius = 1.0

Detect Safari browser

I don't know why the OP wanted to detect Safari, but in the rare case you need browser sniffing nowadays it's problably more important to detect the render engine than the name of the browser. For example on iOS all browsers use the Safari/Webkit engine, so it's pointless to get "chrome" or "firefox" as browser name if the underlying renderer is in fact Safari/Webkit. I haven't tested this code with old browsers but it works with everything fairly recent on Android, iOS, OS X, Windows and Linux.

<script>
    let browserName = "";

    if(navigator.vendor.match(/google/i)) {
        browserName = 'chrome/blink';
    }
    else if(navigator.vendor.match(/apple/i)) {
        browserName = 'safari/webkit';
    }
    else if(navigator.userAgent.match(/firefox\//i)) {
        browserName = 'firefox/gecko';
    }
    else if(navigator.userAgent.match(/edge\//i)) {
        browserName = 'edge/edgehtml';
    }
    else if(navigator.userAgent.match(/trident\//i)) {
        browserName = 'ie/trident';
    }
    else
    {
        browserName = navigator.userAgent + "\n" + navigator.vendor;
    }
    alert(browserName);
</script>

To clarify:

  • All browsers under iOS will be reported as "safari/webkit"
  • All browsers under Android but Firefox will be reported as "chrome/blink"
  • Chrome, Opera, Blisk, Vivaldi etc. will all be reported as "chrome/blink" under Windows, OS X or Linux

Using VBA to get extended file attributes

You say loop .. so if you want to do this for a dir instead of the current document;

Dim sFile As Variant
Dim oShell: Set oShell = CreateObject("Shell.Application")
Dim oDir:   Set oDir = oShell.Namespace("c:\foo")

For Each sFile In oDir.Items
   Debug.Print oDir.GetDetailsOf(sFile, XXX) 
Next

Where XXX is an attribute column index, 9 for Author for example. To list available indexes for your reference you can replace the for loop with;

for i = 0 To 40
   debug.? i, oDir.GetDetailsOf(oDir.Items, i)
Next

Quickly for a single file/attribute:

Const PROP_COMPUTER As Long = 56

With CreateObject("Shell.Application").Namespace("C:\HOSTDIRECTORY")
    MsgBox .GetDetailsOf(.Items.Item("FILE.NAME"), PROP_COMPUTER)
End With

Count records for every month in a year

SELECT    COUNT(*) 
FROM      table_emp 
WHERE     YEAR(ARR_DATE) = '2012' 
GROUP BY  MONTH(ARR_DATE)

SQL Server 2008 can't login with newly created user

SQL Server was not configured to allow mixed authentication.

Here are steps to fix:

  1. Right-click on SQL Server instance at root of Object Explorer, click on Properties
  2. Select Security from the left pane.
  3. Select the SQL Server and Windows Authentication mode radio button, and click OK.

    enter image description here

  4. Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

How to convert int to string on Arduino?

use the itoa() function included in stdlib.h

char buffer[7];         //the ASCII of the integer will be stored in this char array
itoa(-31596,buffer,10); //(integer, yourBuffer, base)

java.lang.IllegalStateException: The specified child already has a parent

If you have this statement..

View view = inflater.inflate(R.layout.fragment1, container);//may be Incorrect 

Then try this.. Add false as third argument.. May be it could help..

View view = inflater.inflate(R.layout.fragment1, container, false);//correct one

cocoapods - 'pod install' takes forever

After a half of the day of investigating why Analyzing Dependencies takes forever, I found out that I was installing the latest Firebase pod (7.1.0), which relies on GoogleAppMeasurement version 7.1.0, and there was another pod, which is an ad mediation framework, which includes Google-Mobile-Ads-SDK. This SDK was relying on a much lower version of GoogleAppMeasurement ~ 6.0. I was able to install the pods by commenting out the conflicting pod from the ad mediation. Something like this:

# Ad network framework
  pod 'SomeMediationNetwork/Core'
#  pod 'SomeMediationNetwork/GoogleMobileAds' # - the conflicting pod
  pod 'SomeMediationNetwork/Facebook'
  pod 'SomeMediationNetwork/SmartAdServer'
  pod 'SomeMediationNetwork/Mopub'

I had to contact the ad mediation library publisher to fix this issue, most probably by updating to the latest Google-Mobile-Ads-SDK pod and releasing a new version.

I hope this one helps some other folks who are banging their head

Fatal error: Class 'SoapClient' not found

I couln't find the SOAP section in phpinfo() so I had to install it.

For information the SOAP extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required according to http://php.net/manual/en/soap.requirements.php

From WHM panel

  1. Software » Module Installers » PHP Extensions & Applications Package
  2. Install SOAP 0.13.0

    WARNING: "pear/HTTP_Request" is deprecated in favor of "pear/HTTP_Request2"

    install ok: channel://pear.php.net/SOAP-0.13.0

  3. Install HTTP_Request2 (optional)

    install ok: channel://pear.php.net/HTTP_Request2

  4. Restart Services » HTTP Server (Apache)

From shell command

1.pear install SOAP

2.reboot

How to check if a column exists in a datatable

You can use operator Contains,

private void ContainColumn(string columnName, DataTable table)
{
    DataColumnCollection columns = table.Columns;        
    if (columns.Contains(columnName))
    {
       ....
    }
}

MSDN - DataColumnCollection.Contains()

Simplest way to form a union of two lists

I think this is all you really need to do:

var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};

var listMerged = listA.Union(listB);

How do I restart a service on a remote machine in Windows?

I would suggest you to have a look at RSHD

You do not need to bother for a client, Windows has it by default.

How to use vagrant in a proxy environment?

Installing proxyconf will solve this, but behind a proxy you can't install a plugin simply using the command vagrant plugin install, Bundler will raise an error.

set your proxy in your environment if you're using a unix like system

export http_proxy=http://user:password@host:port

or get a more detailed answer here: How to use bundler behind a proxy?

after this set up proxyconf

How do I check to see if a value is an integer in MySQL?

I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do

select field from table where field REGEXP '^-?[0-9]+$';

this is reasonably fast. If your field is numeric, just test for

ceil(field) = field

instead.

How to get week number in Python?

I summarize the discussion to two steps:

  1. Convert the raw format to a datetime object.
  2. Use the function of a datetime object or a date object to calculate the week number.

Warm up

from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)

1st step

To manually generate a datetime object, we can use datetime.datetime(2017,5,3) or datetime.datetime.now().

But in reality, we usually need to parse an existing string. we can use strptime function, such as datetime.strptime('2017-5-3','%Y-%m-%d') in which you have to specific the format. Detail of different format code can be found in the official documentation.

Alternatively, a more convenient way is to use dateparse module. Examples are dateparser.parse('16 Jun 2010'), dateparser.parse('12/2/12') or dateparser.parse('2017-5-3')

The above two approaches will return a datetime object.

2nd step

Use the obtained datetime object to call strptime(format). For example,

python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.

It's very tricky to decide which format to use. A better way is to get a date object to call isocalendar(). For example,

python

dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar() 
print(year, week, weekday) # (2016,52,7) in the ISO standard

In reality, you will be more likely to use date.isocalendar() to prepare a weekly report, especially in the Christmas-New Year shopping season.

CodeIgniter - How to return Json response from controller

return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(array(
                    'text' => 'Error 500',
                    'type' => 'danger'
            )));

How to disable action bar permanently

You can force hide the action bar simply:

ActionBar  actionbar = getSupportActionBar();
actionbar.hide();

Just use your default theme, it will work good if fullscreen is set

HTML - Display image after selecting filename

This can be done using HTML5, but will only work in browsers that support it. Here's an example.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.

How to make program go back to the top of the code instead of closing

def start():

Offset = 5

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Please be sensible try just the lower case')

def getMessage():
    print('Enter your message wanted to :')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (Offset))
        key = int(input())
        if (key >= 1 and key <= Offset):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return

memcpy() vs memmove()

As already pointed out in other answers, memmove is more sophisticated than memcpy such that it accounts for memory overlaps. The result of memmove is defined as if the src was copied into a buffer and then buffer copied into dst. This does NOT mean that the actual implementation uses any buffer, but probably does some pointer arithmetic.

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

How to trigger a phone call when clicking a link in a web page on mobile phone

Just use HTML anchor tag <a> and start the attribute href with tel:. I suggest starting the phone number with the country code. pay attention to the following example:

<a href="tel:+989123456789">NO Different What it is</a>

For this example, the country code is +98.

Hint: It is so suitable for cellphones, I know tel: prefix calls FaceTime on macOS but on Windows I'm not sure, but I guess it caused to launch Skype.

For more information: you can visit the list of URL schemes supported by browsers to know all href values prefixes.

How to remove special characters from a string?

If you just want to do a literal replace in java, use Pattern.quote(string) to escape any string to a literal.

myString.replaceAll(Pattern.quote(matchingStr), replacementStr)

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

Hash String via SHA-256 in Java

Java 8: Base64 available:

    MessageDigest md = MessageDigest.getInstance( "SHA-512" );
    md.update( inbytes );
    byte[] aMessageDigest = md.digest();

    String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
    return( outEncoded );

Various ways to remove local Git changes

Use:

git checkout -- <file>

To discard the changes in the working directory.

What uses are there for "placement new"?

It's also useful when you want to re-initialize global or statically allocated structures.

The old C way was using memset() to set all elements to 0. You cannot do that in C++ due to vtables and custom object constructors.

So I sometimes use the following

 static Mystruct m;

 for(...)  {
     // re-initialize the structure. Note the use of placement new
     // and the extra parenthesis after Mystruct to force initialization.
     new (&m) Mystruct();

     // do-some work that modifies m's content.
 }

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

How can I force gradle to redownload dependencies?

You need to redownload it, so you can either manually download and replace the corrupted file and again sync your project . Go to this location C:\users[username].gradle\wrapper\dist\gradle3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9\gradle-3.3-all.zip Here delete gradle3.3allzip and replace it by downloading again from this site https://services.gradle.org/distributions/ Find the same file and download and paste it to that location Then sync your project. Hope it works for you too.

Resource files not found from JUnit test cases

My mistake, the resource files WERE actually copied to target/test-classes. The problem seemed to be due to spaces in my project name, e.g. Project%20Name.

I'm now loading the file as follows and it works:

org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);

Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):

myClass().getResource("resourceFile.txt")??.toURI();

Get safe area inset top and bottom heights

Swift 5, Xcode 11.4

`UIApplication.shared.keyWindow` 

It will give deprecation warning. ''keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes' because of connected scenes. I use this way.

extension UIView {

    var safeAreaBottom: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.bottom
            }
         }
         return 0
    }

    var safeAreaTop: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.top
            }
         }
         return 0
    }
}

extension UIApplication {
    var keyWindowInConnectedScenes: UIWindow? {
        return windows.first(where: { $0.isKeyWindow })
    }
}

How can I limit the visible options in an HTML <select> dropdown?

Tnx @Raj_89 , Your trick was very good , can be better , only by use extra style , that make it on other dom objects , exactly like a common select option tag in html ...

select{
 position:absolute;
}

u can see result here : http://jsfiddle.net/aTzc2/

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.

Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):

int x = 0;
auto f1 = [=]() mutable {x = 42;};  // OK
auto f2 = [=]()         {x = 42;};  // Error: a by-value capture cannot be modified in a non-mutable lambda

Adding values to Arraylist

Well by doing the above you open yourself to run time errors, unless you are happy to accept that your arraylists can contains both strings and integers and elephants.

Eclipse returns an error because it does not want you to be unaware of the fact that by specifying no type for the generic parameter you are opening yourself up for run time errors. At least with the other two examples you know that you can have objects in your Arraylist and since Inetegers and Strings are both objects Eclipse doesn't warn you.

Either code 2 or 3 are ok. But if you know you will have either only ints or only strings in your arraylist then I would do

ArrayList<Integer> arr = new ArrayList<Integer>();

or

ArrayList<String> arr = new ArrayList<String>();

respectively.

git command to move a folder inside another

I had similar problem, but in folder which I wanted to move I had files which I was not tracking.

let's say I had files

a/file1
a/untracked1
b/file2
b/untracked2

And I wanted to move only tracked files to subfolder subdir, so the goal was:

subdir/a/file1
subdir/a/untracked1
subdir/b/file2
subdir/b/untracked2

what I had done was:

  • I created new folder and moved all files that I was interested in moving: mkdir tmpdir && mv a b tmpdir
  • checked out old files git checkout a b
  • created new dir and moved clean folders (without untracked files) to new subdir: mkdir subdir && mv a b subdir
  • added all files from subdir (so Git could add only tracked previously files - it was somekind of git add --update with directory change trick): git add subdir (normally this would add even untracked files - this would require creating .gitignore file)
  • git status shows now only moved files
  • moved rest of files from tmpdir to subdir: mv tmpdir/* subdir
  • git status looks like we executed git mv :)

SQL Server : How to test if a string has only digit characters

I was attempting to find strings with numbers ONLY, no punctuation or anything else. I finally found an answer that would work here.

Using PATINDEX('%[^0-9]%', some_column) = 0 allowed me to filter out everything but actual number strings.

'innerText' works in IE, but not in Firefox

myElement.innerText = myElement.textContent = "foo";

Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.

How to add items into a numpy array

np.insert can also be used for the purpose

import numpy as np
a = np.array([[1, 3, 4],
              [1, 2, 3],
              [1, 2, 1]])
x = 5
index = 3 # the position for x to be inserted before
np.insert(a, index, x, axis=1)
array([[1, 3, 4, 5],
       [1, 2, 3, 5],
       [1, 2, 1, 5]])

index can also be a list/tuple

>>> index = [1, 1, 3] # equivalently (1, 1, 3)
>>> np.insert(a, index, x, axis=1)
array([[1, 5, 5, 3, 4, 5],
       [1, 5, 5, 2, 3, 5],
       [1, 5, 5, 2, 1, 5]])

or a slice

>>> index = slice(0, 3)
>>> np.insert(a, index, x, axis=1)
array([[5, 1, 5, 3, 5, 4],
       [5, 1, 5, 2, 5, 3],
       [5, 1, 5, 2, 5, 1]])

How to programmatically modify WCF app.config endpoint address setting?

I have modified and extended Malcolm Swaine's code to modify a specific node by it's name attribute, and to also modify an external config file. Hope it helps.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;

namespace LobbyGuard.UI.Registration
{
public class ConfigSettings
{

    private static string NodePath = "//system.serviceModel//client//endpoint";

    private ConfigSettings() { }

    public static string GetEndpointAddress()
    {
        return ConfigSettings.loadConfigDocument().SelectSingleNode(NodePath).Attributes["address"].Value;
    }

    public static void SaveEndpointAddress(string endpointAddress)
    {
        // load config document for current assembly
        XmlDocument doc = loadConfigDocument();

        // retrieve appSettings node
        XmlNodeList nodes = doc.SelectNodes(NodePath);

        foreach (XmlNode node in nodes)
        {
            if (node == null)
                throw new InvalidOperationException("Error. Could not find endpoint node in config file.");

            //If this isnt the node I want to change, look at the next one
            //Change this string to the name attribute of the node you want to change
            if (node.Attributes["name"].Value != "DataLocal_Endpoint1")
            {
                continue;
            }

            try
            {
                // select the 'add' element that contains the key
                //XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
                node.Attributes["address"].Value = endpointAddress;

                doc.Save(getConfigFilePath());

                break;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }

    public static void SaveEndpointAddress(string endpointAddress, string ConfigPath, string endpointName)
    {
        // load config document for current assembly
        XmlDocument doc = loadConfigDocument(ConfigPath);

        // retrieve appSettings node
        XmlNodeList nodes = doc.SelectNodes(NodePath);

        foreach (XmlNode node in nodes)
        {
            if (node == null)
                throw new InvalidOperationException("Error. Could not find endpoint node in config file.");

            //If this isnt the node I want to change, look at the next one
            if (node.Attributes["name"].Value != endpointName)
            {
                continue;
            }

            try
            {
                // select the 'add' element that contains the key
                //XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
                node.Attributes["address"].Value = endpointAddress;

                doc.Save(ConfigPath);

                break;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }

    public static XmlDocument loadConfigDocument()
    {
        XmlDocument doc = null;
        try
        {
            doc = new XmlDocument();
            doc.Load(getConfigFilePath());
            return doc;
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new Exception("No configuration file found.", e);
        }
    }

    public static XmlDocument loadConfigDocument(string Path)
    {
        XmlDocument doc = null;
        try
        {
            doc = new XmlDocument();
            doc.Load(Path);
            return doc;
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new Exception("No configuration file found.", e);
        }
    }

    private static string getConfigFilePath()
    {
        return Assembly.GetExecutingAssembly().Location + ".config";
    }
}

}

How to find out the number of CPUs using python

Another option is to use the psutil library, which always turn out useful in these situations:

>>> import psutil
>>> psutil.cpu_count()
2

This should work on any platform supported by psutil(Unix and Windows).

Note that in some occasions multiprocessing.cpu_count may raise a NotImplementedError while psutil will be able to obtain the number of CPUs. This is simply because psutil first tries to use the same techniques used by multiprocessing and, if those fail, it also uses other techniques.

How to keep one variable constant with other one changing with row in excel

Use this form:

=(B0+4)/$A$0

The $ tells excel not to adjust that address while pasting the formula into new cells.

Since you are dragging across rows, you really only need to freeze the row part:

=(B0+4)/A$0

Keyboard Shortcuts

Commenters helpfully pointed out that you can toggle relative addressing for a formula in the currently selected cells with these keyboard shortcuts:

  • Windows: f4
  • Mac: CommandT

How to read a PEM RSA private key from .NET

You might take a look at JavaScience's source for OpenSSLKey

There's code in there that does exactly what you want to do.

In fact, they have a lot of crypto source code available here.


Source code snippet:

//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider  ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;

        // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
        MemoryStream  mem = new MemoryStream(privkey) ;
        BinaryReader binr = new BinaryReader(mem) ;    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();        //advance 1 byte
                else if (twobytes == 0x8230)
                        binr.ReadInt16();       //advance 2 bytes
                else
                        return null;

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                        return null;
                bt = binr.ReadByte();
                if (bt !=0x00)
                        return null;


                //------  all private key components are Integer sequences ----
                elems = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                D = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                P = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                Q = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DP = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DQ = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                IQ = binr.ReadBytes(elems) ;

                Console.WriteLine("showing components ..");
                if (verbose) {
                        showBytes("\nModulus", MODULUS) ;
                        showBytes("\nExponent", E);
                        showBytes("\nD", D);
                        showBytes("\nP", P);
                        showBytes("\nQ", Q);
                        showBytes("\nDP", DP);
                        showBytes("\nDQ", DQ);
                        showBytes("\nIQ", IQ);
                }

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAparams = new RSAParameters();
                RSAparams.Modulus =MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D = D;
                RSAparams.P = P;
                RSAparams.Q = Q;
                RSAparams.DP = DP;
                RSAparams.DQ = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return RSA;
        }
        catch (Exception) {
                return null;
        }
        finally {
                binr.Close();
        }
}

How to get Domain name from URL using jquery..?

var hostname = window.location.origin

Will not work for IE. For IE support as well I would something like this:

var hostName = window.location.hostname;
var protocol = window.locatrion.protocol;
var finalUrl = protocol + '//' + hostname;

Oracle 12c Installation failed to access the temporary location

If your user account has spaces in it and you have tried all the above but none worked,

I recommended you create a new windows user account and give it an administrative privilege, not standard.

Log out of your old account and log into this new account and try installing again. It worked well.

file_put_contents(meta/services.json): failed to open stream: Permission denied

Just start your server using artisian

php artisian serve

Then access your project from the specified URL:

enter image description here

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

OrderBy descending in Lambda expression?

Try this another way:

var qry = Employees
          .OrderByDescending (s => s.EmpFName)
          .ThenBy (s => s.Address)
          .Select (s => s.EmpCode);

Queryable.ThenBy

How to check Elasticsearch cluster health?

You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:

$ curl -XGET 'localhost:9200/_cluster/health?pretty'

This will give you the status and other related data you need.

{
 "cluster_name" : "xxxxxxxx",
 "status" : "green",
 "timed_out" : false,
 "number_of_nodes" : 2,
 "number_of_data_nodes" : 2,
 "active_primary_shards" : 15,
 "active_shards" : 12,
 "relocating_shards" : 0,
 "initializing_shards" : 0,
 "unassigned_shards" : 0,
 "delayed_unassigned_shards" : 0,
 "number_of_pending_tasks" : 0,
 "number_of_in_flight_fetch" : 0
}

'tsc command not found' in compiling typescript

I had this same problem on Ubuntu 19.10 LTS.

To solve this I ran the following command:

$ sudo apt install node-typescript

After that, I was able to use tsc.

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

What is a good regular expression to match a URL?

(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})

Will match the following cases

  • http://www.foufos.gr
  • https://www.foufos.gr
  • http://foufos.gr
  • http://www.foufos.gr/kino
  • http://werer.gr
  • www.foufos.gr
  • www.mp3.com
  • www.t.co
  • http://t.co
  • http://www.t.co
  • https://www.t.co
  • www.aa.com
  • http://aa.com
  • http://www.aa.com
  • https://www.aa.com

Will NOT match the following

  • www.foufos
  • www.foufos-.gr
  • www.-foufos.gr
  • foufos.gr
  • http://www.foufos
  • http://foufos
  • www.mp3#.com

_x000D_
_x000D_
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;_x000D_
var regex = new RegExp(expression);_x000D_
_x000D_
var check = [_x000D_
  'http://www.foufos.gr',_x000D_
  'https://www.foufos.gr',_x000D_
  'http://foufos.gr',_x000D_
  'http://www.foufos.gr/kino',_x000D_
  'http://werer.gr',_x000D_
  'www.foufos.gr',_x000D_
  'www.mp3.com',_x000D_
  'www.t.co',_x000D_
  'http://t.co',_x000D_
  'http://www.t.co',_x000D_
  'https://www.t.co',_x000D_
  'www.aa.com',_x000D_
  'http://aa.com',_x000D_
  'http://www.aa.com',_x000D_
  'https://www.aa.com',_x000D_
  'www.foufos',_x000D_
  'www.foufos-.gr',_x000D_
  'www.-foufos.gr',_x000D_
  'foufos.gr',_x000D_
  'http://www.foufos',_x000D_
  'http://foufos',_x000D_
  'www.mp3#.com'_x000D_
];_x000D_
_x000D_
check.forEach(function(entry) {_x000D_
  if (entry.match(regex)) {_x000D_
    $("#output").append( "<div >Success: " + entry + "</div>" );_x000D_
  } else {_x000D_
    $("#output").append( "<div>Fail: " + entry + "</div>" );_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Check it in rubular - NEW version

Check it in rubular - old version

Exception of type 'System.OutOfMemoryException' was thrown. Why?

You're obviously not disposing of things.

Consider the "using" command when temporarily using objects that implement IDisposable.

Determine version of Entity Framework I am using?

If you go to references, click on the Entity Framework, view properties It will tell you the version number.

Electron: jQuery is not defined

electron FAQ answer :

http://electron.atom.io/docs/faq/

I can not use jQuery/RequireJS/Meteor/AngularJS in Electron.

Due to the Node.js integration of Electron, there are some extra symbols inserted into the DOM like module, exports, require. This causes problems for some libraries since they want to insert the symbols with the same names.

To solve this, you can turn off node integration in Electron:

// In the main process.

let win = new BrowserWindow({  
 webPreferences: {
 nodeIntegration: false   } });

But if you want to keep the abilities of using Node.js and Electron APIs, you have to rename the symbols in the page before including other libraries:

<head> 
<script> 
window.nodeRequire = require; 
delete window.require;
delete window.exports; delete window.module; 
</script> 
<script type="text/javascript" src="jquery.js"></script> 
</head>

Making an svg image object clickable with onclick, avoiding absolute positioning

Assuming you don't need cross browser support (which is impossible without a plugin for IE), have you tried using svg as a background image?

Experimental stuff for sure, but thought I would mention it.

Check file size before upload

JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.

How do I add 24 hours to a unix timestamp in php?

You probably want to add one day rather than 24 hours. Not all days have 24 hours due to (among other circumstances) daylight saving time:

strtotime('+1 day', $timestamp);

While loop in batch

set /a countfiles-=%countfiles%

This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:

set /a countfiles-=1

I'm not sure if the for loop will work, better try something like this:

:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop

PHP7 : install ext-dom issue

For whom want to install ext-dom on php 7.1 and up run this command:

sudo apt install php-xml

Browse files and subfolders in Python

from tkinter import *
import os

root = Tk()
file = filedialog.askdirectory()
changed_dir = os.listdir(file)
print(changed_dir)
root.mainloop()

Stop node.js program from command line

on linux try: pkill node

on windows:

Taskkill /IM node.exe /F

or

from subprocess import call

call(['taskkill', '/IM', 'node.exe', '/F'])

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

How to create an instance of System.IO.Stream stream

System.IO.Stream stream = new System.IO.MemoryStream();

Update multiple values in a single statement

Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:

update 
    MasterTbl
set
    TotalX = Sum(DetailTbl.X),
    TotalY = Sum(DetailTbl.Y),
    TotalZ = Sum(DetailTbl.Z)
from
    DetailTbl
where
    DetailTbl.MasterID = MasterID

Relative imports - ModuleNotFoundError: No module named x

Set PYTHONPATH environment variable in root project directory.

Considering UNIX-like:

export PYTHONPATH=.

Ignore files that have already been committed to a Git repository

If you need to stop tracking a lot of ignored files, you can combine some commands:

git ls-files -i --exclude-standard | xargs -L1 git rm --cached

This would stop tracking the ignored files. If you want to actually remove files from filesystem, do not use the --cached option. You can also specify a folder to limit the search, such as:

git ls-files -i --exclude-standard -- ${FOLDER} | xargs -L1 git rm

How to set bot's status

Use this:

client.user.setActivity("with depression", {
  type: "STREAMING",
  url: "https://www.twitch.tv/monstercat"
});

Creating a daemon in Linux

If your app is one of:

{
  ".sh": "bash",
  ".py": "python",
  ".rb": "ruby",
  ".coffee" : "coffee",
  ".php": "php",
  ".pl" : "perl",
  ".js" : "node"
}

and you don't mind a NodeJS dependency then install NodeJS and then:

npm install -g pm2

pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above

pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores

pm2 list

To keep all apps running on reboot (and daemonise pm2):

pm2 startup

pm2 save

Now you can:

service pm2 stop|restart|start|status

(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)

SSH SCP Local file to Remote in Terminal Mac Os X

Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.

So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:

Using scp, copy file to a directory in the remote user's account, for example the Documents directory:

scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents

Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:

ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www

Maximum size of a varchar(max) variable

EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value syntax is incorrect.

I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. error message. In 2008, the modified script is still successful.

declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

If you are using arrow functions:

it('should do something', async () => {
  // do your testing
}).timeout(15000)

Creating a copy of an object in C#

You could do:

class myClass : ICloneable
{
    public String test;
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

then you can do

myClass a = new myClass();
myClass b = (myClass)a.Clone();

N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.

How to select a record and update it, with a single queryset in Django?

only in a case in serializer things, you can update in very simple way!

my_model_serializer = MyModelSerializer(
    instance=my_model, data=validated_data)
if my_model_serializer.is_valid():

    my_model_serializer.save()

only in a case in form things!

instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
    form.save()

Javascript, viewing [object HTMLInputElement]

change:

$("input:text").change(function() {
    var value=$("input:text").val();
    alert(value);
});

to

$("input:text").change(function() {
    var value=$("input[type=text].selector").val();
    alert(value);
});

note: selector:id,class..

How to make sure that a certain Port is not occupied by any other process

It's netstat -ano|findstr port no

Result would show process id in last column

How can I generate a unique ID in Python?

You might want Python's UUID functions:

21.15. uuid — UUID objects according to RFC 4122

eg:

import uuid
print uuid.uuid4()

7d529dd4-548b-4258-aa8e-23e34dc8d43d

What is the difference between dict.items() and dict.iteritems() in Python2?

You asked: 'Are there any applicable differences between dict.items() and dict.iteritems()'

This may help (for Python 2.x):

>>> d={1:'one',2:'two',3:'three'}
>>> type(d.items())
<type 'list'>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>

You can see that d.items() returns a list of tuples of the key, value pairs and d.iteritems() returns a dictionary-itemiterator.

As a list, d.items() is slice-able:

>>> l1=d.items()[0]
>>> l1
(1, 'one')   # an unordered value!

But would not have an __iter__ method:

>>> next(d.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator

As an iterator, d.iteritems() is not slice-able:

>>> i1=d.iteritems()[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dictionary-itemiterator' object is not subscriptable

But does have __iter__:

>>> next(d.iteritems())
(1, 'one')               # an unordered value!

So the items themselves are same -- the container delivering the items are different. One is a list, the other an iterator (depending on the Python version...)

So the applicable differences between dict.items() and dict.iteritems() are the same as the applicable differences between a list and an iterator.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

With Nedit you can do several operations with selected column:

CTRL+LEFT-MOUSE -> Mark Rectangular Text-Area

MIDDLE-MOUSE pressed in area -> moving text area with pushing aside other text

CTRL+MIDDLE-MOUSE pressed in marked area -> moving text area with overriding aside text and deleting text from original position

CTRL+SHIFT+MIDDLE-MOUSE pressed in marked area -> copying text area with overriding aside text and keeping text from original position

How can I parse a CSV string with JavaScript, which contains comma in data?

Disclaimer

2014-12-01 Update: The answer below works only for one very specific format of CSV. As correctly pointed out by DG in the comments, this solution does not fit the RFC 4180 definition of CSV and it also does not fit Microsoft Excel format. This solution simply demonstrates how one can parse one (non-standard) CSV line of input which contains a mix of string types, where the strings may contain escaped quotes and commas.

A non-standard CSV solution

As austincheney correctly points out, you really need to parse the string from start to finish if you wish to properly handle quoted strings that may contain escaped characters. Also, the OP does not clearly define what a "CSV string" really is. First we must define what constitutes a valid CSV string and its individual values.

Given: "CSV String" Definition

For the purpose of this discussion, a "CSV string" consists of zero or more values, where multiple values are separated by a comma. Each value may consist of:

  1. A double quoted string (may contain unescaped single quotes).
  2. A single quoted string (may contain unescaped double quotes).
  3. A non-quoted string (may not contain quotes, commas or backslashes).
  4. An empty value. (An all whitespace value is considered empty.)

Rules/Notes:

  • Quoted values may contain commas.
  • Quoted values may contain escaped-anything, e.g. 'that\'s cool'.
  • Values containing quotes, commas, or backslashes must be quoted.
  • Values containing leading or trailing whitespace must be quoted.
  • The backslash is removed from all: \' in single quoted values.
  • The backslash is removed from all: \" in double quoted values.
  • Non-quoted strings are trimmed of any leading and trailing spaces.
  • The comma separator may have adjacent whitespace (which is ignored).

Find:

A JavaScript function which converts a valid CSV string (as defined above) into an array of string values.

Solution:

The regular expressions used by this solution are complex. And (IMHO) all non-trivial regular expressions should be presented in free-spacing mode with lots of comments and indentation. Unfortunately, JavaScript does not allow free-spacing mode. Thus, the regular expressions implemented by this solution are first presented in native regular expressions syntax (expressed using Python's handy r'''...''' raw-multi-line-string syntax).

First here is a regular expression which validates that a CVS string meets the above requirements:

Regular expression to validate a "CSV string":

re_valid = r"""
# Validate a CSV string having single, double or un-quoted values.
^                                   # Anchor to start of string.
\s*                                 # Allow whitespace before value.
(?:                                 # Group for value alternatives.
  '[^'\\]*(?:\\[\S\s][^'\\]*)*'     # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*"     # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*    # or Non-comma, non-quote stuff.
)                                   # End group of value alternatives.
\s*                                 # Allow whitespace after value.
(?:                                 # Zero or more additional values
  ,                                 # Values separated by a comma.
  \s*                               # Allow whitespace before value.
  (?:                               # Group for value alternatives.
    '[^'\\]*(?:\\[\S\s][^'\\]*)*'   # Either Single quoted string,
  | "[^"\\]*(?:\\[\S\s][^"\\]*)*"   # or Double quoted string,
  | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*  # or Non-comma, non-quote stuff.
  )                                 # End group of value alternatives.
  \s*                               # Allow whitespace after value.
)*                                  # Zero or more additional values
$                                   # Anchor to end of string.
"""

If a string matches the above regular expression, then that string is a valid CSV string (according to the rules previously stated) and may be parsed using the following regular expression. The following regular expression is then used to match one value from the CSV string. It is applied repeatedly until no more matches are found (and all values have been parsed).

Regular expression to parse one value from a valid CSV string:

re_value = r"""
# Match one value in valid CSV string.
(?!\s*$)                            # Don't match empty last value.
\s*                                 # Strip whitespace before value.
(?:                                 # Group for value alternatives.
  '([^'\\]*(?:\\[\S\s][^'\\]*)*)'   # Either $1: Single quoted string,
| "([^"\\]*(?:\\[\S\s][^"\\]*)*)"   # or $2: Double quoted string,
| ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)  # or $3: Non-comma, non-quote stuff.
)                                   # End group of value alternatives.
\s*                                 # Strip whitespace after value.
(?:,|$)                             # Field ends on comma or EOS.
"""

Note that there is one special case value that this regular expression does not match - the very last value when that value is empty. This special "empty last value" case is tested for and handled by the JavaScript function which follows.

JavaScript function to parse CSV string:

// Return array of string values, or NULL if CSV string not well formed.
function CSVtoArray(text) {
    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;

    // Return NULL if input string is not well formed CSV string.
    if (!re_valid.test(text)) return null;

    var a = []; // Initialize array to receive values.
    text.replace(re_value, // "Walk" the string using replace with callback.
        function(m0, m1, m2, m3) {

            // Remove backslash from \' in single quoted values.
            if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));

            // Remove backslash from \" in double quoted values.
            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
            else if (m3 !== undefined) a.push(m3);
            return ''; // Return empty string.
        });

    // Handle special case of empty last value.
    if (/,\s*$/.test(text)) a.push('');
    return a;
};

Example input and output:

In the following examples, curly braces are used to delimit the {result strings}. (This is to help visualize leading/trailing spaces and zero-length strings.)

// Test 1: Test string from original question.
var test = "'string, duppi, du', 23, lala";
var a = CSVtoArray(test);
/* Array has three elements:
    a[0] = {string, duppi, du}
    a[1] = {23}
    a[2] = {lala} */
// Test 2: Empty CSV string.
var test = "";
var a = CSVtoArray(test);
/* Array has zero elements: */
// Test 3: CSV string with two empty values.
var test = ",";
var a = CSVtoArray(test);
/* Array has two elements:
    a[0] = {}
    a[1] = {} */
// Test 4: Double quoted CSV string having single quoted values.
var test = "'one','two with escaped \' single quote', 'three, with, commas'";
var a = CSVtoArray(test);
/* Array has three elements:
    a[0] = {one}
    a[1] = {two with escaped ' single quote}
    a[2] = {three, with, commas} */
// Test 5: Single quoted CSV string having double quoted values.
var test = '"one","two with escaped \" double quote", "three, with, commas"';
var a = CSVtoArray(test);
/* Array has three elements:
    a[0] = {one}
    a[1] = {two with escaped " double quote}
    a[2] = {three, with, commas} */
// Test 6: CSV string with whitespace in and around empty and non-empty values.
var test = "   one  ,  'two'  ,  , ' four' ,, 'six ', ' seven ' ,  ";
var a = CSVtoArray(test);
/* Array has eight elements:
    a[0] = {one}
    a[1] = {two}
    a[2] = {}
    a[3] = { four}
    a[4] = {}
    a[5] = {six }
    a[6] = { seven }
    a[7] = {} */

Additional notes:

This solution requires that the CSV string be "valid". For example, unquoted values may not contain backslashes or quotes, e.g. the following CSV string is not valid:

var invalid1 = "one, that's me!, escaped \, comma"

This is not really a limitation because any sub-string may be represented as either a single or double quoted value. Note also that this solution represents only one possible definition for "comma-separated values".

Edit history

  • 2014-05-19: Added disclaimer.
  • 2014-12-01: Moved disclaimer to top.

How to make Visual Studio copy a DLL file to the output directory?

(This answer only applies to C# not C++, sorry I misread the original question)

I've got through DLL hell like this before. My final solution was to store the unmanaged DLLs in the managed DLL as binary resources, and extract them to a temporary folder when the program launches and delete them when it gets disposed.

This should be part of the .NET or pinvoke infrastructure, since it is so useful.... It makes your managed DLL easy to manage, both using Xcopy or as a Project reference in a bigger Visual Studio solution. Once you do this, you don't have to worry about post-build events.

UPDATE:

I posted code here in another answer https://stackoverflow.com/a/11038376/364818

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

Try setting an id (android:id="@+id/maps_dialog") for your mapView parent layout. Works for me.

Zoom to fit: PDF Embedded in HTML

just in case someone need it, in firefox for me it work like this

<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>

How to get label of select option with jQuery?

I found this helpful

$('select[name=users] option:selected').text()

When accessing the selector using the this keyword.

$(this).find('option:selected').text()

Python argparse command line flags without arguments

As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

How can I make robocopy silent in the command line except for progress?

If you want no output at all this is the most simple way:

robocopy src dest > nul

If you still need some information and only want to strip parts of the output, use the parameters from R.Koene's answer.

How to write text on a image in windows using python opencv2

I had a similar problem. I would suggest using the PIL library in python as it draws the text in any given font, compared to limited fonts in OpenCV. With PIL you can choose any font installed on your system.

from PIL import ImageFont, ImageDraw, Image
import numpy as np
import cv2

image = cv2.imread("lena.png")

# Convert to PIL Image
cv2_im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_im = Image.fromarray(cv2_im_rgb)

draw = ImageDraw.Draw(pil_im)

# Choose a font
font = ImageFont.truetype("Roboto-Regular.ttf", 50)

# Draw the text
draw.text((0, 0), "Your Text Here", font=font)

# Save the image
cv2_im_processed = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)
cv2.imwrite("result.png", cv2_im_processed)

result.png

How to debug Angular JavaScript Code

You can debug using browsers built in developer tools.

  1. open developer tools in browser and go to source tab.

  2. open the file do you want to debug using Ctrl+P and search file name

  3. add break point on a line ny clicking on left side of the code.

  4. refresh the page.

There are lot of plugin available for debugging you can refer for using chrome plugin Debug Angular Application using "Debugger for chrome" plugin

How to set python variables to true or false?

match_var = a==b

that should more than suffice

you cant use a - in a variable name as it thinks that is match (minus) var

match=1
var=2

print match-var  #prints -1

Determine the size of an InputStream

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

Drawing an SVG file on a HTML5 canvas

Sorry, i don't have enough reputation to comment on the @Matyas answer, but if the svg's image is also in base64, it will be drawed to the output.

Demo:

_x000D_
_x000D_
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.onload = function() {_x000D_
    // draw the image onto the canvas_x000D_
    canvas.getContext('2d').drawImage(img, 0, 0);_x000D_
}_x000D_
img.src = image64;
_x000D_
svg, img, canvas {_x000D_
  display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
  <image xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAEX0lEQVQ4jUWUyW6cVRCFv7r3/kO3u912nNgZgESAAgGBCJgFgxhW7FkgxAbxMLwBEmIRITbsQAgxCEUiSIBAYIY4g1EmYjuDp457+Lv7n+4tFjbwAHVOnVPnlLz75ht67OhhZg/M0p6d5tD9C8SNBBs5XBJhI4uNLC4SREA0UI9yJr2c4e6QO+v3WF27w+rmNrv9Pm7hxDyHFg5yYGEOYxytuRY2SYiSCIwgRgBQIxgjEAKuZWg6R9S0SCS4qKLZElY3HC5tp7QPtmlMN7HOETUTXBJjrEGsAfgPFECsQbBIbDGJZUYgGE8ugQyPm+o0STtTuGZMnKZEjRjjLIgAirEOEQEBDQFBEFFEBWLFtVJmpENRl6hUuFanTRAlbTeZarcx0R6YNZagAdD/t5N9+QgCYAw2jrAhpjM3zaSY4OJGTDrVwEYOYw2qioigoviq5MqF31m9fg1V5fCx+zn11CLNVnufRhBrsVFE1Ihpthu4KDYYwz5YQIxFBG7duMZnH31IqHL6wwnGCLFd4pez3/DaG2/x4GNPgBhEZG/GGlxkMVFkiNMYay3Inqxed4eP33uf7Y0uu90xWkGolFAru7sZn5w5w921m3u+su8vinEO02hEWLN/ANnL2rkvv2an2yd4SCKLM0JVBsCgAYZZzrnPP0eDRzXgfaCuPHXwuEYjRgmIBlQVVLl8/hKI4fRzz3L6uWe5+PMvnHz6aa4uX+D4yYe5vXaLH86eoyoLjLF476l9oKo9pi5HWONRX8E+YznOef7Vl1h86QWurlwjbc+QpikPPfoIcZLS39pmMikp8pzae6q6oqgriqrGqS+xeLScoMYSVJlfOMTl5RXW1+5w5fJVnFGWf1/mxEMnWPppiclkTLM5RdJoUBYFZVlQ5DnZMMMV167gixKLoXXsKGqnOHnqOJ/+/CfZ+XUiZ0jTmFv5mAvf/YjEliQ2vPD8Ir6qqEcZkzt38cMRo5WruFvfL9FqpyRxQhj0qLOax5I2S08+Tu/lFiGUGOPormxwuyfMnjrGrJa88uIixeYWl776lmrzNjmw8vcG8sU7ixpHMXFsCUVg9tABjEvRgzP82j7AhbyiX5Qcv2+Bvy7dYGZ1k7efeQB/Y4PBqGBtdYvb3SFzLcfqToZc/OB1zYeBSpUwLBlvjZidmWaSB1yaYOfn6LqI/r0hyU6P+cRSlhXjbEI2zvnt7y79oqQ3qeg4g6vKjCIXehtDmi6m0UnxVnCRkPUHVNt9qkLJxgXOCYNOg34v48raPaamU2o89/KKsQ9sTSpc0JK7NwdcX8s43Ek5cnSOLC/Z2R6Rj0ra0w2W1/t0xyWn51uk2Ri1QtSO6OU5d7OSi72cQeWxKG7p/Dp//JXTy6C1Pcbc6DMpPRtjTxChEznWhwVZUCKrjCrPoPDczHLmnLBdBgZlRRWUEBR3ZKrme5TlrTGlV440Y1IrXM9qQGi6mkG5V6uza7tUIeCDElTZ1L26elX+fcH/ACJBPYTJ4X8tAAAAAElFTkSuQmCC" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
   _x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
_x000D_
_x000D_

Update div with jQuery ajax response html

It's also possible to use jQuery's .load()

$('#submitform').click(function() {
  $('#showresults').load('getinfo.asp #showresults', {
    txtsearch: $('#appendedInputButton').val()
  }, function() {
    // alert('Load was performed.')
    // $('#showresults').slideDown('slow')
  });
});

unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

Export data from R to Excel

Another option is the openxlsx-package. It doesn't depend on and can read, edit and write Excel-files. From the description from the package:

openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java

Example usage:

library(openxlsx)

# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')

# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')

Besides these two basic functions, the openxlsx-package has a host of other functions for manipulating Excel-files.

For example, with the writeDataTable-function you can create formatted tables in an Excel-file.

Split text with '\r\n'

I think the problem is in your text file. It's probably already split into too many lines and when you read it, it "adds" additional \r and/or \n characters (as they exist in file). Check your what is read into text variable.

The code below (on a local variable with your text) works fine and splits into 2 lines:

string[] stringSeparators = new string[] { "\r\n" };
string text = "somet interesting text\nsome text that should be in the same line\r\nsome text should be in another line";
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);

A simple scenario using wait() and notify() in java

Have you taken a look at this Java Tutorial?

Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.

That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.

jQuery click event on radio button doesn't get fired

It fires. Check demo http://jsfiddle.net/yeyene/kbAk3/

$("#inline_content input[name='type']").click(function(){
    alert('You clicked radio!');
    if($('input:radio[name=type]:checked').val() == "walk_in"){
        alert($('input:radio[name=type]:checked').val());
        //$('#select-table > .roomNumber').attr('enabled',false);
    }
});

Is it possible to use an input value attribute as a CSS selector?

Sure, try:

input[value="United States"]{ color: red; }

jsFiddle example.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

My solution:

  1. remove all projects in current workspace
  2. import all again
  3. maven update project (Alt + F5) -> Select All and check Force Update of Snapshots/Releases
  4. maven build (Ctrl + B) until there is nothing to build

It worked for me after the second try.

How to convert a String to a Date using SimpleDateFormat?

String newstr = "08/16/2011";
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd hh:mm:ss z yyyy");
Calendar c = Calendar.getInstance();
c.setTime(format1.parse(newstr));
System.out.println(format.format(c.getTime()));

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

Resize image in PHP

I created an easy-to-use library for image resizing. It can be found here on Github.

An example of how to use the library:

// Include PHP Image Magician library
require_once('php_image_magician.php');

// Open JPG image
$magicianObj = new imageLib('racecar.jpg');

// Resize to best fit then crop (check out the other options)
$magicianObj -> resizeImage(100, 200, 'crop');

// Save resized image as a PNG (or jpg, bmp, etc)
$magicianObj -> saveImage('racecar_small.png');

Other features, should you need them, are:

  • Quick and easy resize - Resize to landscape, portrait, or auto
  • Easy crop
  • Add text
  • Quality adjustment
  • Watermarking
  • Shadows and reflections
  • Transparency support
  • Read EXIF metadata
  • Borders, Rounded corners, Rotation
  • Filters and effects
  • Image sharpening
  • Image type conversion
  • BMP support

View HTTP headers in Google Chrome?

You can find the headers option in the Network tab in Developer's console in Chrome:

  1. In Chrome press F12 to open Developer's console.
  2. Select the Network tab. This tab gives you the information about the requests fired from the browser.
  3. Select a request by clicking on the request name. There you can find the Header information for that request along with some other information like Preview, Response and Timing.

Also, in my version of Chrome (50.0.2661.102), it gives an extension named LIVE HTTP Headers which gives information about the request headers for all the HTTP requests.

update: added image

enter image description here

Singletons vs. Application Context in Android?

From the proverbial horse's mouth...

When developing your app, you may find it necessary to share data, context or services globally across your app. For example, if your app has session data, such as the currently logged-in user, you will likely want to expose this information. In Android, the pattern for solving this problem is to have your android.app.Application instance own all global data, and then treat your Application instance as a singleton with static accessors to the various data and services.

When writing an Android app, you're guaranteed to only have one instance of the android.app.Application class, and so it's safe (and recommended by Google Android team) to treat it as a singleton. That is, you can safely add a static getInstance() method to your Application implementation. Like so:

public class AndroidApplication extends Application {

    private static AndroidApplication sInstance;

    public static AndroidApplication getInstance(){
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }
}

SQL query to find record with ID not in another table

Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:

SELECT t1.ID, t1.Name 
FROM   Table1 t1
WHERE  NOT EXISTS (
    SELECT TOP 1 NULL
    FROM Table2 t2
    WHERE t1.ID = t2.ID
)

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

What is the syntax meaning of RAISERROR()

16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx

What is the default encoding of the JVM?

The default character set of the JVM is that of the system it's running on. There's no specific value for this and you shouldn't generally depend on the default encoding being any particular value.

It can be accessed at runtime via Charset.defaultCharset(), if that's any use to you, though really you should make a point of always specifying encoding explicitly when you can do so.

Bootstrap combining rows (rowspan)

You should use bootstrap column nesting.

See Bootstrap 3 or Bootstrap 4:

<div class="row">
    <div class="col-md-5">Span 5</div>
    <div class="col-md-3">Span 3<br />second line</div>
    <div class="col-md-2">
        <div class="row">
            <div class="col-md-12">Span 2</div>
        </div>
        <div class="row">
            <div class="col-md-12">Span 2</div>
        </div>
    </div>
    <div class="col-md-2">Span 2</div>
</div>
<div class="row">
    <div class="col-md-6">
        <div class="row">
            <div class="col-md-12">Span 6</div>
            <div class="col-md-12">Span 6</div>
        </div>
    </div>
    <div class="col-md-6">Span 6</div>
</div>

http://jsfiddle.net/DRanJ/125/

(In Fiddle screen, enlarge your test screen to see the result, because I'm using col-md-*, then responsive stacks columns)

Note: I am not sure that BS2 allows columns nesting, but in the answer of Paul Keister, the columns nesting is not used. You should use it and avoid to reinvente css while bootstrap do well.

The columns height are auto, if you add a second line (like I do in my example), column height adapt itself.

C pass int array pointer as parameter into a function

In new code assignment should be,

B[0] = 5

In func(B), you are just passing address of the pointer which is pointing to array B. You can do change in func() as B[i] or *(B + i). Where i is the index of the array.

In the first code the declaration says,

int *B[10]

says that B is an array of 10 elements, each element of which is a pointer to a int. That is, B[i] is a int pointer and *B[i] is the integer it points to the first integer of the i-th saved text line.

What is a "bundle" in an Android application

I have to add that bundles are used by activities to pass data to themselves in the future.

When the screen rotates, or when another activity is started, the method protected void onSaveInstanceState(Bundle outState) is invoked, and the activity is destroyed. Later, another instance of the activity is created, and public void onCreate(Bundle savedInstanceState) is called. When the first instance of activity is created, the bundle is null; and if the bundle is not null, the activity continues some business started by its predecessor.

Android automatically saves the text in text fields, but it does not save everything, and subtle bugs sometimes appear.

The most common anti-pattern, though, is assuming that onCreate() does just initialization. It is wrong, because it also must restore the state.

There is an option to disable this "re-create activity on rotation" behavior, but it will not prevent restart-related bugs, it will just make them more difficult to mention.

Note also that the only method whose call is guaranteed when the activity is going to be destroyed is onPause(). (See the activity life cycle graph in the docs.)

Remove unwanted parts from strings in a column

Try this using regular expression:

import re
data['result'] = data['result'].map(lambda x: re.sub('[-+A-Za-z]',x)

How to determine whether a year is a leap year?

As a one-liner function:

def is_leap_year(year):
    """Determine whether a year is a leap year."""

    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

It's similar to the Mark's answer, but short circuits at the first test (note the parenthesis).

Alternatively, you can use the standard library's calendar.isleap, which has exactly the same implementation:

from calendar import isleap
print(isleap(1900))

Count occurrences of a char in a string using Bash

awk works well if you your server has it

var="text,text,text,text" 
num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"

How do I access previous promise results in a .then() chain?

Mutable contextual state

The trivial (but inelegant and rather errorprone) solution is to just use higher-scope variables (to which all callbacks in the chain have access) and write result values to them when you get them:

function getExample() {
    var resultA;
    return promiseA(…).then(function(_resultA) {
        resultA = _resultA;
        // some processing
        return promiseB(…);
    }).then(function(resultB) {
        // more processing
        return // something using both resultA and resultB
    });
}

Instead of many variables one might also use an (initially empty) object, on which the results are stored as dynamically created properties.

This solution has several drawbacks:

  • Mutable state is ugly, and global variables are evil.
  • This pattern doesn't work across function boundaries, modularising the functions is harder as their declarations must not leave the shared scope
  • The scope of the variables does not prevent to access them before they are initialized. This is especially likely for complex promise constructions (loops, branching, excptions) where race conditions might happen. Passing state explicitly, a declarative design that promises encourage, forces a cleaner coding style which can prevent this.
  • One must choose the scope for those shared variables correctly. It needs to be local to the executed function to prevent race conditions between multiple parallel invocations, as would be the case if, for example, state was stored on an instance.

The Bluebird library encourages the use of an object that is passed along, using their bind() method to assign a context object to a promise chain. It will be accessible from each callback function via the otherwise unusable this keyword. While object properties are more prone to undetected typos than variables, the pattern is quite clever:

function getExample() {
    return promiseA(…)
    .bind({}) // Bluebird only!
    .then(function(resultA) {
        this.resultA = resultA;
        // some processing
        return promiseB(…);
    }).then(function(resultB) {
        // more processing
        return // something using both this.resultA and resultB
    }).bind(); // don't forget to unbind the object if you don't want the
               // caller to access it
}

This approach can be easily simulated in promise libraries that do not support .bind (although in a somewhat more verbose way and cannot be used in an expression):

function getExample() {
    var ctx = {};
    return promiseA(…)
    .then(function(resultA) {
        this.resultA = resultA;
        // some processing
        return promiseB(…);
    }.bind(ctx)).then(function(resultB) {
        // more processing
        return // something using both this.resultA and resultB
    }.bind(ctx));
}

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

Here's some code with a dummy geom_blank layer,

range_act <- range(range(results$act), range(results$pred))

d <- reshape2::melt(results, id.vars = "pred")

dummy <- data.frame(pred = range_act, value = range_act,
                    variable = "act", stringsAsFactors=FALSE)

ggplot(d, aes(x = pred, y = value)) +
  facet_wrap(~variable, scales = "free") +
  geom_point(size = 2.5) + 
  geom_blank(data=dummy) + 
  theme_bw()

enter image description here

Column/Vertical selection with Keyboard in SublimeText 3

This should do it:

  1. Ctrl+A - select all.
  2. Ctrl+Shift+L - split selection into lines.
  3. Then move all cursors with left/right, select with Shift+left/right. Move all cursors to start of line with Home.

Convert a string into an int

You can also use like :

NSInteger getVal = [self.string integerValue];

Duplicate headers received from server

This ones a little old but was high in the google ranking so I thought I would throw in the answer I found from Chrome, pdf display, Duplicate headers received from the server

Basically my problem also was that the filename contained commas. Do a replace on commas to remove them and you should be fine. My function to make a valid filename is below.

    public static string MakeValidFileName(string name)
    {
        string invalidChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
        string invalidReStr = string.Format(@"[{0}]+", invalidChars);
        string replace = Regex.Replace(name, invalidReStr, "_").Replace(";", "").Replace(",", "");
        return replace;
    }

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

Java using enum with switch statement

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

Is there a way to remove unused imports and declarations from Angular 2+?

There are already so many good answers on this thread! I am going to post this to help anybody trying to do this automatically! To automatically remove unused imports for the whole project this article was really helpful to me.

In the article the author explains it like this:

Make a stand alone tslint file that has the following in it:

{
  "extends": ["tslint-etc"],
  "rules": {
    "no-unused-declaration": true
  }
}

Then run the following command to fix the imports:

 tslint --config tslint-imports.json --fix --project .

Consider fixing any other errors it throws. (I did)

Then check the project works by building it:

ng build

or

ng build name_of_project --configuration=production 

End: If it builds correctly, you have successfully removed imports automatically!

NOTE: This only removes unnecessary imports. It does not provide the other features that VS Code does when using one of the commands previously mentioned.

Set cookies for cross origin requests

Note for Chrome Browser released in 2020.

A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.

So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.

More info https://www.chromium.org/updates/same-site.

Firefox and Edge developers also want to release this feature in the future.

Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8