Programs & Examples On #Vcdiff

How to display a JSON representation and not [Object Object] on the screen

There are 2 ways in which you can get the values:-

  1. Access the property of the object using dot notation (obj.property) .
  2. Access the property of the object by passing in key value for example obj["property"]

When should I use semicolons in SQL Server?

By default, SQL statements are terminated with semicolons. You use a semicolon to terminate statements unless you've (rarely) set a new statement terminator.

If you're sending just one statement, technically you can dispense with the statement terminator; in a script, as you're sending more than one statement, you need it.

In practice, always include the terminator even if you're just sending one statement to the database.

Edit: in response to those saying statement terminators are not required by [particular RDBMS], while that may be true, they're required by the ANSI SQL Standard. In all programming, if we can adhere to a Standard without loss of functionality, we should, because then neither our code or our habits are tied to one proprietary vendor.

With some C compilers, it's possible to have main return void, even though the Standard requires main to return int. But doing so makes our code, and ourselves, less portable.

The biggest difficulty in programming effectively isn't learning new things, it's unlearning bad habits. To the extent that we can avoid acquiring bad habits in the first place, it's a win for us, for our code, and for anyone reading or using our code.

button image as form input submit button?

Make the submit button the main image you are using. So the form tags would come first then submit button which is your only image so the image is your clickable image form. Then just make sure to put whatever you are passing before the submit button code.

Build Maven Project Without Running Unit Tests

mvn clean install -Dskiptests=true   

Now, the only difference from the answers above is that the "T" is in lower case.

What's the safest way to iterate through the keys of a Perl hash?

I always use method 2 as well. The only benefit of using each is if you're just reading (rather than re-assigning) the value of the hash entry, you're not constantly de-referencing the hash.

What is the proper way to re-throw an exception in C#?

I know this is an old question, but I'm going to answer it because I have to disagree with all the answers here.

Now, I'll agree that most of the time you either want to do a plain throw, to preserve as much information as possible about what went wrong, or you want to throw a new exception that may contain that as an inner-exception, or not, depending on how likely you are to want to know about the inner events that caused it.

There is an exception though. There are several cases where a method will call into another method and a condition that causes an exception in the inner call should be considered the same exception on the outer call.

One example is a specialised collection implemented by using another collection. Let's say it's a DistinctList<T> that wraps a List<T> but refuses duplicate items.

If someone called ICollection<T>.CopyTo on your collection class, it might just be a straight call to CopyTo on the inner collection (if say, all the custom logic only applied to adding to the collection, or setting it up). Now, the conditions in which that call would throw are exactly the same conditions in which your collection should throw to match the documentation of ICollection<T>.CopyTo.

Now, you could just not catch the execption at all, and let it pass through. Here though the user gets an exception from List<T> when they were calling something on a DistinctList<T>. Not the end of the world, but you may want to hide those implementation details.

Or you could do your own checking:

public CopyTo(T[] array, int arrayIndex)
{
  if(array == null)
    throw new ArgumentNullException("array");
  if(arrayIndex < 0)
    throw new ArgumentOutOfRangeException("arrayIndex", "Array Index must be zero or greater.");
  if(Count > array.Length + arrayIndex)
    throw new ArgumentException("Not enough room in array to copy elements starting at index given.");
  _innerList.CopyTo(array, arrayIndex);
}

That's not the worse code because it's boilerplate and we can probably just copy it from some other implementation of CopyTo where it wasn't a simple pass-through and we had to implement it ourselves. Still, it's needlessly repeating the exact same checks that are going to be done in _innerList.CopyTo(array, arrayIndex), so the only thing it has added to our code is 6 lines where there could be a bug.

We could check and wrap:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentNullException ane)
  {
    throw new ArgumentNullException("array", ane);
  }
  catch(ArgumentOutOfRangeException aore)
  {
    throw new ArgumentOutOfRangeException("Array Index must be zero or greater.", aore);
  }
  catch(ArgumentException ae)
  {
    throw new ArgumentException("Not enough room in array to copy elements starting at index given.", ae);
  }
}

In terms of new code added that could potentially be buggy, this is even worse. And we don't gain a thing from the inner exceptions. If we pass a null array to this method and receive an ArgumentNullException, we're not going to learn anything by examining the inner exception and learning that a call to _innerList.CopyTo was passed a null array and threw an ArgumentNullException.

Here, we can do everything we want with:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentException ae)
  {
    throw ae;
  }
}

Every one of the exceptions that we expect to have to throw if the user calls it with incorrect arguments, will correctly be thrown by that re-throw. If there's a bug in the logic used here, it's in one of two lines - either we were wrong in deciding this was a case where this approach works, or we were wrong in having ArgumentException as the exception type looked for. It's the only two bugs that the catch block can possibly have.

Now. I still agree that most of the time you either want a plain throw; or you want to construct your own exception to more directly match the problem from the perspective of the method in question. There are cases like the above where re-throwing like this makes more sense, and there are plenty of other cases. E.g. to take a very different example, if an ATOM file reader implemented with a FileStream and an XmlTextReader receives a file error or invalid XML, then it will perhaps want to throw exactly the same exception it received from those classes, but it should look to the caller that it is AtomFileReader that is throwing a FileNotFoundException or XmlException, so they might be candidates for similarly re-throwing.

Edit:

We can also combine the two:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentException ae)
  {
    throw ae;
  }
  catch(Exception ex)
  {
    //we weren't expecting this, there must be a bug in our code that put
    //us into an invalid state, and subsequently let this exception happen.
    LogException(ex);
    throw;
  }
}

Get only records created today in laravel

with carbon:

return $model->where('created_at', '>=', \Carbon::today()->toDateString());

without carbon:

return $model->where('created_at', '>=', date('Y-m-d').' 00:00:00');

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

Default instance name of SQL Server Express

in my case the right server name was the name of my computer. for example John-PC, or somth

Doctrine findBy 'does not equal'

To give a little more flexibility I would add the next function to my repository:

public function findByNot($field, $value)
{
    $qb = $this->createQueryBuilder('a');
    $qb->where($qb->expr()->not($qb->expr()->eq('a.'.$field, '?1')));
    $qb->setParameter(1, $value);

    return $qb->getQuery()
        ->getResult();
}

Then, I could call it in my controller like this:

$this->getDoctrine()->getRepository('MyBundle:Image')->findByNot('id', 1);

Creating a batch file, for simple javac and java command execution

Am i understanding your question only? You need .bat file to compile and execute java class files?

if its a .bat file. you can just double click.

and in your .bat file, you just need to javac Main.java ((make sure your bat has the path to ur Main.java) java Main

If you want to echo compilation warnings/statements, that would need something else. But since, you want that to be automated, maybe you eventually don't need that.

How do I select a sibling element using jQuery?

Since $(this) refers to .countdown you can use $(this).next() or $(this).next('button') more specifically.

Does C# have a String Tokenizer like Java's?

_words = new List<string>(YourText.ToLower().Trim('\n', '\r').Split(' ').
            Select(x => new string(x.Where(Char.IsLetter).ToArray()))); 

Or

_words = new List<string>(YourText.Trim('\n', '\r').Split(' ').
            Select(x => new string(x.Where(Char.IsLetterOrDigit).ToArray()))); 

What does <T> denote in C#

This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx

An example of this is to make a collection of items of a specific type.

class MyArray<T>
{
    T[] array = new T[10];

    public T GetItem(int index)
    {
        return array[index];
    }
}

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

List of IP addresses/hostnames from local network in Python

Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).

https://github.com/vivkv/scanip

How can I check if char* variable points to empty string?

An empty string has one single null byte. So test if (s[0] == (char)0)

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

In my case, it seems ng is not registered into my environment path. I have been using npm run command to run the ng commands. Be aware in order to pass arguments you need an extra -- as per the npm run specification.

Example:

npm run ng g c components/scheduling **--** --module=app

Or:

npm run ng g c components/scheduling **--** --skip-import

How do I flush the cin buffer?

I have found two solutions to this.

The first, and simplest, is to use std::getline() for example:

std::getline(std::cin, yourString);

... that will discard the input stream when it gets to a new-line. Read more about this function here.

Another option that directly discards the stream is this...

#include <limits>
// Possibly some other code here
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

Good luck!

How to make child process die after parent exits?

As other people have pointed out, relying on the parent pid to become 1 when the parent exits is non-portable. Instead of waiting for a specific parent process ID, just wait for the ID to change:

pit_t pid = getpid();
switch (fork())
{
    case -1:
    {
        abort(); /* or whatever... */
    }
    default:
    {
        /* parent */
        exit(0);
    }
    case 0:
    {
        /* child */
        /* ... */
    }
}

/* Wait for parent to exit */
while (getppid() != pid)
    ;

Add a micro-sleep as desired if you don't want to poll at full speed.

This option seems simpler to me than using a pipe or relying on signals.

Paste in insert mode?

While in insert mode, you can use Ctrl-R {register}, where register can be:

  • + for the clipboard,
  • * for the X clipboard (last selected text in X),
  • " for the unnamed register (last delete or yank in Vim),
  • or a number of others (see :h registers).

Ctrl-R {register} inserts the text as if it were typed.

Ctrl-R Ctrl-O {register} inserts the text with the original indentation.

Ctrl-R Ctrl-P {register} inserts the text and auto-indents it.

Ctrl-O can be used to run any normal mode command before returning to insert mode, so
Ctrl-O "+p can also be used, for example.

For more information, view the documentation with :h i_ctrl-r

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

using wildcards in LDAP search filters/queries

This should work, at least according to the Search Filter Syntax article on MSDN network.

The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.

You may also try separating the filter into two parts:

(|(displayName=*searchstring)(displayName=searchstring*))

Remove trailing spaces automatically or with a shortcut

You can enable whitespace trimming at file save time from settings:

  1. Open Visual Studio Code User Settings (menu FilePreferencesSettingsUser Settings tab).
  2. Click the enter image description here icon in the top-right part of the window. This will open a document.
  3. Add a new "files.trimTrailingWhitespace": true setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.
  4. Save the User Settings file.

We also added a new command to trigger this manually (Trim Trailing Whitespace from the command palette).

Programmatically Hide/Show Android Soft Keyboard

UPDATE 2

@Override
    protected void onResume() {
        super.onResume();
        mUserNameEdit.requestFocus();

        mUserNameEdit.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                InputMethodManager keyboard = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.showSoftInput(mUserNameEdit, 0);
            }
        },200); //use 300 to make it run when coming back from lock screen
    }

I tried very hard and found out a solution ... whenever a new activity starts then keyboard cant open but we can use Runnable in onResume and it is working fine so please try this code and check...

UPDATE 1

add this line in your AppLogin.java

mUserNameEdit.requestFocus();

and this line in your AppList.java

listview.requestFocus()'

after this check your application if it is not working then add this line in your AndroidManifest.xml file

<activity android:name=".AppLogin" android:configChanges="keyboardHidden|orientation"></activity>
<activity android:name=".AppList" android:configChanges="keyboard|orientation"></activity>

ORIGINAL ANSWER

 InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);

for hide keyboard

 imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); 

for show keyboard

 imm.showSoftInput(ed, 0);

for focus on EditText

 ed.requestFocus();

where ed is EditText

HTML display result in text (input) field?

innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.

For your case you want to set the value of an input element. So you should use the value attribute.

Change innerHTML to value

document.getElementById('add').value = sum;

Selenium wait until document is ready

For the people who need to wait for a specific element to show up. (used c#)

public static void WaitForElement(IWebDriver driver, By element)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
    wait.Until(ExpectedConditions.ElementIsVisible(element));
}

Then if you want to wait for example if an class="error-message" exists in the DOM you simply do:

WaitForElement(driver, By.ClassName("error-message"));

For id, it will then be

WaitForElement(driver, By.Id("yourid"));

ApiNotActivatedMapError for simple html page using google-places-api

I had the same error. To fix the error:

  1. Open the console menu Gallery Menu and select API Manager.
  2. On the left, click Credentials and then click New Credentials.
  3. Click Create Credentials.
  4. Click API KEY.
  5. Click Navigator Key (there are more options; It depends on when consumed).

You must use this new API Navigator Key, generated by the system.

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

I was having some trouble with this so let me be very explicit so noobs like me can understand.

Lets say that we have a data file or something like that

# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import sympy as sym

"""
Generate some data, let's imagine that you already have this. 
"""
x = np.linspace(0, 3, 50)
y = np.exp(x)

"""
Plot your data
"""
plt.plot(x, y, 'ro',label="Original Data")

"""
brutal force to avoid errors
"""    
x = np.array(x, dtype=float) #transform your data in a numpy array of floats 
y = np.array(y, dtype=float) #so the curve_fit can work

"""
create a function to fit with your data. a, b, c and d are the coefficients
that curve_fit will calculate for you. 
In this part you need to guess and/or use mathematical knowledge to find
a function that resembles your data
"""
def func(x, a, b, c, d):
    return a*x**3 + b*x**2 +c*x + d

"""
make the curve_fit
"""
popt, pcov = curve_fit(func, x, y)

"""
The result is:
popt[0] = a , popt[1] = b, popt[2] = c and popt[3] = d of the function,
so f(x) = popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3].
"""
print "a = %s , b = %s, c = %s, d = %s" % (popt[0], popt[1], popt[2], popt[3])

"""
Use sympy to generate the latex sintax of the function
"""
xs = sym.Symbol('\lambda')    
tex = sym.latex(func(xs,*popt)).replace('$', '')
plt.title(r'$f(\lambda)= %s$' %(tex),fontsize=16)

"""
Print the coefficients and plot the funcion.
"""

plt.plot(x, func(x, *popt), label="Fitted Curve") #same as line above \/
#plt.plot(x, popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3], label="Fitted Curve") 

plt.legend(loc='upper left')
plt.show()

the result is: a = 0.849195983017 , b = -1.18101681765, c = 2.24061176543, d = 0.816643894816

Raw data and fitted function

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.

So try to download other versions of PostgreSQL and get all the components

Create directories using make file

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

outDir/someTarget: Makefile outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

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

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

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

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

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

outDir:
    mkdir -p outDir

This correctly yields:

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

TL;DR:

Write a rule to create the directory:

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

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

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

Division of integers in Java

As your output results a double you should cast either completed variable or total variable or both to double while dividing.

So, the correct implmentation will be:

System.out.println((double)completed/total);

How do you set a JavaScript onclick event to a class with css

You could do it with jQuery.

$('.myClass').click(function() {
  alert('hohoho');
});

Pretty Printing JSON with React

The 'react-json-view' provides solution rendering json string.

import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

How to pull remote branch from somebody else's repo

GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:

  1. Scroll to the bottom of the PR to see the Merge or Squash and merge button
  2. Click the link on the right: view command line instructions
  3. Press the Copy icon to the right of Step 1
  4. Paste the commands in your terminal

How to encrypt String in Java

Here's my implementation from meta64.com as a Spring Singleton. If you want to create a ciper instance for each call that would work also, and then you could remove the 'synchronized' calls, but beware 'cipher' is not thread-safe.

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton")
public class Encryptor {

    @Value("${aeskey}")
    private String keyStr;

    private Key aesKey = null;
    private Cipher cipher = null;

    synchronized private void init() throws Exception {
        if (keyStr == null || keyStr.length() != 16) {
            throw new Exception("bad aes key configured");
        }
        if (aesKey == null) {
            aesKey = new SecretKeySpec(keyStr.getBytes(), "AES");
            cipher = Cipher.getInstance("AES");
        }
    }

    synchronized public String encrypt(String text) throws Exception {
        init();
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        return toHexString(cipher.doFinal(text.getBytes()));
    }

    synchronized public String decrypt(String text) throws Exception {
        init();
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        return new String(cipher.doFinal(toByteArray(text)));
    }

    public static String toHexString(byte[] array) {
        return DatatypeConverter.printHexBinary(array);
    }

    public static byte[] toByteArray(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }

    /*
     * DO NOT DELETE
     * 
     * Use this commented code if you don't like using DatatypeConverter dependency
     */
    // public static String toHexStringOld(byte[] bytes) {
    // StringBuilder sb = new StringBuilder();
    // for (byte b : bytes) {
    // sb.append(String.format("%02X", b));
    // }
    // return sb.toString();
    // }
    //
    // public static byte[] toByteArrayOld(String s) {
    // int len = s.length();
    // byte[] data = new byte[len / 2];
    // for (int i = 0; i < len; i += 2) {
    // data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i +
    // 1), 16));
    // }
    // return data;
    // }
}

How to add Action bar options menu in Android Fragments

I am late for the answer but I think this is another solution which is not mentioned here so posting.

Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.

filter.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >


    <item
        android:id="@+id/action_filter"
        android:title="@string/filter"
        android:orderInCategory="10"
        android:icon="@drawable/filter"
        app:showAsAction="ifRoom" />


</menu>

Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

Step 3: Now add the method onCreateOptionsMenu which will be override as:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.filter, menu);  // Use filter.xml from step 1
    }

Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_filter){
            //Do whatever you want to do 
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

How to execute a command in a remote computer?

I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

execcmd \\yourremoteserver <your command here>

Doesn't get any simpler than this :)

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

Center image in div horizontally

I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/

PHP json_encode json_decode UTF-8

If your source-file is already utf8 then drop the utf8_* functions. php5 is storing strings as array of byte.

you should add a meta tag for encoding within the html AND you should add an http header which sets the transferencoding to utf-8.

<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

and in php

<?php
header('Content-Type: text/html; charset=utf-8');

How to calculate the SVG Path for an arc (of a circle)

Note for the answer-seekers (who I also was) - if using arc is not obligatory, a far simpler solution to draw a part-circle is to use stroke-dasharray of SVG <circle>.

Divide dash array into two elements, and scale their range to the desired angle. Starting angle can be adjusted using stroke-dashoffset.

Not a single cosine in sight.

Full example with explanations: https://codepen.io/mjurczyk/pen/wvBKOvP

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

is there a tool to create SVG paths from an SVG file?

Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.

  1. First download Gimp: https://www.gimp.org/downloads/
  2. Export your SVG as a .svg file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it up
  3. Import the SVG file into Gimp with File -> Open, and the following (or similar) dialog should show up:

Gimp SVG Open Dialog

Check both the Import Paths and Merge imported paths options

  1. Then go to Windows->Dockable Dialogues->Paths
  2. Right-click on the single path which says Imported Path and you should see the following dialog:

enter image description here

  1. Click Export Path... and save this text file to a location of your choice
  2. Locate and open up this file with a text editor of your choice e.g Notepad, TextEdit
  3. Copy the text within the <path d="copy this text here" />
  4. Since Gimp formats the text with lots of spaces, you may need to re-format it, by removing some of the spaces to paste it into your HTML in a single line

How do I make a comment in a Dockerfile?

As others have mentioned, comments are referenced with a # and are documented here. However, unlike some languages, the # must be at the beginning of the line. If they occur part way through the line, they are interpreted as an argument and may result in unexpected behavior.

# This is a comment

COPY test_dir target_dir # This is not a comment, it is an argument to COPY

RUN echo hello world # This is an argument to RUN but the shell may ignore it

It should also be noted that parser directives have recently been added to the Dockerfile which have the same syntax as a comment. They need to appear at the top of the file, before any other comments or commands. Originally, this directive was added for changing the escape character to support Windows:

# escape=`

FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\

The first line, while it appears to be a comment, is a parser directive to change the escape character to a backtick so that the COPY and RUN commands can use the backslash in the path. A parser directive is also used with BuildKit to change the frontend parser with a syntax line. See the experimental syntax for more details on how this is being used in practice.

With a multi-line command, the commented lines are ignored, but you need to comment out every line individually:

$ cat Dockerfile
FROM busybox:latest
RUN echo first command \
# && echo second command disabled \
 && echo third command

$ docker build .
Sending build context to Docker daemon  23.04kB
Step 1/2 : FROM busybox:latest
 ---> 59788edf1f3e
Step 2/2 : RUN echo first command  && echo third command
 ---> Running in b1177e7b563d
first command
third command
Removing intermediate container b1177e7b563d
 ---> 5442cfe321ac
Successfully built 5442cfe321ac

Change the name of a key in dictionary

if you want to change all the keys:

d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}

In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}

if you want to change single key: You can go with any of the above suggestion.

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

In a Git repository, how to properly rename a directory?

From Web Application I think you can't, but you can rename all the folders in Git Client, it will move your files in the new renamed folders, than commit and push to remote repository.

I had a very similar issue: I had to rename different folders from uppercase to lowercase (like Abc -> abc), I've renamed all the folders with a dummy name (like 'abc___') and than committed to remote repository, after that I renamed all the folders to the original name with the lowercase (like abc) and it took them!

What is the IntelliJ shortcut key to create a javadoc comment?

You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else. By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

How can I initialize a MySQL database with schema in a Docker container?

I've tried Greg's answer with zero success, I must have done something wrong since my database had no data after all the steps: I was using MariaDB's latest image, just in case.

Then I decided to read the entrypoint for the official MariaDB image, and used that to generate a simple docker-compose file:

database:
  image: mariadb
  ports:
     - 3306:3306
  expose:
     - 3306
  volumes:
     - ./docker/mariadb/data:/var/lib/mysql:rw
     - ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
  environment:
     MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

Now I'm able to persist my data AND generate a database with my own schema!

Oracle SQL Query for listing all Schemas in a DB

Most likely, you want

SELECT username
  FROM dba_users

That will show you all the users in the system (and thus all the potential schemas). If your definition of "schema" allows for a schema to be empty, that's what you want. However, there can be a semantic distinction where people only want to call something a schema if it actually owns at least one object so that the hundreds of user accounts that will never own any objects are excluded. In that case

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )

Assuming that whoever created the schemas was sensible about assigning default tablespaces and assuming that you are not interested in schemas that Oracle has delivered, you can filter out those schemas by adding predicates on the default_tablespace, i.e.

SELECT username
  FROM dba_users
 WHERE default_tablespace not in ('SYSTEM','SYSAUX')

or

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )
   AND default_tablespace not in ('SYSTEM','SYSAUX')

It is not terribly uncommon to come across a system where someone has incorrectly given a non-system user a default_tablespace of SYSTEM, though, so be certain that the assumptions hold before trying to filter out the Oracle-delivered schemas this way.

Replace a value if null or undefined in JavaScript

Here’s the JavaScript equivalent:

var i = null;
var j = i || 10; //j is now 10

Note that the logical operator || does not return a boolean value but the first value that can be converted to true.

Additionally use an array of objects instead of one single object:

var options = {
    filters: [
        {
            name: 'firstName',
            value: 'abc'
        }
    ]
};
var filter  = options.filters[0] || '';  // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || '';  // is ''

That can be accessed by index.

sudo echo "something" >> /etc/privilegedFile doesn't work

sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

I had the same problem but got round it by setting AutoPostBack to true and in an update panel set the trigger to the dropdownlist control id and event name to SelectedIndexChanged e.g.

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" enableViewState="true">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddl1" EventName="SelectedIndexChanged" />
        </Triggers>
        <ContentTemplate>
            <asp:DropDownList ID="ddl1" runat="server" ClientIDMode="Static" OnSelectedIndexChanged="ddl1_SelectedIndexChanged" AutoPostBack="true" ViewStateMode="Enabled">
                <asp:ListItem Text="--Please select a item--" Value="0" />
            </asp:DropDownList>
        </ContentTemplate>
    </asp:UpdatePanel>

How to check if an item is selected from an HTML drop down list?

Select select = new Select(_element);
List<WebElement> selectedOptions = select.getAllSelectedOptions();

if(selectedOptions.size() > 0){
    return true;
}else{
    return false;
}

Comparing floating point number to zero

notice, that code is:

std::abs((x - y)/x) <= epsilon

you are requiring that the "relative error" on the var is <= epsilon, not that the absolute difference is

How can you create multiple cursors in Visual Studio Code

There is no binding for exactly what you want.

The only thing that comes close is Ctrl+F2 which will select all of them at once.

You can bind it to Ctrl+D doing the following:

  • Click on File > Preferences > Keyboard Shortcuts
    You should see a pane full of the current bindings and on the right a list of custom bindings
  • In the current bindings, search for Ctrl+F2 and copy that whole line and paste it into the right pane.
  • You might have to remove the comma at the end and then change Ctrl+F2 to Ctrl+D and then save the file.

It should look something like this:

// Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+d",               "command": "editor.action.changeAll",
                                    "when": "editorTextFocus" }
]

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Bootstrap 3 Flush footer to bottom. not fixed

For Bootstrap:

<div class="navbar-fixed-bottom row-fluid">
  <div class="navbar-inner">
    <div class="container">
      Text
    </div>
  </div>
</div>

How to prevent page scrolling when scrolling a DIV element?

If you don't care about the compatibility with older IE versions (< 8), you could make a custom jQuery plugin and then call it on the overflowing element.

This solution has an advantage over the one Šime Vidas proposed, as it doesn't overwrite the scrolling behavior - it just blocks it when appropriate.

$.fn.isolatedScroll = function() {
    this.bind('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
            bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
    });
    return this;
};

$('.scrollable').isolatedScroll();

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

even i faced the same problem. The possibility of this could be usage of same port by two or more application/process. In Some cases you can use different port number which will avoid this problem, but in other case you have to manually kill the process with help of command prompt.

The command to kill is, In your command prompt first enter this command

C:\Users\A611003>tasklist

After this you can able to see list of process running with process ID. For example, enter image description here

From this select the process you want to stop, for example consider the process id 304 is your server and you have problem with that. Then enter this command.

C:\Users\A611003>Taskkill /PID 304 /F

This will kill that process now you can clean, publish your server and start it.

Note: If you fail to add /F in the above command it does nothing. It is the force kill. you can also try/? for list of available options.

VBScript How can I Format Date?

Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.

Thus:

Function timeStamp()
    Dim t 
    t = Now
    timeStamp = Year(t) & "-" & _
    Right("0" & Month(t),2)  & "-" & _
    Right("0" & Day(t),2)  & "_" & _  
    Right("0" & Hour(t),2) & _
    Right("0" & Minute(t),2) '    '& _    Right("0" & Second(t),2) 
End Function

How to add minutes to current time in swift

Two approaches:

  1. Use Calendar and date(byAdding:to:wrappingComponents:). E.g., in Swift 3 and later:

    let calendar = Calendar.current
    let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
    
  2. Just use + operator (see +(_:_:)) to add a TimeInterval (i.e. a certain number of seconds). E.g. to add five minutes, you can:

    let date = startDate + 5 * 60
    

    (Note, the order is specific here: The date on the left side of the + and the seconds on the right side.)

    You can also use addingTimeInterval, if you’d prefer:

    let date = startDate.addingTimeInterval(5 * 60)
    

Bottom line, +/addingTimeInterval is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval doesn’t.


For Swift 2 renditions, see the previous revision of this answer.

React.js: Wrapping one component into another

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

How to merge two json string in Python?

What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:

d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \ 
               jsonStringB["timestamp_in_ms"]

Merging method is obviously up to you.

How do I make entire div a link?

Using

<a href="foo.html"><div class="xyz"></div></a>

works in browsers, even though it violates current HTML specifications. It is permitted according to HTML5 drafts.

When you say that it does not work, you should explain exactly what you did (including jsfiddle code is a good idea), what you expected, and how the behavior different from your expectations.

It is unclear what you mean by “all the content in that div is in the css”, but I suppose it means that the content is really empty in HTML markup and you have CSS like

.xyz:before { content: "Hello world"; }

The entire block is then clickable, with the content text looking like link text there. Isn’t this what you expected?

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

System.IO.IOException: file used by another process

The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.

How to see the changes in a Git commit?

For checking complete changes:

  git diff <commit_Id_1> <commit_Id_2>

For checking only the changed/added/deleted files:

  git diff <commit_Id_1> <commit_Id_2> --name-only

NOTE: For checking diff without commit in between, you don't need to put the commit ids.

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

Windows 10:

Android Studio -> File -> Other Settings -> Default Project Structure... -> JDK location:

copy string shown, such as:

C:\Program Files\Android\Android Studio\jre

In file locator directory window, right-click on "This PC" ->

Properties -> Advanced System Settings -> Environment Variables... -> System Variables

click on the New... button under System Variables, then type and paste respectively:

.......Variable name: JAVA_HOME

.......Variable value: C:\Program Files\Android\Android Studio\jre

and hit OK buttons to close out.

Some installations may require JRE_HOME to be set as well, the same way.

To check, open a NEW black console window, then type echo %JAVA_HOME% . You should get back the full path you typed into the system variable. Windows 10 seems to support spaces in the filename paths for system variables very well, and does not seem to need ~tilde eliding.

How can I make a SQL temp table with primary key and auto-incrementing field?

you dont insert into identity fields. You need to specify the field names and use the Values clause

insert into #tmp (AssignedTo, field2, field3) values (value, value, value)

If you use do a insert into... select field field field it will insert the first field into that identity field and will bomb

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

in this scenario:

DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));

aren't you missing the column you want to compare to? example:

DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));    

I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.

Server Error in '/' Application. ASP.NET

Looks like this is a very generic message from iis. in my case we enabled integrated security on web config but forgot to change IIS app pool identity. Things to check -

  • go to event viewer on your server and check exact message.
  • -make sure your app pool and web config using same security(E.g Windows,integrated)

Note: this may not help every time but this might be one of the reason for above error message.

Vertical rulers in Visual Studio Code

In v1.43 is the ability to separately color the vertical rulers.

See issue Support multiple rulers with different colors - (in settings.json):

"editor.rulers": [
  {
    "column": 80,
    "color": "#ff00FF"
  },
  100,  // <- a ruler in the default color or as customized (with "editorRuler.foreground") at column 100
  {
    "column": 120,
    "color": "#ff0000"
  },
], 

Check if any type of files exist in a directory using BATCH script

You can use this

@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
   echo Folder is NON empty
   goto :EOF
)
echo Folder is empty or does not exist

Taken from here.

That should do what you need.

Does not contain a static 'main' method suitable for an entry point

hey i got same error and the solution to this error is just write Capital M instead of small m.. eg:- static void Main() I hope it helps..

tqdm in Jupyter Notebook prints new progress bars repeatedly

Try using tqdm.notebook.tqdm instead of tqdm, as outlined here.

This could be as simple as changing your import to:

from tqdm.notebook import tqdm

Good luck!

EDIT: After testing, it seems that tqdm actually works fine in 'text mode' in Jupyter notebook. It's hard to tell because you haven't provided a minimal example, but it looks like your problem is caused by a print statement in each iteration. The print statement is outputting a number (~0.89) in between each status bar update, which is messing up the output. Try removing the print statement.

Correct way to import lodash

Import specific methods inside of curly brackets

import { map, tail, times, uniq } from 'lodash';

Pros:

  • Only one import line(for a decent amount of functions)
  • More readable usage: map() instead of _.map() later in the javascript code.

Cons:

  • Every time we want to use a new function or stop using another - it needs to be maintained and managed

Copied from:The Correct Way to Import Lodash Libraries - A Benchmark article written by Alexander Chertkov.

What is the difference between compare() and compareTo()?

Comparable interface contains a method called compareTo(obj) which takes only one argument and it compares itself with another instance or objects of the same class.

Comparator interface contains a method called compare(obj1,obj2) which takes two arguments and it compares the value of two objects from the same or different classes.

How to redirect in a servlet filter?

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

Get all child views inside LinearLayout at once

Get all views of a view plus its children recursively in Kotlin:

private fun View.getAllViews(): List<View> {
    if (this !is ViewGroup || childCount == 0) return listOf(this)

    return children
            .toList()
            .flatMap { it.getAllViews() }
            .plus(this as View)
}

sql like operator to get the numbers only

Try something like this - it works for the cases you have mentioned.

select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'

How to display a jpg file in Python?

Don't forget to include

import Image

In order to show it use this :

Image.open('pathToFile').show()

How to pass a variable to the SelectCommand of a SqlDataSource?

Try this instead, remove the SelectCommand property and SelectParameters:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">

Then in the code behind do this:

SqlDataSource1.SelectParameters.Add("userId", userId.ToString());

SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"

While this worked for me, the following code also works:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
    SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>


SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

How to use 'cp' command to exclude a specific directory?

ls -I "filename1" -I "filename2" | xargs cp -rf -t destdir 

The first part ls all the files but hidden specific files with flag -I. The output of ls is used as standard input for the second part. xargs build and execute command cp -rf -t destdir from standard input. the flag -r means copy directories recursively, -f means copy files forcibly which will overwrite the files in the destdir, -t specify the destination directory copy to.

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

AttributeError: Module Pip has no attribute 'main'

This helps me, https://pip.pypa.io/en/stable/installing/

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

If you are using python3 and not set it default. do this,

python3 get-pip.py

It works for me.

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

clientHeight/clientWidth returning different values on different browsers

The body element takes the available width, which is usually your browser viewport. As such, it will be different dimensions cross browser due to browser chrome borders, scrollbars, vertical space being take up by menus and whatnot...

The fact that the heights also vary, also tells me you set the body/html height to 100% through css since the height is usually dependant on elements inside the body..

Unless you set the width of the body element to a fixed value through css or it's style property, it's dimensions will as a rule, always vary cross browsers/versions and perhaps even depending on plugins you installed for the browser. Constant values in such a case is more an exception to the rule...

When you invoke .clientWidth on other elements that do not take the automatic width of the browser viewport, it will always return the elements 'width' + 'padding'. So a div with width 200 and a padding of 20 will have clientWidth = 240 (20 padding left and right).

The main reason however, why one would invoke clientWidth, is exactly due to possible expected discrepancies in results. If you know you will get a constant width and the value is known, then invoking clientWidth is redundant...

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

Using both Python 2.x and Python 3.x in IPython Notebook

A solution is available that allows me to keep my MacPorts installation by configuring the Ipython kernelspec.

Requirements:

  • MacPorts is installed in the usual /opt directory
  • python 2.7 is installed through macports
  • python 3.4 is installed through macports
  • Ipython is installed for python 2.7
  • Ipython is installed for python 3.4

For python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

For python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

Now you can open an Ipython notebook and then choose a python 2.x or a python 3.x notebook.

Choose your python!

How to break out of jQuery each Loop

I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.

$('.groupName').each(function() {
    if($(this).text() == groupname){
        alert('This group already exists');
        breakOut = true;
        return false;
    }
});
if(breakOut) {
    breakOut = false;
    return false;
} 

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

Animation CSS3: display + opacity

I changed a bit but the result is beautiful.

.child {
    width: 0px;
    height: 0px;
    opacity: 0;
}

.parent:hover child {
    width: 150px;
    height: 300px;
    opacity: .9;
}

Thank you to everyone.

How can I get just the first row in a result set AFTER ordering?

In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!

CSS: background image on background color

really interesting problem, haven't seen it yet. this code works fine for me. tested it in chrome and IE9

<html>
<head>
<style>
body{
    background-image: url('img.jpg');
    background-color: #6DB3F2;
}
</style>
</head>
<body>
</body>
</html>

How to retrieve images from MySQL database and display in an html tag

I have added slashes before inserting into database so on the time of fetching i removed slashes again stripslashes() and it works for me. I am sharing the code which works for me.

How i inserted into mysql db (blob type)

$db = mysqli_connect("localhost","root","","dName"); 
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$query = "INSERT INTO student_img (id,image) VALUES('','$image')";  
$query = mysqli_query($db, $query);

Now to access the image

$sqlQuery = "SELECT * FROM student_img WHERE id = $stid";
$rs = $db->query($sqlQuery);
$result=mysqli_fetch_array($rs);
echo '<img src="data:image/jpeg;base64,'.base64_encode( stripslashes($result['image']) ).'"/>';

Hope it will help someone

Thanks.

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

How to run SUDO command in WinSCP to transfer files from Windows to linux

I know this is old, but it is actually very possible.

  • Go to your WinSCP profile (Session > Sites > Site Manager)

  • Click on Edit > Advanced... > Environment > SFTP

  • Insert sudo su -c /usr/lib/sftp-server in "SFTP Server" (note this path might be different in your system)

  • Save and connect

Source

AWS Ubuntu 18.04: enter image description here

Custom "confirm" dialog in JavaScript?

Faced with the same problem, I was able to solve it using only vanilla JS, but in an ugly way. To be more accurate, in a non-procedural way. I removed all my function parameters and return values and replaced them with global variables, and now the functions only serve as containers for lines of code - they're no longer logical units.

In my case, I also had the added complication of needing many confirmations (as a parser works through a text). My solution was to put everything up to the first confirmation in a JS function that ends by painting my custom popup on the screen, and then terminating.

Then the buttons in my popup call another function that uses the answer and then continues working (parsing) as usual up to the next confirmation, when it again paints the screen and then terminates. This second function is called as often as needed.

Both functions also recognize when the work is done - they do a little cleanup and then finish for good. The result is that I have complete control of the popups; the price I paid is in elegance.

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

Found elsewhere on the web

EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
-- EXEC sp_MSForEachTable 'DELETE FROM ?' -- Uncomment to execute
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL'

How do I deserialize a complex JSON object in C# .NET?

If you use C# 2010 or newer, you can use dynamic type:

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);

Then you can access attributes and arrays in dynamic object using dot notation:

string nemo = json.response[0].images[0].report.nemo;

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

Cannot kill Python script with Ctrl-C

KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python

Does Python have a string 'contains' substring method?

Here is your answer:

if "insert_char_or_string_here" in "insert_string_to_search_here":
    #DOSTUFF

For checking if it is false:

if not "insert_char_or_string_here" in "insert_string_to_search_here":
    #DOSTUFF

OR:

if "insert_char_or_string_here" not in "insert_string_to_search_here":
    #DOSTUFF

The openssl extension is required for SSL/TLS protection

This issue occurs due to openssl and extension director so uncomment below extensions in php.ini file

extension=php_openssl.dll

extension_dir = "ext"

Its works on my machine.

How to downgrade php from 5.5 to 5.3

Long answer: it is possible!

  1. Temporarily rename existing xampp folder
  2. Install xampp 1.7.7 into xampp folder name
  3. Folder containing just installed 1.7.7 distribution rename to different name and previously existing xampp folder rename back just to xampp.
  4. In xampp folder rename php and apache folders to different names (I propose php_prev and apache_prev) so you can after switch back to them by renaming them back.
  5. Copy apache and php folders from folder with xampp 1.7.7 into xampp directory
  6. In xampp directory comment line apache/conf/httpd.conf:458

    #Include "conf/extra/httpd-perl.conf"

  7. In xampp directory do next replaces in files:

php/pci.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*

php/pciconf.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*

php/pear.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/peardev.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/pecl.bat:32

from

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/phar.phar.bat:1

from

%~dp0php.exe %~dp0pharcommand.phar %*

to

"%~dp0php.exe" "%~dp0pharcommand.phar" %*

Enjoy new XAMPP with PHP 5.3

Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2

Get mouse wheel events in jQuery?

Answers talking about "mousewheel" event are refering to a deprecated event. The standard event is simply "wheel". See https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel

Does WGET timeout?

Prior to version 1.14, wget timeout arguments were not adhered to if downloading over https due to a bug.

Can media queries resize based on a div element instead of the screen?

A Media Query inside of an iframe can function as an element query. I've successfully implement this. The idea came from a recent post about Responsive Ads by Zurb. No Javascript!

Find element's index in pandas Series

I'm impressed with all the answers here. This is not a new answer, just an attempt to summarize the timings of all these methods. I considered the case of a series with 25 elements and assumed the general case where the index could contain any values and you want the index value corresponding to the search value which is towards the end of the series.

Here are the speed tests on a 2013 MacBook Pro in Python 3.7 with Pandas version 0.25.3.

In [1]: import pandas as pd                                                

In [2]: import numpy as np                                                 

In [3]: data = [406400, 203200, 101600,  76100,  50800,  25400,  19050,  12700, 
   ...:          9500,   6700,   4750,   3350,   2360,   1700,   1180,    850, 
   ...:           600,    425,    300,    212,    150,    106,     75,     53, 
   ...:            38]                                                                               

In [4]: myseries = pd.Series(data, index=range(1,26))                                                

In [5]: myseries[21]                                                                                 
Out[5]: 150

In [7]: %timeit myseries[myseries == 150].index[0]                                                   
416 µs ± 5.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [8]: %timeit myseries[myseries == 150].first_valid_index()                                        
585 µs ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [9]: %timeit myseries.where(myseries == 150).first_valid_index()                                  
652 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [10]: %timeit myseries.index[np.where(myseries == 150)[0][0]]                                     
195 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [11]: %timeit pd.Series(myseries.index, index=myseries)[150]                 
178 µs ± 9.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [12]: %timeit myseries.index[pd.Index(myseries).get_loc(150)]                                    
77.4 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [13]: %timeit myseries.index[list(myseries).index(150)]
12.7 µs ± 42.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [14]: %timeit myseries.index[myseries.tolist().index(150)]                   
9.46 µs ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

@Jeff's answer seems to be the fastest - although it doesn't handle duplicates.

Correction: Sorry, I missed one, @Alex Spangher's solution using the list index method is by far the fastest.

Update: Added @EliadL's answer.

Hope this helps.

Amazing that such a simple operation requires such convoluted solutions and many are so slow. Over half a millisecond in some cases to find a value in a series of 25.

How to check if a value is not null and not empty string in JS

Both null and empty could be validated as follows:

<script>
function getName(){
    var myname = document.getElementById("Name").value;
    if(myname != '' && myname != null){
        alert("My name is "+myname);
    }else{
        alert("Please Enter Your Name");
    }       
}

What is the difference between up-casting and down-casting with respect to class variable

1.- Upcasting.

Doing an upcasting, you define a tag of some type, that points to an object of a subtype (Type and subtype may be called class and subclass, if you feel more comfortable...).

Animal animalCat = new Cat();

What means that such tag, animalCat, will have the functionality (the methods) of type Animal only, because we've declared it as type Animal, not as type Cat.

We are allowed to do that in a "natural/implicit/automatic" way, at compile-time or at a run-time, mainly because Cat inherits some of its functionality from Animal; for example, move(). (At least, cat is an animal, isn't it?)

2.- Downcasting.

But, what would happen if we need to get the functionality of Cat, from our type Animal tag?.

As we have created the animalCat tag pointing to a Cat object, we need a way to call the Cat object methods, from our animalCat tag in a some smart pretty way.

Such procedure is what we call Downcasting, and we can do it only at the run-time.

Time for some code:

public class Animal {
    public String move() {
        return "Going to somewhere";
    }
}

public class Cat extends Animal{
    public String makeNoise() {
        return "Meow!";
    }   
}

public class Test {

    public static void main(String[] args) {
        
    //1.- Upcasting 
    //  __Type_____tag________object
        Animal animalCat = new Cat();
    //Some animal movement
        System.out.println(animalCat.move());
        //prints "Going to somewhere"
        
    //2.- Downcasting   
    //Now you wanna make some Animal noise.
        //First of all: type Animal hasn't any makeNoise() functionality.
        //But Cat can do it!. I wanna be an Animal Cat now!!
        
        //___________________Downcast__tag_____ Cat's method
        String animalNoise = ( (Cat) animalCat ).makeNoise();
        
        System.out.println(animalNoise);
        //Prints "Meow!", as cats usually done.
        
    //3.- An Animal may be a Cat, but a Dog or a Rhinoceros too.
        //All of them have their own noises and own functionalities.
        //Uncomment below and read the error in the console:
        
    //  __Type_____tag________object
        //Cat catAnimal = new Animal();
        
    }

}

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Exception of type 'System.OutOfMemoryException' was thrown.

If you're using IIS Express, select Show All Application from IIS Express in the task bar notification area, then select Stop All.

Now re-run your application.

Memory errors and list limits?

There is no memory limit imposed by Python. However, you will get a MemoryError if you run out of RAM. You say you have 20301 elements in the list. This seems too small to cause a memory error for simple data types (e.g. int), but if each element itself is an object that takes up a lot of memory, you may well be running out of memory.

The IndexError however is probably caused because your ListTemp has got only 19767 elements (indexed 0 to 19766), and you are trying to access past the last element.

It is hard to say what you can do to avoid hitting the limit without knowing exactly what it is that you are trying to do. Using numpy might help. It looks like you are storing a huge amount of data. It may be that you don't need to store all of it at every stage. But it is impossible to say without knowing.

What is the difference between Tomcat, JBoss and Glassfish?

Apache tomcat is just an only serverlet container it does not support for Enterprise Java application(JEE). JBoss and Glassfish are supporting for JEE application but Glassfish much heavy than JBOSS server : Reference Slide

Read values into a shell variable from a pipe

bash 4.2 introduces the lastpipe option, which allows your code to work as written, by executing the last command in a pipeline in the current shell, rather than a subshell.

shopt -s lastpipe
echo "hello world" | read test; echo test=$test

IE8 css selector

Building upon image72's excellent answer, you could actually have advanced CSS selectors like this:

<!--[if lt IE 7]><body class="IE IE7down IE8down IE9down IE10down"><![endif]-->
<!--[if IE 7]><body class="IE IE7 IE7down IE8down IE9down IE10down IE7up"><![endif]-->
<!--[if IE 8]><body class="IE IE8 IE8down IE9down IE10down IE7up IE8up"><![endif]-->
<!--[if IE 9]><body class="IE IE9 IE9down IE10down IE7up IE8up IE9up"><![endif]-->
<!--[if gte IE 10]><body class="IE IE10 IE10down IE7up IE8up IE9up IE10up"><![endif]-->
<!--[if !IE]>--><body class="notIE"><!--<![endif]-->

so that in your css you can do this:

.notIE   .foo { color: blue;   } /* Target all browsers except IE */
.IE9up   .foo { color: green;  } /* Taget IE equal or greater than 9 */
.IE8     .foo { color: orange; } /* Taget IE 8 only */
.IE7down .foo { color: red;    } /* Target IE equal or less than 7 */

.IE8 .foo, .IE9 .foo {
    font-size: 1.2em;            /* Target IE8 & IE9 only */
}

.bar { background-color: gray; } /* Applies to all browsers, as usual */

/* Maybe show a message only to IE users? */
.notIE #betterBrowser { display: none;  } /* Any browser except IE */
.IE    #betterBrowser { display: block; } /* All versions of IE */

This is great because:

  • It's perfectly standards compliant (no ugly/dangerous css hacks)
  • No need to have separate stylesheets
  • You can easily target any version of IE as well as complex combinations

JS regex: replace all digits in string

find the numbers and then replaced with strings which specified. It is achieved by two methods

  1. Using a regular expression literal

  2. Using keyword RegExp object

Using a regular expression literal:

<script type="text/javascript">

var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));

</script>

**Output:**my contact number is XXX. my age is XXX.

for more details:

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

how to auto select an input field and the text in it on page load

To do it on page load:

_x000D_
_x000D_
window.onload = function () {_x000D_
  var input = document.getElementById('myTextInput');_x000D_
  input.focus();_x000D_
  input.select();_x000D_
}
_x000D_
<input id="myTextInput" value="Hello world!" />
_x000D_
_x000D_
_x000D_

How to do multiline shell script in Ansible

I prefer this syntax as it allows to set configuration parameters for the shell:

---
- name: an example
  shell:
    cmd: |
      docker build -t current_dir .
      echo "Hello World"
      date

    chdir: /home/vagrant/

How do I change the font size and color in an Excel Drop Down List?

I created a custom view that is at 100%. Use the dropdowns then click to view page layout to go back to a smaller view.

Adding values to Arraylist

in the first you don't define the type that will be held and linked within your arraylist construct

this is the preferred method to do so, you define the type of list and the ide will handle the rest

in the third one you will better just define List for shorter code

Convert digits into words with JavaScript

For those who are looking for imperial/english naming conventions.

Based on @Salman's answer

_x000D_
_x000D_
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];

function inWords (num) {
    if ((num = num.toString()).length > 12) return 'overflow';
    n = ('00000000000' + num).substr(-12).match(/^(\d{3})(\d{3})(\d{3})(\d{1})(\d{2})$/);
    if (!n) return; var str = '';
    str += (n[1] != 0) ? (Number(n[1]) > 99 ? this.a[Number(n[1][0])] + 'hundred ' : '') + (a[Number(n[1])] || b[n[1][1]] + ' ' + a[n[1][2]]) + 'billion ' : '';
    str += (n[2] != 0) ? (Number(n[2]) > 99 ? this.a[Number(n[2][0])] + 'hundred ' : '') + (a[Number(n[2])] || b[n[2][1]] + ' ' + a[n[2][2]]) + 'million ' : '';
    str += (n[3] != 0) ? (Number(n[3]) > 99 ? this.a[Number(n[3][0])] + 'hundred ' : '') + (a[Number(n[3])] || b[n[3][1]] + ' ' + a[n[3][2]]) + 'thousand ' : '';
    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
     str += (Number(n[5]) !== 0) ? ((str !== '') ? 'and ' : '') +
                (this.a[Number(n[5])] || this.b[n[5][0]] + ' ' +
                    this.a[n[5][1]]) + '' : '';
    return str;
}

document.getElementById('number').onkeyup = function () {
    document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
_x000D_
<span id="words"></span>
<input id="number" type="text" />
_x000D_
_x000D_
_x000D_

How to get the squared symbol (²) to display in a string

Not sure what kind of text box you are refering to. However, I'm not sure if you can do this in a text box on a user form.

A text box on a sheet you can though.

Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Text = "R2=" & variable
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Characters(2, 1).Font.Superscript = msoTrue

And same thing for an excel cell

Sheets("Sheet1").Range("A1").Characters(2, 1).Font.Superscript = True

If this isn't what you're after you will need to provide more information in your question.

EDIT: posted this after the comment sorry

How can I reset eclipse to default settings?

Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.

Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.

How does HttpContext.Current.User.Identity.Name know which usernames exist?

For windows authentication

select your project.

Press F4

Disable "Anonymous Authentication" and enable "Windows Authentication"

enter image description here

How to get a jqGrid cell value when editing

This is my solution:

                function getDataLine(grida, rowid){  //vykradeno z inineeditu a vohackovano

                    if(grida.lastIndexOf("#", 0) === 0){
                        grida = $(grida);
                    }else{
                        grida = $("#"+grida);
                    }

                    var nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;

                    ind = grida.jqGrid("getInd",rowid,true);
                    if(ind === false) {return success;}
                    editable = $(ind).attr("editable");
                    if (editable==="1") {
                        var cm;
                        var colModel = grida.jqGrid("getGridParam","colModel") ;
                        $("td",ind).each(function(i) {
                            // cm = $('#mygrid').p.colModel[i];
                            cm = colModel[i];
                            nm = cm.name;
                            if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
                                switch (cm.edittype) {
                                    case "checkbox":
                                        var cbv = ["Yes","No"];
                                        if(cm.editoptions ) {
                                            cbv = cm.editoptions.value.split(":");
                                        }
                                        tmp[nm]=  $("input",this).is(":checked") ? cbv[0] : cbv[1]; 
                                        break;
                                    case 'text':
                                    case 'password':
                                    case 'textarea':
                                    case "button" :
                                        tmp[nm]=$("input, textarea",this).val();
                                        break;
                                    case 'select':
                                        if(!cm.editoptions.multiple) {
                                            tmp[nm] = $("select option:selected",this).val();
                                            tmp2[nm] = $("select option:selected", this).text();
                                        } else {
                                            var sel = $("select",this), selectedText = [];
                                            tmp[nm] = $(sel).val();
                                            if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
                                            $("select option:selected",this).each(
                                                function(i,selected){
                                                    selectedText[i] = $(selected).text();
                                                }
                                            );
                                            tmp2[nm] = selectedText.join(",");
                                        }
                                        if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
                                        break;
                                }
                            }
                        });
                    }
                    return tmp;
                }

jquery append external html file into my page

You can use jquery's load function here.

$("#your_element_id").load("file_name.html");

If you need more info, here is the link.

Why would anybody use C over C++?

There's also the approach some shops take of using some of C++'s features in a C-like way, but avoiding ones that are objectionable. For example, using classes and class methods and function overloading (which are usually easy for even C diehards to cope with), but not the STL, stream operators, and Boost (which are harder to learn and can have bad memory characteristics).

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Detecting mobile devices

Related answer: https://stackoverflow.com/a/13805337/1306809

There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.

Apache Spark: map vs mapPartitions?

Map:

Map transformation.

The map works on a single Row at a time.

Map returns after each input Row.

The map doesn’t hold the output result in Memory.

Map no way to figure out then to end the service.

// map example

val dfList = (1 to 100) toList

val df = dfList.toDF()

val dfInt = df.map(x => x.getInt(0)+2)

display(dfInt)

MapPartition:

MapPartition transformation.

MapPartition works on a partition at a time.

MapPartition returns after processing all the rows in the partition.

MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.

MapPartition service can be shut down before returning.

// MapPartition example

Val dfList = (1 to 100) toList

Val df = dfList.toDF()

Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))

Df1.collec()

//display(df1.collect())

For more details, please refer to the Spark map vs mapPartitions transformation article.

Hope this is helpful!

How to jump to top of browser page

Pure Javascript solution

theId.onclick = () => window.scrollTo({top: 0})

If you want smooth scrolling

theId.onclick = () => window.scrollTo({ top: 0, behavior: `smooth` })

Woocommerce get products

<?php
$args     = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args ); 
?>

This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products

1114 (HY000): The table is full

You may be running out of space either in the partition where the mysql tables are stored (usually /var/lib/mysql) or in where the temporary tables are stored (usually /tmp).

You may want to: - monitor your free space during the index creation. - point the tmpdir MySQL variable to a different location. This requires a server restart.

Set a button background image iPhone programmatically

Code for background image of a Button in Swift 3.0

buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)

Hope this will help someone.

Select first occurring element after another element

For your literal example you'd want to use the adjacent selector (+).

h4 + p {color:red}//any <p> that is immediately preceded by an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I'm not</p>

However, if you wanted to select all successive paragraphs, you'd need to use the general sibling selector (~).

h4 ~ p {color:red}//any <p> that has the same parent as, and comes after an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I am too</p>

It's known to be buggy in IE 7+ unfortunately.

require(vendor/autoload.php): failed to open stream

Create composer.json file with requisite library for ex:

{
    "require": {
        "mpdf/mpdf": "^6.1"
    }
}

Execute the below command where composer.json exists:

composer install

In case of Drupal :

Use the web root folder of drupal to include autoload for ex:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/vendor/autoload.php';

In case of other systems: Use the root folder variable or location to include the autoload.php

How to get the day name from a selected date?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
    static void Main(string[] args)
    { 
 Console.WriteLine("Enter the Day Number ");
 int day = int.Parse(Console.ReadLine());
 Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}  
 } 
   }

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

Using XPATH to search text containing &nbsp;

I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:

<xsl:value-of select="count(//td[text()='&nbsp;'])" />

The value returned is 1, which is the correct value in my test case.

However, I did have to declare nbsp as an entity within my XML and XSL using the following:

<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> ]>

I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.

Edit: My code sample actually contains the characters '&nbsp;' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!

How can I delete derived data in Xcode 8?

For Xcode Version 8.2 (8C38), you can remove the projects completely (project name in Xcode, programs, data, etc.) one by one by doing the following: [Note: the instructions are not for just remove the project names from the Welcome Window]

Launch the Xocde and wait until the Welcome window is displayed. The projects will be shown on the right hand side (see below) Xcode Welcome Window

Right click the project you want to remove completely and a pop window [Show in Folder] jumps out; selec it to find out where is the project in the [Finder] (see below) Find the project folder

Right click the project folder in the Finder to find it’s path through [Get Info]; use path in the Info window to go to the parent folder, and go to there[Locate the project folder path] (see below)

Right click the Project Folder (e.g. DemoProject01) and Porject file (DemoProject01.xcodeproj) and select [Move to Trash] ; you will see that (a) the folder in finder is removed AND (b) the Project in the Xcode Welcome Window’s Project List is removed.

How do I remove my IntelliJ license in 2019.3?

For Linux to reset current 30 days expiration license, you must run code:

rm ~/.config/JetBrains/IntelliJIdea2019.3/options/other.xml
rm -rf ~/.config/JetBrains/IntelliJIdea2019.3/eval/*
rm -rf .java/.userPrefs

How to draw interactive Polyline on route google maps v2 android

You can use this method to draw polyline on googleMap

// Draw polyline on map
public void drawPolyLineOnMap(List<LatLng> list) {
    PolylineOptions polyOptions = new PolylineOptions();
    polyOptions.color(Color.RED);
    polyOptions.width(5);
    polyOptions.addAll(list);

    googleMap.clear();
    googleMap.addPolyline(polyOptions);

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (LatLng latLng : list) {
        builder.include(latLng);
    }

    final LatLngBounds bounds = builder.build();

    //BOUND_PADDING is an int to specify padding of bound.. try 100.
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, BOUND_PADDING);
    googleMap.animateCamera(cu);
}

You need to add this line in your gradle in case you haven't.

compile 'com.google.android.gms:play-services-maps:8.4.0'

exceeds the list view threshold 5000 items in Sharepoint 2010

I had the same problem.please do the following it may help you: By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.

To Change the LVT:

  1. Click SharePoint Central Administration,
  2. Go to Application Management
  3. Manage Web Applications
  4. Select your application
  5. Click General Settings at the ribbon
  6. Select Resource Throttling
  7. List View Threshold limit --> change the value to your need.
  8. Also change the List View Threshold for Auditors and Administrators.if you are a administrator.

Click OK to save it.

Open popup and refresh parent page on close popup

You can use the below code in the parent page.

<script>
    window.onunload = refreshParent;
    function refreshParent() {
      window.opener.location.reload();
    }
</script>

Easy way to convert Iterable to Collection

Since RxJava is a hammer and this kinda looks like a nail, you can do

Observable.from(iterable).toList().toBlocking().single();

How do I give ASP.NET permission to write to a folder in Windows 7?

I know this is an old thread but to further expand the answer here, by default IIS 7.5 creates application pool identity accounts to run the worker process under. You can't search for these accounts like normal user accounts when adding file permissions. To add them into NTFS permission ACL you can type the entire name of the application pool identity and it will work.

It is just a slight difference in the way the application pool identity accounts are handle as they are seen to be virtual accounts.

Also the username of the application pool identity is "IIS AppPool\application pool name" so if it was the application pool DefaultAppPool the user account would be "IIS AppPool\DefaultAppPool".

These can be seen if you open computer management and look at the members of the local group IIS_IUSRS. The SID appended to the end of them is not need when adding the account into an NTFS permission ACL.

Hope that helps

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

GSON - Date format

This is a bug. Currently you either have to set a timeStyle as well or use one of the alternatives described in the other answers.

How do a send an HTTPS request through a proxy in Java?

HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.

You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,

http://www.javaworld.com/javaworld/javatips/jw-javatip111.html

EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,

 public SSLTunnelSocketFactory(String proxyhost, String proxyport){
      tunnelHost = proxyhost;
      tunnelPort = Integer.parseInt(proxyport);
      dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
 }

 ...

 connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
 connection.setDefaultHostnameVerifier( new HostnameVerifier()
 {
    public boolean verify( String arg0, SSLSession arg1 )
    {
        return true;
    }
 }  );

EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,

http://bugs.sun.com/view_bug.do?bug_id=6614957

The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,

public class SSLContextTest {

    public static void main(String[] args) {

        System.setProperty("https.proxyHost", "proxy.xxx.com");
        System.setProperty("https.proxyPort", "8888");

        try {

            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkServerTrusted =============");
                }
            } }, new SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(
                    sslContext.getSocketFactory());

            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String arg0, SSLSession arg1) {
                            System.out.println("hostnameVerifier =============");
                            return true;
                        }
                    });

            URL url = new URL("https://www.verisign.net");
            URLConnection conn = url.openConnection();
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}

This is what I get when I run the program,

checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......

As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.

How can I see normal print output created during pytest run?

pytest captures the stdout from individual tests and displays them only on certain conditions, along with the summary of the tests it prints by default.

Extra summary info can be shown using the '-r' option:

pytest -rP

shows the captured output of passed tests.

pytest -rx

shows the captured output of failed tests (default behaviour).

The formatting of the output is prettier with -r than with -s.

How do I use disk caching in Picasso?

This is what I did. Works well.

First add the OkHttp to the gradle build file of the app module:

compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'

Then make a class extending Application

import android.app.Application;

import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;

public class Global extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        Picasso.Builder builder = new Picasso.Builder(this);
        builder.downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE));
        Picasso built = builder.build();
        built.setIndicatorsEnabled(true);
        built.setLoggingEnabled(true);
        Picasso.setSingletonInstance(built);

    }
}

add it to the Manifest file as follows :

<application
        android:name=".Global"
        .. >

</application>

Now use Picasso as you normally would. No changes.

EDIT:

if you want to use cached images only. Call the library like this. I've noticed that if we don't add the networkPolicy, images won't show up in an fully offline start even if they are cached. The code below solves the problem.

Picasso.with(this)
            .load(url)
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(imageView);

EDIT #2

the problem with the above code is that if you clear cache, Picasso will keep looking for it offline in cache and fail, the following code example looks at the local cache, if not found offline, it goes online and replenishes the cache.

Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {

    }

    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(posts.get(position).getImageUrl())
                .error(R.drawable.header)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});

PHP date yesterday

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43

Event handler not working on dynamic content

You are missing the selector in the .on function:

.on(eventType, selector, function)

This selector is very important!

http://api.jquery.com/on/

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler

See jQuery 1.9 .live() is not a function for more details.

Subtract days, months, years from a date in JavaScript

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

You need to individually add/remove unit of time in date object

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

SELECT with a Replace()

You are creating an alias P and later in the where clause you are using the same, that is what is creating the problem. Don't use P in where, try this instead:

SELECT Replace(Postcode, ' ', '') AS P FROM Contacts
WHERE Postcode LIKE 'NW101%'

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

Ubuntu defaults to the OpenJDK packages. If you want to install Oracle's JDK, then you need to visit their download page, and grab the package from there.

Once you've installed the Oracle JDK, you also need to update the following (system defaults will point to OpenJDK):

export JAVA_HOME=/my/path/to/oracle/jdk
export PATH=$JAVA_HOME/bin:$PATH

If you want the Oracle JDK to be the default for your system, you will need to remove the OpenJDK packages, and update your profile environment variables.

How to see full query from SHOW PROCESSLIST

See full query from SHOW PROCESSLIST :

SHOW FULL PROCESSLIST;

Or

 SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

Check if an array is empty or exists

The following is my solution wrapped in a function that also throws errors to manage a couple of problems with object scope and all types of possible data types passed to the function.

Here's my fiddle used to examine this problem (source)

var jill = [0];
var jack;
//"Uncaught ReferenceError: jack is not defined"

//if (typeof jack === 'undefined' || jack === null) {
//if (jack) {
//if (jack in window) {
//if (window.hasOwnP=roperty('jack')){
//if (jack in window){

function isemptyArray (arraynamed){
    //cam also check argument length
  if (arguments.length === 0) { 
    throw "No argument supplied";
  }

  //console.log(arguments.length, "number of arguments found");
  if (typeof arraynamed !== "undefined" && arraynamed !== null) {
      //console.log("found arraynamed has a value");
      if ((arraynamed instanceof Array) === true){
        //console.log("I'm an array");
        if (arraynamed.length === 0) {
            //console.log ("I'm empty");
            return true;
        } else {
          return false;
        }//end length check
      } else {
        //bad type
        throw "Argument is not an array";
      } //end type check
  } else {
    //bad argument
    throw "Argument is invalid, check initialization";;
  }//end argument check
}

try {
  console.log(isemptyArray(jill));
} catch (e) {
    console.log ("error caught:",e);
}

'int' object has no attribute '__getitem__'

you can also covert int to str first and assign index to it then again convert it to int like this:

int(str(x)[n]) //where x is an integer value

Calling a JavaScript function named in a variable

I'd avoid eval.

To solve this problem, you should know these things about JavaScript.

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

So, why not something like,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

Is there a decent wait function in C++?

Lots of people have suggested POSIX sleep, Windows Sleep, Windows system("pause"), C++ cin.get()… there's even a DOS getch() in there, from roughly the late 1920s.

Please don't do any of these.

None of these solutions would pass code review in my team. That means, if you submitted this code for inclusion in our products, your commit would be blocked and you would be told to go and find another solution. (One might argue that things aren't so serious when you're just a hobbyist playing around, but I propose that developing good habits in your pet projects is what will make you a valued professional in a business organisation, and keep you hired.)

Keeping the console window open so you can read the output of your program is not the responsibility of your program! When you add a wait/sleep/block to the end of your program, you are violating the single responsibility principle, creating a massive abstraction leak, and obliterating the re-usability/chainability of your program. It no longer takes input and gives output — it blocks for transient usage reasons. This is very non-good.

Instead, you should configure your environment to keep the prompt open after your program has finished its work. Your Batch script wrapper is a good approach! I can see how it would be annoying to have to keep manually updating, and you can't invoke it from your IDE. You could make the script take the path to the program to execute as a parameter, and configure your IDE to invoke it instead of your program directly.

An interim, quick-start approach would be to change your IDE's run command from cmd.exe <myprogram> or <myprogram>, to cmd.exe /K <myprogram>. The /K switch to cmd.exe makes the prompt stay open after the program at the given path has terminated. This is going to be slightly more annoying than your Batch script solution, because now you have to type exit or click on the red 'X' when you're done reading your program's output, rather than just smacking the space bar.


I assume usage of an IDE, because otherwise you're already invoking from a command prompt, and this would not be a problem in the first place. Furthermore, I assume the use of Windows (based on detail given in the question), but this answer applies to any platform… which is, incidentally, half the point.

How do I POST an array of objects with $.ajax (jQuery or Zepto)

edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).

As simple as:

JSON.stringify(yourData)

You should encode you data in JSON before sending it, you can't just send an object like this as POST data.

I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:

$.post(_saveDeviceUrl, {
    data : $.toJSON(postData)
}, function(response){
    //Process your response here
}
);

How do I use vim registers?

I think the secret guru register is the expression = register. It can be used for creative mappings.

:inoremap  \d The current date <c-r>=system("date")<cr>

You can use it in conjunction with your system as above or get responses from custom VimL functions etc.

or just ad hoc stuff like

<c-r>=35+7<cr>

jQuery click not working for dynamically created items

You have to add click event to an exist element. You can not add event to dom elements dynamic created. I you want to add event to them, you should bind event to an existed element using ".on".

$('p').on('click','selector_you_dynamic_created',function(){...});

.delegate should work,too.

mysql datetime comparison

But this is obviously performing a 'string' comparison

No. The string will be automatically cast into a DATETIME value.

See 11.2. Type Conversion in Expression Evaluation.

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

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

In my case I wanted to access an array inside a custom helper like so,

{{#ifCond arr.[@index] "foo" }}

Which did not work, but the answer suggested by @julesbou worked.

Working code:

{{#ifCond (lookup arr @index) "" }}

Hope this helps! Cheers.

How to read specific lines from a file (by line number)?

I think this would work

 open_file1 = open("E:\\test.txt",'r')
 read_it1 = open_file1.read()
 myline1 = []
 for line1 in read_it1.splitlines():
 myline1.append(line1)
 print myline1[0]

How do I print the percent sign(%) in c

Try printing out this way

printf("%%");

Retina displays, high-res background images

Do I need to double the size of the .box div to 400px by 400px to match the new high res background image

No, but you do need to set the background-size property to match the original dimensions:

@media (-webkit-min-device-pixel-ratio: 2), 
(min-resolution: 192dpi) { 

    .box{
        background:url('images/[email protected]') no-repeat top left;
        background-size: 200px 200px;
    }
}

EDIT

To add a little more to this answer, here is the retina detection query I tend to use:

@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) { 

}

- Source

NB. This min--moz-device-pixel-ratio: is not a typo. It is a well documented bug in certain versions of Firefox and should be written like this in order to support older versions (prior to Firefox 16). - Source


As @LiamNewmarch mentioned in the comments below, you can include the background-size in your shorthand background declaration like so:

.box{
    background:url('images/[email protected]') no-repeat top left / 200px 200px;
}

However, I personally would not advise using the shorthand form as it is not supported in iOS <= 6 or Android making it unreliable in most situations.

Angular 2: How to call a function after get a response from subscribe http.post

You can do this be using a new Subject too:

Typescript:

let subject = new Subject();

get_categories(...) {
   this.http.post(...).subscribe( 
      (response) => {
         this.total = response.json();
         subject.next();
      }
   ); 

   return subject; // can be subscribed as well 
}

get_categories(...).subscribe(
   (response) => {
     // ...
   }
);

Querying data by joining two tables in two database on different servers

for this simply follow below query

select a.Id,a.type,b.Name,b.City from DatabaseName.dbo.TableName a left join DatabaseName.dbo.TableName b on a.Id=b.Id

Where I wrote databasename, you have to define the name of the database. If you are in same database so you don't need to define the database name but if you are in other database you have to mention database name as path or it will show you error. Hope I made your work easy

Typescript sleep

For some reason the above accepted answer does not work in New versions of Angular (V6).

for that use this..

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

above worked for me.

Usage:

this.delay(3000);

OR more accurate way

this.delay(3000).then(any=>{
     //your task after delay.
});

SQL Column definition : default value and not null redundant?

My SQL teacher said that if you specify both a DEFAULT value and NOT NULLor NULL, DEFAULT should always be expressed before NOT NULL or NULL.

Like this:

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL

How to check for empty value in Javascript?

Your script seems incorrect in several places.

Try this

var timetemp = document.getElementsByTagName('input');

for (var i = 0; i < timetemp.length; i++){
    if (timetemp[i].value == ""){
        alert ('No value');
    }
    else{
        alert (timetemp[i].value);
    }
}

Example: http://jsfiddle.net/jasongennaro/FSzT2/

Here's what I changed:

  1. started by getting all the inputs via TagName. This makes an array
  2. initialized i with a var and then looped through the timetemp array using the timetemp.length property.
  3. used timetemp[i] to reference each input in the for statement

How to determine the number of days in a month in SQL Server?

--Last Day of Previous Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)))

--Last Day of Current Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)))

--Last Day of Next Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)))

Personally though, I would make a UDF for it if there is not a built in function...

jQuery + client-side template = "Syntax error, unrecognized expression"

As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

SQL Server: Get data for only the past year

I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.

At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.

SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))

Thanks to those above whose solutions helped me arrive at what I needed.

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

YOU CALL THIS IN JADE: firebase.initializeApp(config); IN THE BEGIN OF THE FUNC

script.
    function signInWithGoogle() {
        firebase.initializeApp(config);
        var googleAuthProvider = new firebase.auth.GoogleAuthProvider
        firebase.auth().signInWithPopup(googleAuthProvider)
        .then(function (data){
            console.log(data)
        })
        .catch(function(error){
            console.log(error)
        })
    }

Is it possible to focus on a <div> using JavaScript focus() function?

document.getElementById('tries').scrollIntoView() works. This works better than window.location.hash when you have fixed positioning.

Is there an easy way to attach source in Eclipse?

It may seem like overkill, but if you use maven and include source, the mvn eclipse plugin will generate all the source configuration needed to give you all the in-line documentation you could ask for.

Pandas: sum DataFrame rows for given columns

The shortest and simpliest way here is to use

    df.eval('e = a + b + d')

What is a Subclass

A subclass is something that extends the functionality of your existing class. I.e.

Superclass - describes the catagory of objects:

public abstract class Fruit {

    public abstract Color color;

}

Subclass1 - describes attributes of the individual Fruit objects:

public class Apple extends Fruit {

    Color color = red;

}

Subclass2 - describes attributes of the individual Fruit objects:

public class Banana extends Fruit {

    Color color = yellow;

}

The 'abstract' keyword in the superclass means that the class will only define the mandatory information that each subclass must have i.e. A piece of fruit must have a color so it is defines in the super class and all subclasses must 'inherit' that attribute and define the value that describes the specific object.

Does that make sense?

tsc throws `TS2307: Cannot find module` for a local file

In VS2019, the project property page, TypeScript Build tab has a setting (dropdown) for "Module System". When I changed that from "ES2015" to CommonJS, then VS2019 IDE stopped complaining that it could find neither axios nor redux-thunk (TS2307).

tsconfig.json:

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": "src",
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": [
      "es6",
      "dom",
      "es2015.promise"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "outDir": "build/dist",
    "rootDir": "src",
    "sourceMap": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "es5",
    "skipLibCheck": true,
    "strict": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "exclude": [
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts",
    "node_modules",
    "obj",
    "**/*.spec.ts"
  ],
  "include": [
    "src",
    "src/**/*.ts",
    "@types/**/*.d.ts",
    "node_modules/axios",
    "node_modules/redux-thunk"
  ]
}

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

i think that is what you want.

SELECT 
      A.SalesOrderID, 
      A.OrderDate, 
      FooFromB.*

FROM A,
     (SELECT TOP 1 B.Foo
      FROM B
      WHERE A.SalesOrderID = B.SalesOrderID
      ) AS FooFromB

WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'

How to change the name of an iOS app?

If you wanna change the name, that will be displayed on your screen, right under your icon, in Xcode 4, go to Targets->info->Bundle Display Name and change it to whatever you want.

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.