text:
Q: Uploading folders php Lets say I have a folder full of about fifty pictures I'd just taken on a photo shoot and I wanted to upload all of them to my website. So instead of having to select every single one and upload it, I could just upload the folder that they're in. Yet being that the browsers won't let you select folders, I know I could make it so you copy and paste the path to that folder, yet that would be ugly,hackish and complicated. Is there a better way to get around uploading a folder instead of having to do that? And if I do have to do that, will copy() work on folders or will I have to use a recursive loop to get all the pictures out of that folder and any folders within it?

A: you should add the multiple attribute to the input:file element. That way you can select as many files as you want via a single input:file field.

A: PHP itself is unable to handle such a task because it must rely on the HTML interface to communicate with the client. If you are using HTML5, or if your clients use browsers with the appropriate support, you can use the multiple attribute for the file input element to handle this task.
For versions of HTML prior to HTML5, You will need to add a tool that can handle multiple file uploads, such as SWFUpload(Flash), jUpload(Java applet), or Uploadify (jQuery).

A: Simply: It isn't possible just with html form. Just zip them and unzip them on server side.

A: Until HTML5 browsers take over the world, or you use client-side solutions based on Flash or Java, the ONLY way you'll be able to upload multiple files is by providing a <input type="file" ...> for each file you want uploaded.
Allowing file uploads from browsers is a major security risk, so the file inputs are one of the most heavily policed/regulated elements in browsers - allowing any kind of programmability opens the door to an exploit being able to suck any file(s) the attack wants from the client machine.

A: I do this for my wifes website http://www.beccablake.com.  She is also a photographer.  I created a custom module (she uses drupal as the CMS) to upload a zip file containing all the pictures.  Once uploaded I extract the zip and iterate through all the files and create new nodes for each one.  Here is a snippet of code from that module that may help you do what you want.
<?php
$file = 'path/to/zip/pictures.zip';
$dest = 'path/to/pictures/directory';
exec('unzip "'. $file .'" -d '. $dest);
// If you need to do something with each file (like I do)
$files = scandir($dest);
?>

This assumes you can perform an 'exec' on your server to unzip.  My code is a lot different as I do more with the pics since its in Drupal, I create a proofing gallery and each picture is its own node so users can comment/rate/favorite the photos... etc.
Good Luck!

A: The browser will never transmit any information about the client's directory structure, so such a general solution as you envision it is not possible in terms of directories. What you can hope for is that clients will offer a facility to turn a user's directory selection into a list of contained files, but in any event this would not be of any concern to you on the server side.


text:
Q: How to Store Image in SDCard using Service? I am getting the Image URL and set that URL in GridView.it shows me Successfully in Gridview.But I also want to Store That Images in SDCard Using Service.How to do That.Please Someone Help me for my this Issue.Thank You.
public class MainActivity extends Activity {

ListView list;
GridView gv;
String TAG = "GRIDVIEW";
LazyAdapter adapter;
Bitmap bitmap;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(this, MyService.class));
    new loading().execute();
    // gv = (GridView) findViewById(R.id.grid_view);
    // startService(new Intent(MainActivity.this, MyService.class));
    // gv = (GridView) findViewById(R.id.grid_view);
    // gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
    // gv.setHorizontalSpacing(10);
    // gv.setVerticalSpacing(40);

    // gv.setGravity(200);

}

ProgressDialog mprogress;

private class loading extends AsyncTask<String, Void, String> {

    protected void onPreExecute() {
        mprogress = new ProgressDialog(MainActivity.this);
        mprogress.setMessage("Loading...");
        mprogress.show();

        super.onPreExecute();

    }

    protected String doInBackground(String... params) {
        // startService(new Intent(MainActivity.this, MyService.class));
        return null;
    }

    protected void onPostExecute(String result) {
        getGirdview();
        mprogress.dismiss();
        super.onPostExecute(result);
    }

    private void getGirdview() {
        gv = (GridView) findViewById(R.id.grid_view);
        gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
        gv.setHorizontalSpacing(10);
        gv.setVerticalSpacing(40);
    }

}

public String[] mStrings = {

        "http://a1.twimg.com/profile_images/97470808/icon_normal.png",
        "http://a3.twimg.com/profile_images/511790713/AG.png",
        };
    }

public class MyService extends Service {

String TAG = "GRIDVIEW";
Bitmap bitmap;
MainActivity mclass = new MainActivity();

public void onStart(Intent intent, int startId) {

    for (int i = 0; i < mclass.mStrings.length; i++) {

        String str = mclass.mStrings[i];
        bitmap = DownloadImage(str);
        // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
        // R.drawable.ic_launcher);
        // File sd = Environment.getExternalStorageDirectory();
        File storagePath = new File(
                Environment.getExternalStorageDirectory(), "Wallpaper");
        storagePath.mkdirs();

        String fileName = "test" + i + ".png";
        File dest = new File(storagePath, fileName);
        try {
            FileOutputStream out;
            out = new FileOutputStream(dest);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    super.onStart(intent, startId);

}

public int onStartCommand(Intent intent, int flags, int startId) {

    // for (int i = 0; i < mStrings.length; i++) {
    //
    // String str = mStrings[i];
    // bitmap = DownloadImage(str);
    // // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
    // // R.drawable.ic_launcher);
    // // File sd = Environment.getExternalStorageDirectory();
    // File storagePath = new File(
    // Environment.getExternalStorageDirectory(), "Wallpaper");
    // storagePath.mkdirs();
    //
    // String fileName = "test" + i + ".png";
    // File dest = new File(storagePath, fileName);
    // try {
    // FileOutputStream out;
    // out = new FileOutputStream(dest);
    // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    // out.flush();
    // out.close();
    // } catch (FileNotFoundException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }

    return super.onStartCommand(intent, flags, startId);
}

public IBinder onBind(Intent intent) {

    return null;
}

// public void onStart(Intent intent, int startId) {
//
// for (int i = 0; i < mStrings.length; i++) {
//
// String str = mStrings[i];
// bitmap = DownloadImage(str);
// // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// // R.drawable.ic_launcher);
// // File sd = Environment.getExternalStorageDirectory();
// File storagePath = new File(
// Environment.getExternalStorageDirectory(), "Wallpaper");
// storagePath.mkdirs();
//
// String fileName = "test" + i + ".png";
// File dest = new File(storagePath, fileName);
// try {
// FileOutputStream out;
// out = new FileOutputStream(dest);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// out.flush();
// out.close();
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// super.onStart(intent, startId);
// }

private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}

private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Toast.makeText(MyService.this, "Image is Downloaded",
            Toast.LENGTH_SHORT).show();
    return bitmap;
}

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
        .synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;

public ImageLoader(Context context) {
    fileCache = new FileCache(context);
    executorService = Executors.newFixedThreadPool(5);
}

final int stub_id = R.drawable.ic_launcher;

public void DisplayImage(String url, ImageView imageView) {
    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null)
        imageView.setImageBitmap(bitmap);
    else {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView) {
    PhotoToLoad p = new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f);
    if (b != null)
        return b;

    // from web
    try {
        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl
                .openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex) {
        ex.printStackTrace();
        if (ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
    try {
        // decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        FileInputStream stream1 = new FileInputStream(f);
        BitmapFactory.decodeStream(stream1, null, o);
        stream1.close();

        // Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE = 70;
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
                    || height_tmp / 2 < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        FileInputStream stream2 = new FileInputStream(f);
        Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
        stream2.close();
        return bitmap;
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

// Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;

    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;

    PhotosLoader(PhotoToLoad photoToLoad) {
        this.photoToLoad = photoToLoad;
    }

    @Override
    public void run() {
        try {
            if (imageViewReused(photoToLoad))
                return;
            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            Activity a = (Activity) photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
    String tag = imageViews.get(photoToLoad.imageView);
    if (tag == null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
        bitmap = b;
        photoToLoad = p;
    }

    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        if (bitmap != null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

}
public class LazyAdapter extends BaseAdapter {

private Context mContext;
String TAG = "GridView";
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
Bitmap bitmap;

public LazyAdapter(Activity a, String[] d) {
    activity = a;
    data = d;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader = new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.length;
}

public Object getItem(int position) {
    return data;
}

public long getItemId(int position) {
    return 0;
}

public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.item, null);
    }

    // TextView txt_name = (TextView) convertView.findViewById(R.id.text);
    // txt_name.setText("item" + position);

    ImageView image = (ImageView) convertView.findViewById(R.id.image);
    // image.setTag(data[position]);

    imageLoader.DisplayImage(data[position], image);

    return convertView;
}

}

A: Environment.getExternalStorage() will return the sd card location. Once you get the location, you can create directories as needed. Looks like you are doing it....so what is the issue that you are running into?
Also, use IntentService rather than a service......it takes care of most of the plumbing work for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Noether current for a local gauge transformation for the Klein-Gordon Lagrangian The Noether current corresponding to the transformation $\phi \to e^{i\alpha} \phi$ for the Klein-Gordon Lagrangian density
$$\mathcal{L}~=~|\partial_{\mu}\phi|^2 -m^2 |\phi|^2$$
by finding $\delta S$, and setting it to zero. The general formula for a global transformation is
$$j^{\mu}=\frac{\partial \mathcal{L}}{\partial(\partial_{\mu} \phi)}\Delta \phi-\mathcal{J}^{\mu},$$
where $ \partial_{\mu} \mathcal{J}^{\mu}$ is the change in the Lagrangian density due to the transformation. (See Peskin section 2.2).
How do I find the Noether's current corresponding to a local transformation $\phi \to e^{i\alpha(x)}\phi$?

A: Comment to the question (v4): OP is talking about a local complex phase transformation for a complex massive scalar (KG) theory. But a generic local complex phase transformation is not a quasi-symmetry$^1$ of the KG action, and hence Noether's (2nd) theorem does not apply.
--
$^1$ A infinitesimal transformation $\delta$ is a quasi-symmetry if the Lagrangian density ${\cal L}$ is preserved $\delta {\cal L}= d_{\mu} f^{\mu}$ modulo a total space-time divergence off-shell, cf. this Phys.SE answer. If the total space-time divergence $d_{\mu} f^{\mu}$ is zero off-shell, we speak of a symmetry.

A: For a local gauge transformation $\delta \phi = i \alpha(x)\phi$, and $\delta \phi^*=-i\alpha(x)\phi$.
These equations imply $\delta(\partial_{\mu}\phi)=i(\partial_{\mu} \alpha)\phi+i \alpha (\partial_{\mu}\phi)$ and $\delta(\partial_{\mu}\phi^*)=-i(\partial_{\mu} \alpha)\phi^*-i \alpha (\partial_{\mu}\phi^*)$
Therefore, $\delta \mathcal{L}=\delta(\partial_{\mu}\phi \partial^{\mu}\phi^*)-m^2 \delta(\phi* \phi)=\partial_{\mu}\alpha J^{\mu}$, where $J^{\mu}=i(\phi \partial^{\mu}\phi^*-\phi^* \partial^{\mu}\phi)$
Setting $\delta S=\int \delta \mathcal{L}=0$, one gets $\partial_{\mu}J^{\mu}=0$


text:
Q: Bootstrap Carousel - Image too small I'm working with Bootstrap and the carousel plugin. This is my code:

                ‹
                ›

But the images are displayed too small. I want to fill it the whole carousel.
Here is an image (yes, the image is bigger than it is shown in the image):

A:

    ...

The question is answered here

A: In bootstrap 3 add the responsive and center classes:

I believe this is a duplicate question.


text:
Q: Convert duration in seconds to hours and minutes and skip empty values We have a Time Tracking model with a duration (in seconds) value that is always greater than 60 (1 minute).
I need to convert the duration to hours and minutes if they are not zero and without zero at the start of hours or minutes.
For example:
duration1 = 63000  # expected value:  17 h 30 m
duration2 = 28800  # expected value:  8 h
duration3 = 1800   # expected value:  30 m
duration4 = 300    # expected value:  5 m

I almost did, but have small problem with a zero values:
Time.at(duration1).utc.strftime('%H h %M m').sub!(/^0/, '')
# 17 h 30 m

Time.at(duration2).utc.strftime('%H h %M m').sub!(/^0/, '')
# 8 h 00 m

Time.at(duration3).utc.strftime('%H h %M m').sub!(/^0/, '')
# 0 h 30 m

Time.at(duration4).utc.strftime('%H h %M m').sub!(/^0/, '')
# 0 h 05 m

Thanks for answers.

A: Why not just something simple like this:
def to_hms(time)
  hours = time / 3600
  minutes = (time / 60) % 60

  if (hours > 0 and minutes > 0)
    '%d h %d m' % [ hours, minutes ]
  elsif (hours > 0)
    '%d h' % hours
  elsif (minutes > 0)
    '%d m' % minutes
  end
end

Where this produces the desired results:
to_hms(63000)
# => "17 h 30 m"
to_hms(28800)
# => "8 h"
to_hms(1800)
# => "30 m"

A: Use
.gsub(/\b0+(?:\B|\s[hm](?:\s|$))/, '')

See proof.
Explanation
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  0+                       '0' (1 or more times (matching the most
                           amount possible))
--------------------------------------------------------------------------------
  (?:                      group, but do not capture:
--------------------------------------------------------------------------------
    \B                       the boundary between two word chars (\w)
                             or two non-word chars (\W)
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    \s                       whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
    [hm]                     any character of: 'h', 'm'
--------------------------------------------------------------------------------
    (?:                      group, but do not capture:
--------------------------------------------------------------------------------
      \s                       whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
     |                        OR
--------------------------------------------------------------------------------
      $                        before an optional \n, and the end of
                               the string
--------------------------------------------------------------------------------
    )                        end of grouping
--------------------------------------------------------------------------------
  )                        end of grouping

A: You can either match 00 followed by h or m, or you can match a 0 and assert a digit 1-9 directly to the right followed by either h or m
\b(?:00 [hm]|0(?=[1-9] [hm]))\s*

Rubular demo and a Ruby demo.
Time.at(duration1).utc.strftime('%H h %M m').gsub(/\b(?:00 [hm]|0(?=[1-9] [hm]))\s*/, ''))

A: Taking a page from @Tadman's answer, I suggest the following.
def doit(duration)
  hr, min = (duration/60).divmod(60)
  case
  when hr == 0  then "#{min} m"
  when min == 0 then "#{hr} h"
  else               "#{hr} h, #{min} m"
  end
end

doit 63000  #=> "17 h 30 m"
doit 28800  #=> "8 h"
doit 1800   #=> "30 m"
doit 0      #=> "0 m"

See Integer#divmod (which references Numeric#divmod). For example,
(63000/60).divmod(60) #=> [17, 1800]
  #=> [17, 30]

I'll leave my origin answer below for anyone wanting to practice the construction of regular expressions, but I cannot recommend its use in practice, or for that matter, the use of a regular expression generally (or conversion to a Time object).
def doit(duration)
  hrs, secs = duration.divmod(3600)
  ("%d h %d m" % [hrs, secs/60]).gsub(/\A0 h |(?<=h) 0 m\z/, '')
end

doit 63000  #=> "17 h 30 m"
doit 28800  #=> "8 h"
doit 1800   #=> "30 m"
doit 0      #=> ""

I will explain the regular expression below.

Notice that doit 0 above returns an empty string. If it is desired that "0 m" be returned in that case the regular expression can be modified as follows.
def doit(duration)
  hrs, secs = duration.divmod(3600)
  ("%d h %d m" % [hrs, secs/60]).gsub(/\A0 h |(?<=h)(?<!\A0 h) 0 m\z/, '')
end

doit 63000  #=> "17 h 30 m"
doit 28800  #=> "8 h"
doit 1800   #=> "30 m"
doit 0      #=> "0 m"

The second regular expression can be written in free-spacing mode to make it self-documenting.
/
\A          # match beginning of string
0[ ]h[ ]    # match '0 h '
|           # or
(?<=h)      # use postive lookbehind to assert the current match is preceded by 'h'
(?<!\A0 h)  # use negative lookbehind to assert the current match not preceded by
            # '0 h' at the beginning of the string
0[ ]m       # match '0 m'
\z          # invoke free-spacing regex definition mode

The first regular espression above differs from this one only that it does not contain the negative lookbehind.
When using free-spacing mode the regex engine removes all whitespace outside comments before parsing the expression. Spaces that are part of the expression must therefore be protected. I've done that be put each space in a character class. The are other ways to do that, one being to escape spaces (\ ).

A: If you are using Rails 6.1+, you can try to utilize the following function:

def format_seconds(numeric)
  seconds = numeric.abs.seconds

  hours   = seconds.in_hours.floor.hours
  minutes = seconds.in_minutes.minutes - hours.in_minutes.minutes

  hours   = hours.parts[:hours].to_i
  minutes = minutes.parts[:minutes].to_i

  formatted =
    case
    when hours.nonzero? && minutes.nonzero?
      "#{hours} h #{minutes} m"
    when hours.nonzero?
      "#{hours} h"
    when minutes.nonzero?
      "#{minutes} m"
    else
      '0 m'
    end

  formatted = "-#{formatted}" if numeric.negative?

  formatted
end

# format_seconds(63_000)
# => "17 h 30 m"

# format_seconds(28_800)
# => "8 h"

# format_seconds(1_800)
# => "30 m"

# format_seconds(0)
# => "0 m"

# format_seconds(1_000_000)
# => "277 h 46 m"

# format_seconds(-1_000_000)
# => "-277 h 46 m"

# format_seconds(300.25)
# => "5 m"

Sources:

*

*Numeric#abs.

*Numeric#seconds.

*ActiveSupport::Duration#in_hours.

*Numeric#floor.

*Numeric#hours.

*ActiveSupport::Duration#in_hours.

*Numeric#minutes.

*ActiveSupport::Duration#parts.

*Numeric#nonzero?.

*Numeric#negative?.

A: Just for fun, chaining Kernel#then, returning a hash with data, manipulate it rejecting zeros, etc.
duration0 = 322200

res = duration0.divmod(24*60*60).then do |day, sec|
  sec.divmod(60*60).then do |hour, sec|
    sec.divmod(60).then do |min, sec|
      {d: day, h: hour, m: min, s: sec}
    end
  end
end.reject { |_, v| v.zero? }.map { |k, v| "#{v}#{k}"}.join(' ')

res #=> "3d 17h 30m"

You could add days to hours if you want: {h: 24 * days + hour, m: min, s: sec}.


text:
Q: How to check if page is being iframed inside a colorbox? I have certain pages on my site that sometimes open in regular windows and sometimes open in an iframe inside colorbox modal windows (depending on location and context).
When a page is being displayed in an inframe inside a colorbox, I want to remove certain navigational elements from the page. To do this, first I need to find out, if the page is being displayed inside a colorbox.
Is there a way to find this out through jQuery?
Thanks.


text:
Q: Strange output from ndarray.shape I am trying to convert the value of a dictionary to a 1d array using:np.asarray(dict.values()), but when I tried to print the shape of the output array, I have problem.
My array looks like this:
dict_values([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26])

but the output of array.shape is:
()

by which I was expecting (27,1) or (27,)
after I changed the code to np.asarray(dict.values()).flatten(),the output of array.shape became
(1,)

I have read the document of numpy.ndarray.shape, but can't get a hint why the outputs are like these. Can someone explain it to me? Thx

A: This must be python 3.
From docs

The objects returned by dict.keys(), dict.values() and dict.items()
  are view objects. They provide a dynamic view on the dictionary's
  entries, which means that when the dictionary changes, the view
  reflects these changes.

The issue is that dict.values() is only returning a dynamic view of the data in dictionary's values, Leading to the behaviour you see.
dict_a = {'1': 1, '2': 2}
res = np.array(dict_a.values())
res.shape #()
res
#Output:
array(dict_values([1, 2]), dtype=object)

Notice that the numpy array isn't resolving the view object into the actual integers, but rather just coercing the view into an array with dtype = object
To avoid this issue, consume the view to get a list, as follows:
dict_a = {'1': 1, '2': 2}
res = np.array(list(dict_a.values()))
res.shape #(2,)
res #array([1, 2])
res.dtype #dtype('int32')


text:
Q: In Swift Table View not populating Firebase data I've been stuck with this issue for the past 2 days and can't find a solution. I'm using Firebase with a View Controller, top portion of the screen I'm using it to display the info of the user that is logged in and under I have a Table View where I want to display the picture and basic information of other users. I'm able to download the data from Firebase and display the info of the user that is logged-in. The issue I'm having is populating the data inside the cells. I created a service file because I'm going to use the functions few times in other areas of the app.
Here is my code:
import Foundation
import Firebase

struct Service {

    static func fetchUser(withUid uid: String, completion: @escaping(Member) -> Void) {
        COLLECTION_USERS.document(uid).getDocument { (snapshot, error) in
            guard let dictionary = snapshot?.data() else { return }
            let user = Member(dictionary: dictionary)
            completion(user)}
    }

    static func fetchUsers(forCurrentUser user: Member, completion: @escaping([Member]) -> Void) {
        var members = [Member]()

        let query = COLLECTION_USERS

        query.getDocuments { (snapshot, error) in
            guard let snapshot = snapshot else { return }
            snapshot.documents.forEach({ document in
                let dictionary = document.data()
                let user = Member(dictionary: dictionary)

                guard user.uid != Auth.auth().currentUser?.uid else { return }
                members.append(user)

                    if members.count == snapshot.documents.count - 1 { completion(members)
                        print("FROM SERVICE MEMBERS: \(members)") // Console displays this: FROM SERVICE FETCHING USERS COUNT 5
                }}
            )}
    }
}

VIEW CONTROLLER
import UIKit
import Firebase

class HomeVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var memberFeedTableView: UITableView!
    @IBOutlet weak var profileImage: userImagesView!
    @IBOutlet weak var profileNameAgeLbl: UILabel!
    @IBOutlet weak var profileCityLbl: UILabel!
    @IBOutlet weak var profileStatus: UILabel!
    @IBOutlet weak var changeFilterOptions: UIBarButtonItem!

    var members = [Member]()

    var userId = Auth.auth().currentUser?.uid
    var handle: AuthStateDidChangeListenerHandle?
    var userListener: ListenerRegistration!

    override func viewDidLoad() {
        super.viewDidLoad()

        memberFeedTableView.dataSource = self
        memberFeedTableView.delegate = self
        memberFeedTableView.rowHeight = 450

        configureUI()

        fetchUserData()
    }

    func configureUI() {
        navigationController?.navigationBar.isHidden = false
        overrideUserInterfaceStyle = .light

        tapToReleaseKeyboard()

        let background = backgroundGradientColor()
        background.frame = self.view.bounds
        self.view.layer.insertSublayer(background, at: 0)

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return members.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = memberFeedTableView.dequeueReusableCell(withIdentifier: "MembersFeedCell", for: indexPath) as! MembersFeedCell
        cell.configureMemberFeedCell(member: members[indexPath.row])
        return cell
    }

    func fetchUsersData(forCurrentUser user: Member) {
        Service.fetchUsers(forCurrentUser: user) { users in
            self.members = users //issue is here, I'm not sure how to send the array to the table view to populate the cells.
            print("CHECKING ARRAY..: \(self.members.count)") // Console displays this: CHECKING ARRAY..: 4

        }
    }

    func fetchUserData() {
        guard let currentUid = Auth.auth().currentUser?.uid else { return }
        Service.fetchUser(withUid: currentUid) { user in
            self.fetchUsersData(forCurrentUser: user)
            self.profileNameAgeLbl.text = user.name + "," + " " + (user.age)
            self.profileCityLbl.text = user.city
            self.profileImage.loadImage(with: user.imageURL)}
    }

Any help is greatly appreciated. Thank you!


text:
Q: Change the color of a row based on string data in a cell using VB in excel I have an excel spreadsheet where I would like to highlight all the rows where the string "05 Paint" appears in cells in column A.  I found this code that changes the color of the cell containing the string "05 Paint" but can't figure out how to highlight the whole row:
Sub Highlight()
Dim rng As Range, cell As Range
Set rng = Range("A2:A250")
For Each cell In rng
   Select Case cell.Value
       Case "05 Paint"
       cell.Interior.ColorIndex = 4
   End Select
Next
End Sub

Ideally I would like the row to be highlighted from column A to column I.
Any help would be appreciated.
Thanks!

A: Use
Cell.Resize(1, 9).Interior.ColorIndex = 4

A: So you know which row to be highlighted. That makes it none-dynamic.
You can try "conditional formatting" for that row. Plus going through each cell could be as nearly costly as my suggestion.
You can try and compare the best performance gain solutiin for your need.

A: Where "entire row" has been defined a ColumnsA:I, the search string is 05 Paint (being either all of or part of the cell content) and the search is case insensitive then:
Record Macro:
select ColumnsA:I, HOME > Styles - Conditional Formatting, New Rule...
Use a formula to determine which cells to format
Format values where this formula is true:
=SEARCH("05 Paint",$A1)

Format..., select formatting, OK, OK.
Stop recording.


text:
Q: Detect selected row with force touch watchkit Is it possible to detect selected row index with force touch? Did force touch in tableView current row is highlighted. But i can't take info about him when context menu appears. TableView method -didSelectRowAtIndex: not called with this event.

A: The only thing you can handle programmatically with the Force Touch is the Context Menu and this menu is associated with a specific controller, more information you will find following the link.
About the row highlighting: When you start tapping the system doesn't know what the real action is - the regular touch or the force one. So it is starting to highlight a specific area and only later find out what was the action.


text:
Q: Can't load stylesheet on mobile I am using a single stylesheet for both mobile and desktop and utilizing @media all.  The queries work on the desktop, but the stylesheet will not load at all on mobile.  I have tried iOS and Android.  I am also using the tags:
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

and
<link href="http://localhost/Atoz/css/styles.css" type="text/css" rel="stylesheet"  media="all"/><meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

here is my

A: Use the code below
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="css/mobile.css" type="text/css" />

Mobile Related jQuery Plugins are below. it will make your life easy.
http://jquerymobile.com/
http://jqtjs.com/
http://phonegap.com/


text:
Q: Google Maps Geocode: Invalid signature for address but not for LatLng Recently I've started having an issue with the Google Maps geocode service using an address.
When sending a LatLng request (below) the request completes successfully, providing the required JSON however when sending an address (using the same signing code and signing proceedure) I receive a 403 with the error message:

Unable to authenticate the request.
Provided 'signature' is not valid for the provided client ID. Learn more: https://developers.google.com/maps/documentation/business/webservices/auth

*

*LatLng - https://maps.googleapis.com/maps/api/geocode/json?latlng=37.092590332%2C-8.78356933594&client=revoked&sensor=true&signature=revoked

*Address - https://maps.googleapis.com/maps/api/geocode/json?signature=revoked&client=revoked&sensor=true&address=SW1A+2
I've played around with http vs https, different types of URL encoding etc but cannot seem to get it to work.
Anybody have any ideas?
For completeness I've included my signing code below:
class GoogleGeocoder(Geocoder):

    url = 'https://maps.googleapis.com/maps/api/geocode/json'

    def build_params(self):
        if self.lon and self.lat:
            self.get_params = {
                'latlng': '{lat},{lon}'.format(
                    lat=self.lat,
                    lon=self.lon
                )
            }
        elif self.address:
            self.get_params = {
                'address': self.address
            }
        else:
            raise Exception("Must provide either an address or (lon, lat)")
        self.get_params['sensor'] = 'true'
        self.get_params['client'] = GOOGLE_CLIENT_STRING

        req = requests.Request('GET', self.url, params=self.get_params)
        r = req.prepare()
        url_for_signing = r.path_url
        decodedKey = base64.urlsafe_b64decode(GOOGLE_SIGNING_KEY)
        signature = hmac.new(decodedKey, url_for_signing, hashlib.sha1)
        encodedSignature = base64.urlsafe_b64encode(signature.digest())
        self.get_params['signature'] = encodedSignature
        return self


text:
Q: Can't find __main__ when initializing my SQLite database I'm new to Python and even newer to Flask. When I'm trying to initialize my database using SQLAlchemy I get an error. Does anyone know what's going on and how I can resolve this issue so I can run db.create_table() to initialize my database and to test my API endpoints?
I enter:
python3
from app import db

The error:
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
/Users/mark/Documents/Coding/friend_code/venv/bin/python3: can't find '__main__' module in '/Users/mark/Documents/Coding/friend_code'

And this is my entire code inside app.py
import os
import secrets
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request, jsonify
from flask_marshmallow import Marshmallow

users = []
theme = [
    {'neon red and neon blue': ('rgb(255, 60, 40)', 'rgb(10, 185, 230)')},
    {'gray': ('rgb(130, 130, 130)', 'rgb(130, 130, 130)')},
    {'blue and neon yellow': ('rgb(70, 85, 230)', 'rgb(230, 255, 0)')},
    {'neon pink and neon green': ('rgb(255, 50, 120)', 'rgb(30, 220, 0)')},
    {'neon purple and neon orange': ('rgb(180, 0, 245)', 'rgb(250, 160, 5)')},
    {'neon yellow': ('rgb(250, 160, 5)', 'rgb(250, 160, 5)')}
]

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))

# database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
    os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# initializion
db = SQLAlchemy(app)
ma = Marshmallow(app)

# user class/model
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    avatar = db.Column(db.String, default='default.jpg', nullable=False,)
    friend_code = db.Column(db.Integer, nullable=False)
    update_code = db.Column(db.String, nullable=False)
    theme = db.Column(db.String, default='neon red and neon blue')
    dark_mode = db.Column(db.Boolean, default=True, nullable=False)

    def __init__(self, username, avatar, friend_code, update_code, theme, dark_mode):
        self.username = username
        self.avatar = avatar
        self.friend_code = friend_code
        self.update_code = update_code
        self.theme = theme
        self.dark_mode = dark_mode

# user schema
class UserSchema(ma.Schema):
    # allowed visible fields
    class Meta:
        fields = ('username', 'avatar', 'friend_code',
                  'update_code', 'theme', 'dark_mode')

# initialization
user_schema = UserSchema()

# GET
@app.route('/<username>', methods=['GET'])
def get(username):
    user = User.query.get(username)
    return user_schema.jsonify(user)

# POST
@app.route('/', methods=['POST'])
def post():
    username = request.json['username']
    avatar = request.json['avatar']
    friend_code = request.json['friend_code']
    update_code = secrets.token_urlsafe(8)
    theme = request.json['theme']
    dark_mode = request.json['dark_mode']

    new_user = User(username, avatar, friend_code,
                    update_code, theme, dark_mode)

    # add to db
    db.session.add(new_user)
    db.session.commit()

    return user_schema.jsonify(new_user)

# run server
app.run(debug=True)

A: How are you invoking your code? If you are calling directly, like with
$ python app.py

then you need to wrap the app.run() command inside of a main block at the end of app.py
if __name__ == "__main__":
    app.run(debug=True)

Otherwise if you are trying to invoke the package directly, like with
$ python -m friend_code

then you need to include a __main__.py file inside the folder which contains the block of code with the main block (as well as with the import statement for app).
The issue is that your run server function call is being executed every time you try to import the database from that file, because it is not wrapped with one of these main blocks.
You can read more about how this works from this in-depth answer.
With regard to creating your database tables the simplest method would be creating a file which handles this for you, which you can then run directly
create_db.py
if __name__ == "__main__":
    from app import db
    db.create_all()
    print("Database Created")


text:
Q: Mysql query group by week with specific start and end I searched stack overflow and have come so close yet have not found if this is possible.
I want to group a weekly query  from 11:30 am Friday to 11:29 am Friday for each week.
adding days and hours only partially work. I need to keep this in a mysql query not coding in php, etc.

A: You need to give more information on your table structure and some sample date. If I have understood correctly then below is simple pseudo code  which you can start use to start framing your requirement .
select something from table where date between 1:30 am Friday and 11:29 am
group by trunc(date).

Note :
- Format the date in where condition using to_Date.
- Week definition might be different in database so you need to manipulate.


text:
Q: How to create an animated GIF using FFMPEG with an interval? Hello fellow overflowers,
A brief overview of what I'm trying to accomplish; I have a site that will accept video uploads, uploads get converted into the mp4 format to be uniformed and playable on the web using one of the many available players.  That part is all fine and dandy.
The problem now is I want to show the user a short scaled preview (animated gif) of the video before they click to play it.  The code I'm working with now is
ffmpeg -i test.mp4 -vf scale=150:-1 -t 10 -r 1 test.gif
Which works for creating a scaled animated gif with a fixed width of 150px at a rate of 1 frame per second but its only an animation of the first 10 seconds of the video.  I'm trying to do something that spreads out the frame gap to cover the whole video length but create an animated gift that's no more then 10 seconds long.
For example say I have a video that's 30 seconds I want the gif to be 10 seconds long but cover frames of the entire 30 seconds so it might start at frame 3 or 3 seconds in and create a frame in the gif, then at 6 seconds in the video create another frame, then 9 seconds in another, and so forth where the final outcome is
    example video 30 seconds long          example video 1 minute 45 second long

video position - gif frame/per second      video position - gif frame/per second
      00:03:00   1                               00:10:50   1
      00:06:00   2                               00:21:00   2
      00:09:00   3                               00:31:50   3
      00:12:00   4                               00:42:00   4
      00:15:00   5                               00:52:50   5
      00:18:00   6                               01:03:00   6
      00:21:00   7                               01:13:50   7
      00:24:00   8                               01:24:00   8
      00:27:00   9                               01:34:50   9
      00:30:00   10                              01:45:00   10

  3 second interval between frames         10.5 second interval between frames

Where you end up with an animated gif that's 10 seconds long showing a preview of the entire video no matter the length of it.  Which basically just boils down to
video length / 10 (length of desired animated gif) = interval to use between frames but I don't know how I can use that data to accomplish my problem...
So does anyone have an idea or suggestion on how this can be accomplished with relative ease?  I can probably do it by calculating the length through code and running a command to extract each individual frame from the video that's needed then generate a gif from the images but I'd like to be able to do it all with just one command.   Thanks.

A: So I ended up just doing this by code having found this script (http://www.alberton.info/video_preview_as_animated_gif_with_ffmpeg_and_spl.html#.UxnU_IXYNyI) which made it easy where you can simply specify the position in the video by percentage on the frame to extract along with the interval between frames I can accomplish my problem above using the following.
// where ffmpeg is located, such as /usr/sbin/ffmpeg
$ffmpeg = '/usr/bin/ffmpeg';

// the input video file
$video = 'sample.avi';

// extract one frame at 10% of the length, one at 20% and so on
$frames = array('10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%');

// set the delay between frames in the output GIF in ms (60 = 1 min)
$joiner = new Thumbnail_Joiner(60);

// loop through the extracted frames and add them to the joiner object specifying
// the max width/height to make the thumb based on the dimensions of the video
foreach (new Thumbnail_Extractor($video, $frames, '150x150', $ffmpeg) as $key => $frame) {
    $joiner->add($frame);
}

$joiner->save('sample.gif');

The above will go 10% into the length of the video, grab the frame for the first image of the animated GIF, create a 60ms/1sec delay, go 20% into the length of the video and repeat the process for each percentage specified which results in a video of any length having an animated GIF that's 10 seconds long containing 10 frames within the video at 10% intervals in length that show for 1 second each.


text:
Q: Mongodb calculate area of polygon
Hi I have objects like this on my mongodb
{
  "_id" : ObjectId("53a9cf13a004869fb0476859"),
  "id" : NumberLong(4090259),
  "version" : "3",
  "changeset" : "10265399",
  "uid" : "136321",
  "user" : "Teddy73",
  "timestamp" : "2012-01-01T21:32:37Z",
  "poly" : {
    "type" : "Polygon",
    "coordinates" : [[
        [8.6030412, 49.6544071], [8.602331, 49.6556077],
        [8.6073617, 49.6575444], [8.6081741, 49.6564124], [8.6030412, 49.6544071]
    ]]
  },
  "natural" : "water",
  "source" : "landsat"
}

is it possible to calculate the area of poly?
In Postgres there is a function called
area()


text:
Q: Launching Geb tests from Intellij I am a long time Eclipse / GGTS user trying to make the transition to Intellij. I'm gradually getting used to it, however one of the things I miss about GGTS was the ability to launch Geb tests from with the IDE very quickly.
When I try to launch a Geb test (pointing at an already-running grails instance on localhost) from Intellij, the entire Grails stack unnecessarily fires up (it looks like test-app MySpec is being called). This means that I need to wait about 3 or 4 minutes before my spec even starts running.
Is there a way to launch Geb tests within Intellij without starting up Grails?

A: Use the -baseUrl option when you run your tests.
Create a new Grails Run configuration in IDEA that looks something like this:
test-app functional: -baseUrl=http://localhost:8080/

Then your Geb tests will connect to the grails instance running on localhost:8080 instead of creating their own instance.


text:
Q: Make search companion the default when searching folders I'm running Windows XP and I've installed Windows Search so that Outlook is able to index my emails and speed up searching. The problem is that now every time I do a "find in files and folders" the first thing that pops up is the windows search dialog with a discrete "this folder is not indexed, use search companion instead" at the bottom.
Now I have no intention of indexing any of my drive - is there any way to make the search companion the default again (without uninstalling Windows Search)

A: Start > Run > type regedit and click OK, then navigate to:
HKEY_CURRENT_USER\Software\Microsoft\Windows Desktop Search\DS

Then double-click on 'ShowStartSearchBand' and set the value to '0'. Close that and you're done, the next time you click 'Search' in explorer, the old, reliable search companion will appear.
Source

A: You need to enable search companion:

*

*You have to open "Windows Desktop Search"

*Then in the left hand pane at the bottom, next to the little old dog, scroll down and click "Click here to use search companion."

It modifies the registry value ShowStartSearchBand under:
HKEY_CURRENT_USER\Software\Microsoft\Windows Desktop Search\DS

*Open this registry key using regedit and change ShowStartSearchBand and change its value to 0.


text:
Q: Align two same sized boxes with differing origin points I have two boxes, both are the exact same size and shape. Box A's origin is in the very centre of the shape whereas box B's origin is in an arbitrary place within the shape. We also have the min and max points of each box (relative to the origin) so that we are able to determine where the origin is within the box. The goal is to use box A's origin position to offset box B's origin position so that all of the faces of both boxes align.
I'm sure this is a simple math problem but I just can't quite figure it out how to use box B's min and max points to offset box B's origin so that the boxes align.
boxA        = BoxShape()
boxA.min    = [-5, -7, -3]
boxA.max    = [ 5,  7,  3]
boxA.origin = [10, 78, 43]

boxB        = BoxShape()
boxB.min    = [-4, -4, -4]
boxB.max    = [ 6, 10,  2]
boxB.origin = boxA.origin + some_offset

A: After some more poking around I finally found the solution. The problem I was having was that I was using box B's min instead of max in the equation I wrote. Switching it out for max now works.
function get_offset(min, max, half)
    min  = math.abs(min)
    max  = math.abs(max)
    half = math.abs(half)

    if max > half then
        return half - max
    else
        return min - half
    end
end

function process(entity)
    min      = entity.scale * entity.min
    max      = entity.scale * entity.max
    size     = entity.shape:getSize()
    position = entity.rigidBody:getPosition()

    x = get_offset(min.x, max.x, size.x / 2)
    y = get_offset(min.y, max.y, size.y / 2)
    z = get_offset(min.z, max.z, size.z / 2)

    entity.position.x = position.x + x
    entity.position.y = position.y + y
    entity.position.z = position.z + z
end


text:
Q: Is it okay to allow objects to be stored in each other depending on loading order? I have an object that represent's a User's account on my site, and a separate object that acts as an attachment to the main account object and extends the user's ability to operate some major functionality on the site - a full functioning storefront.
I have been representing the relationship as so:
Class Account {
    $id
    $store // this is the store object
    $email
    $password
    $status

    get_store() // loads the store
}

Class Store {
    $id // unique store id
    $store_name
    $store_info

    post_item()
}

So far, this has been working great, but when I search or aggregate stores this way, it requires me to go through the Account object to get to the store.
I would like to cut the process in half by being able to also get to the account object through the store.
Does it create a problem to ALSO allow an $account object to be stored in the $store object, just in case I want to load it the other way around?
An example of allowing for this bi-directional loading would be as follows:
Class Account {
    $id
    $store // this is the store object
    $email
    $password
    $status

    get_store() // loads the store
}

Class Store {
    $id
    $account // this is the account object
    $store_name
    $store_info

    get_account() // loads the account
    post_item()
}

A: That's a common refactoring. The only thing you have to be aware of is that you will need to manage the "back pointer" when you associate one object with the other, e.g. when fetching the store for an account, you have to make sure the store will also get the back pointer to that account and vice versa.
Further reading:

*

*Change Unidirectional Association to Bidirectional

*Same with examples in PHP


text:
Q: Windows 2012 R2 RRAS VPN Bandwidth issue (worked fine with 2008 R2) 3 machines :
VPN Server (VS)
Random Server (RS)
My Personnal Computer (PC)

*

*PC and VS on different networks

*VS and RS are on same network

*VS can connect the internet directly and has a bandwidth of 100+ Mbits

*PC can connect the internet directly and has a bandwidth of 100+ Mbits

*RS can connect the internet through VS (not using the vpn access, they are on same network) and has a bandwidth of 100+ Mbits

*PC can connect the internet through VS (using VPN) BUT bandwidth is heavily reduced : less then 1 Mbits, latency is greatly increase (+100ms instead of 10)

My vpn bandwidth is very low and I don't understand why. It's not just when I use the vpn to access the internet, it's whenever I exchange data with the VPN network and it's very problematic.
I had the very same configuration with windows 2008 R2 and i didn't have the bandwidth issue.
Any idea ?

A: I installed the vendor-provided drivers of the host machine.
Fixed everything


text:
Q: Cucumber - Java - Exception in thread "main" java.lang.NoClassDefFoundError: io/cucumber/plugin/ConcurrentEventListener I've tried searching for the specific error. Though there have been few questions answered for java.lang.NoClassDefFoundError I could not find one for io/cucumber/plugin/ConcurrentEventListener.

*

*I am creating a basic cucumber test to login to a public website

*I have implemented a separate webconnector module to handle driver operations using pico-container

*I understand there is something wrong with the dependencies added to pom.xml but not able to zero in on the root cause.

When I run the scenario from feature file (and even with the runner) I keep getting below error when running the test.
I'll appreciate any help or pointers on the problem I'm facing. Thank you.
Stacktrace:
*
***Exception in thread "main" java.lang.NoClassDefFoundError: io/cucumber/plugin/ConcurrentEventListener**
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:174)
    at cucumber.runtime.formatter.PluginFactory.pluginClass(PluginFactory.java:166)
    at cucumber.runtime.formatter.PluginFactory.getPluginClass(PluginFactory.java:223)
    at cucumber.runtime.formatter.PluginFactory.isStepDefinitionReporterName(PluginFactory.java:206)
    at io.cucumber.core.options.RuntimeOptionsBuilder$ParsedPluginData.addPluginName(RuntimeOptionsBuilder.java:213)
    at io.cucumber.core.options.RuntimeOptionsBuilder.addPluginName(RuntimeOptionsBuilder.java:61)
    at io.cucumber.core.options.RuntimeOptionsParser.parse(RuntimeOptionsParser.java:90)
    at io.cucumber.core.options.CommandlineOptionsParser.parse(CommandlineOptionsParser.java:25)
    at io.cucumber.core.options.CommandlineOptionsParser.parse(CommandlineOptionsParser.java:29)
    at io.cucumber.core.cli.Main.run(Main.java:29)
    at io.cucumber.core.cli.Main.main(Main.java:14)
Caused by: java.lang.ClassNotFoundException: io.cucumber.plugin.ConcurrentEventListener
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 23 more
Process finished with exit code 1*

*
My pom.xml:
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
<!--        Selenium Dependencies-->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>3.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.14.0</version>
        </dependency>
<!--        Selenium Drivers -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>3.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>3.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-remote-driver</artifactId>
            <version>3.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-ie-driver</artifactId>
            <version>3.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-edge-driver</artifactId>
            <version>3.14.0</version>
        </dependency>
<!--        Cucumber Dependencies-->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>4.8.1</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java8</artifactId>
            <version>4.8.1</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>4.8.1</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>gherkin</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-picocontainer</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>4.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M2</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>4.8.1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

The test runner:
package Runners;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        dryRun = false,
        strict = true,
        monochrome = true,
        features = {"src/test/resources/features"},
        glue = {"StepDefs","WebConnector"},
        plugin = {
                "pretty"
        }
)
public class Runner {
}

And the sample feature file:
Feature: User logs into the account on National Rail
  Background: Browser set up
  Given The browser is launched Chrome
  Scenario Outline: User successfully logs in to the account
    Given I am on Home page
    And I enter login credentials <User_Id>,<Password>
    Examples:
    | User_Id |Password  |
    | UserId1 |password1 |
    | UserId2 |password2 |

A: Try upgrading all the Cucumber dependencies to v5, you seem to have v5 of gherkin but rest of them are v4.
If you check github, there's no ConcurrentEventListener for v4 but there's one for v5
I believe, this should resolve your issue.

A: *

*Please make sure to use the same version for all of your Cucumber dependencies.

You are currently mixing <version>4.8.1</version> and <version>5.0.0</version>.

*Please make sure to only specify the (Cucumber) dependencies you actually need. Some dependencies (e.g. Gherkin) are transitive, meaning they are provided by the Cucumber dependencies you specify.

You can find more on which dependencies to use (and their latest version) in the Cucumber docs


text:
Q: Mocha/Chai Test linkTo Function Returning AssertionError I'm trying to find & correct the Javascript code in challenge.js so that it passes the Mocha & Chai tests as specified in spec.js.... Nothing I try will get it to pass the tests when I run the command $ mocha spec.js in the Terminal.... To provide more information, the resulting error message that is continually returned in the Terminal regardless of any changes I make to challenge.js is shown underneath.
Challenge.js
module.exports.linkTo = function(text, address) {
  return "" + address + ""
};

Spec.js
var expect = require("chai").expect;
var challenge = require("./challenge.js");

describe("linkTo", function() {
  it("should be defined", function() {
    expect(challenge.linkTo).to.exist;
  });

  it("should return a valid link for Bloc", function() {
    expect(challenge.linkTo("Bloc", "http://www.bloc.io")).to.eql("Bloc");
  });
});

Error Message as returned in Terminal
linkTo
✓ should be defined
1) should return a valid link for Bloc

  1 passing (11ms)
  1 failing

  1) linkTo should return a valid link for Bloc:

  AssertionError: expected 'http://www.bloc.io' to deeply equal 'Bloc'
  + expected - actual

  +Bloc
  -http://www.bloc.io

  at Context.<anonymous> (/home/vagrant/frontend-javascript-exercises/02-reading-mocha-tests/00-a-tested-function/spec.js:10:63)
  at callFn (/usr/local/lib/node_modules/mocha/lib/runnable.js:266:21)
  at Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:259:7)
  at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:387:10)
  at /usr/local/lib/node_modules/mocha/lib/runner.js:470:12
  at next (/usr/local/lib/node_modules/mocha/lib/runner.js:312:14)
  at /usr/local/lib/node_modules/mocha/lib/runner.js:322:7
  at next (/usr/local/lib/node_modules/mocha/lib/runner.js:257:23)
  at Object._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:289:5)
  at processImmediate [as _immediateCallback] (timers.js:336:15)

Can anyone PLEASE point out the correction(s) needed in challenge.js in order for the tests to pass when I run $ mocha spec.js in the Terminal???
Thanks in advance
Lex

A: Replace adress with text and text with address inside function declaration.
module.exports.linkTo = function(text, address) {
  return "" + text + ""
};

Test output cleary says what was expected
+Bloc
-http://www.bloc.io


text:
Q: How can I show my canvas in a .jar file, as only the JFrame shows? I have asked this question before, but it wasn't good enough, so I deleted it and made a new one.
I'm building a game and I want to export the game as a .jar file so I can run it on other people's computers. The only problem is, when I run the jar, an empty JFrame appears. What should at least appear is a black screen, even though I have added my Canvas to the JFrame.
I can run everything in my IDE (Eclipse), but when I put it on my desktop, nothing seems to happen. One of the solutions I pondered was to download the .jars and put them in the AppData folder of said computer, and then get the login application (which works just fine) to run the main class in the .jar using a URLClassLoader.
The only problem with that is that I don't quite understand how to use the URLClassLoader, nor am I good with using the JavaDoc either. :/
Here's a look at my main class (I have all my imports too,):
public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 6601282971656374659L;

    /* The version of the game, will be updates with annotation later! It also has the location to the game path! */
    public static final String version = "Version: 0.1 Alpha";
    private static final String GAME_PATH = System.getProperty("user.home") + "\\AppData\\Roaming\\[Game]";

    /* Basic integers and Dimensions for the JFrame and Canvas */
    public static final int WIDTH = 460;
    public static final int HEIGHT = 280;
    private static final int SCALE = 2;
    private final Dimension size = new Dimension((WIDTH * SCALE), (HEIGHT * SCALE));

    /* BufferedImage below is the one thing that is drawn to the screen. The pixels[] array holds the pixel data of said image. */
    private BufferedImage screen = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    public int[] pixels = ((DataBufferInt) screen.getRaster().getDataBuffer()).getData();

    /* A Thread for running the game and two Booleans for being either in-game or in-menu. */
    private Thread thread;
    public static volatile boolean isRunning = false;
    public static volatile boolean inGame = false;

    /* Characters for determining what state the player is in, and what level is selected. (MAY CHANGE TO INT LATER!) */
    public static char state = 'N';
    public static int player_select = 0;
    public static int level_select = 0;

    /* The only non-local reference in this class. Used for creating the window. */
    JFrame frame;

    /* Imports having to do with the logic behind the game and then rendering. */
    Display display;
    UIListener listen;
    Keyboard key;
    Mouser mouse;
    Music music;

    /* The three main classes. */

    /**
     * The main constructor. It's responsible for creating the JFrame and adding this canvas to it. It also sets the level to a default selection.
     */
    public Game() {
            frame = new JFrame("Game");

            display = new Display(screen);
            key = new Keyboard(200);
            mouse = new Mouser();
            listen = new UIListener(mouse);

            setPlayer(PlayerClass.KNIGHT);
            setLevel(ClassicLevel.FLOOR_1);

            if (getLevel() == ClassicLevel.floor_1) {
                    getPlayer().setDirection(PlayerClass.NORTH);
            }

            setPreferredSize(size);
            setMaximumSize(size);
            setMinimumSize(size);
            addKeyListener(key);
            addMouseListener(mouse);

            frame.setLayout(new BorderLayout());
            frame.add(this, BorderLayout.CENTER);
            frame.pack();

            frame.setIconImage(new ImageIcon("res/Game_logo.png").getImage());
            frame.setLocationRelativeTo(null);
            frame.setResizable(false);
            frame.setVisible(true);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    /**
     * Responsible for starting the game, the most important part. It also requests the focus of the Canvas and creates a buffer strategy.
     */
    public synchronized void begin() {
            thread = new Thread(this, "Game");
            createBufferStrategy(3);
            requestFocus();

            thread.start();
            isRunning = true;
    }

    /**
     * Method responsible for stopping the thread that runs the game.
     *
     * @throws InterruptedException
     */
    public synchronized void finish() throws InterruptedException {
            isRunning = false;
            thread.join();
    }

    /* Integers that reflect the Keyboard's movements. Should not be removed. */
    int xMove = 0, yMove = 0;

    /**
     * This method is responsible for updating the logic behind the game, i.e. Mobs, time, AI, etc.
     */
    private synchronized void tick() {
            key.checkForKeys();
            int speed = getPlayer().getSpeed();

            if (key.up) {
                    yMove -= speed;
                    getPlayer().setDirection(PlayerClass.NORTH);
            }

            if (key.down) {
                    yMove += speed;
                    getPlayer().setDirection(PlayerClass.SOUTH);
            }

            if (key.left) {
                    xMove -= speed;
                    getPlayer().setDirection(PlayerClass.WEST);
            }

            if (key.right) {
                    xMove += speed;
                    getPlayer().setDirection(PlayerClass.EAST);
            }
    }

    /* Integers responsible for the FPS and UPS. */
    public int frames = 0, updates = 0;

    /**
     * Method responsible for rendering the logic in the "update()" method to the screen.
     */
    private synchronized void render() {
            BufferStrategy buffer = this.getBufferStrategy();
            Graphics gfx = buffer.getDrawGraphics();

            final int centerY = (HEIGHT / 2) - (48 / 2);
            final int centerX = (WIDTH / 2) - (48 / 2);

            display.clear();
            getLevel().render(xMove, yMove, display);
            display.renderPlayer(getPlayer(), centerX, centerY);

            display.alignPixels(pixels);

            gfx.drawImage(screen, 0, 0, getWidth(), getHeight(), null);
            gfx.drawImage(UIRender.playerBar(getPlayer().getIcon()), 0, getHeight() - 100, 200, 100, null);

            gfx.setFont(GameGUI.gameFont());
            gfx.setColor(new Color(220, 220, 220));
            gfx.drawString(Game.version, 3, 15);

            if (key.show) {
                    key.showInfo(gfx, frames, updates);
            } else if (key.escape) {
                    UIRender.renderEscapeMenu(this);
            }

            gfx.dispose();
            buffer.show();
    }

    public final void screenShot(String filename) throws Exception {
            Robot robot = new Robot();
            Rectangle window = new Rectangle(frame.getX(), frame.getY(), WIDTH * SCALE, HEIGHT * SCALE);
            BufferedImage image = robot.createScreenCapture(window);
            ImageIO.write(image, "png", new File(GAME_PATH + filename));
    }

    /**
     * Method responsible for setting the state of the game. (i.e. in options, in credits, etc.)
     *
     * @param setState
     */
    public static void setState(char setState) {
            state = setState;
    }

    /**
     * Sets the desired player for the game.
     *
     * @param selection
     */
    public static void setPlayer(int selection) {
            player_select = selection;
    }

    /**
     * Method for returning the player that the user has selected while in the class select.
     *
     * @return
     */
    public static PlayerClass getPlayer() {
            if (player_select == 1) return KnightClass.knight;
            if (player_select == 2) return WizardClass.wizard;
            if (player_select == 3) return ArcherClass.archer;

            return KnightClass.knight;
    }

    /**
     * Method responsible for setting the desired level of the user.
     *
     * @param selection
     */
    public static void setLevel(int selection) {
            level_select = selection;
    }

    /**
     * Method used for getting the level that the user picked.
     *
     * @return
     */
    private final Level getLevel() {
            if (level_select == ClassicLevel.FLOOR_1) return ClassicLevel.floor_1;
            return SurvivalLevel.level;
    }

    /**
     * The main "run()" method; needed for any class that implements the Runnable.java interface.
     */
    public void run() {
            long pastTime = System.nanoTime(), lastSecond = System.currentTimeMillis();

            final float desig = 1_000_000_000F / 50F;
            float single = 0;

            // Remove to play actual game.
            state = 50;

            if (state != 50) {
                    //Music.playTitleMusic();
            }

            while (isRunning == true) {
                    if (state == 'N') {
                            UIRender.renderNaprav(this);
                            if ((System.currentTimeMillis() - lastSecond) > 2000) {
                                    // Wait 2 seconds and then go to the menu.
                                    lastSecond += 1000;
                                    state = 'M';
                            }
                    } else if (state == 'M') {
                            UIRender.renderMenu(this);
                            listen.listenInMenu();
                    } else if (state == 'O') {
                            UIRender.renderOptions(this);
                            listen.listenInOptions();
                    } else if (state == 'C') {
                            UIRender.renderCredits(this);
                            listen.listenInCredits();
                    } else if (state == 'S') {
                            UIRender.renderClassSelect(this);
                            listen.listenInClassSelection();
                    } else if (state == 'L') {
                            UIRender.renderLevelSelect(this);
                            listen.listenInLevelSelection();
                    } else if (state == 'Q') {
                            System.exit(0);
                    } else {
                            inGame = true;
                            // Remember to comment out the code below when state is auto-equal to 50.
                            //Music.stopTitleMusic();
                            break;
                    }
            }

            while (inGame == true) {
                    long currentTime = System.nanoTime();
                    single += (currentTime - pastTime) / desig;

                    pastTime = currentTime;
                    while (single >= 1) {
                            tick();
                            updates++;
                            single--;
                    }

                    frames++;
                    render();

                    if ((System.currentTimeMillis() - lastSecond) > 1000) {
                            lastSecond += 1000;
                            frame.setTitle("Game | FPS: " + frames + ", UPS: " + updates);

                            frames = 0;
                            updates = 0;
                    }
            }
    }

    /**
     * The "main()" method; needed for every Java program.
     *
     * @param args
     */
    public static void main(String[] args) {
            //new Login();
            Game dungeon = new Game();
            dungeon.begin();
    }
}

Thanks in advance.


text:
Q: IQKeyBoardManager : Hide keyboard for a specific textfield In my app I have a form where the user fills out his/her information, the form has some textfields and amongst those is one where the user can select their country. This textfiled is a dropdown which when active displays a dropdown (tableview) with the list of countries to select. I have created a demo project, to reproduce the issue and share it here.
In this demo, I have add 3 textfields, when the user goes to the second textfiled, using the next button on the keyboard, a tableview is displayed. Now what I want to achieve is my keyboard should hide when the dropdown tableview is displayed.
I have put in quite some time trying to figure this out but has no success.
Here is the link to the demo project:
https://github.com/tejaskutal/IQKeyboardManagerDemo
Any help is greatly appretiated.
P.S: For some weird reason, when you click next when the first textfiled is active, it jumps to the third one first and then goes to second textfield after next is clicked one more time. However, this has nothing to do with the original problem so I left it there.

A: No need to handle different delegate. In your viewDidload you can do something like,
 yourTextField.inputView = UIView.init(frame: CGRect.zero)
 yourTextField.inputAccessoryView = UIView.init(frame: CGRect.zero)

so, for that textfield keyboard or toolbar will not be appeared.

A: You can use your UITextField's delegate and implement the textFieldShouldBeginEditing. Something like
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == theTextFieldToIgnore {
            view.endEditing(true)
            return false
        }
}

As for your textField chaining, you should implement the textFieldShouldReturn
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == firstOne {
            textField.resignFirstResponder()
            secondOne.becomeFirstResponder()
        }
        return true
    }

A: Return key Action which textfield you want to resign
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
        [self.yourTf resignFirstResponder];

}


text:
Q: Eclipse keeps crashing when running project My Eclipse keeps crashing when I run my project, and sometimes even the browser itself too.
I don't know why.
Here's the error I get:

What can I do to remedy this?


text:
Q: Strange behavior with extra tick style The extra y ticks at y = 6000 and y = 5400 and the extra x ticks at x = 24 and x = 20.4 are not drawn.
    \documentclass[border=10pt]{standalone}
    \usepackage{pgfplots}
    \usetikzlibrary{intersections}
    \usepgfplotslibrary{fillbetween}
    \pgfplotsset{major grid style={thick,darkgray}}
    \pgfplotsset{minor grid style={lightgray}}
    \begin{document}
    \begin{tikzpicture}[
     extended line/.style={shorten >=-#1,shorten <=-#1},
    /pgf/declare function={f(\x)=  1000*(\x +5)*exp(-0.2*\x);}]
    \begin{axis}[
         restrict x to domain=0:22, xmax=22, xmin=0,
         restrict y to domain=0:6000, ymax=6000, ymin=0,
         x=0.6cm,
         y=0.0012cm,
         axis x line=bottom,
         axis y line=left,
         major tick style=black,
         axis line style = ultra thick,
         tick align=outside,
         tickwidth=0.14cm,
         tick style=thick,
         minor x tick num=4,
         minor y tick num=4,
         grid=both,
         xtick={0,2,...,20},
         ytick={0,1000,...,5000},
         y tick label style={/pgf/number format/1000 sep={}},
         extra x ticks={20.4,20.8,21.2,21.6,22},
         extra x tick label={\null},
         extra y ticks={5200,5400,5600,5800,6000},
         extra y tick label={\null},
         extra x tick style={grid=minor,tick style={draw=none}},
         extra y tick style={grid=minor,tick style={draw=none}},
         xlabel=$x$,ylabel=$f(x)$,
         every axis x label/.style={
         at={(ticklabel* cs:1.01)},anchor=west},
         every axis y label/.style={
         at={(ticklabel* cs:1.01)}, anchor=south},
         samples=3000,
         axis on top=false,
         >=stealth,
         ]
        \addplot [ultra thick,domain=0:20] {f(x)};
        \end{axis}
        \end{tikzpicture}
        \end{document}

A: if i understood correctly what you like to achieve, than you not need extra ticks. you only need to define tick labels accordingly:
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{intersections}
\usepgfplotslibrary{fillbetween}

\pgfplotsset{major grid style={thick,darkgray}}
\pgfplotsset{minor grid style={lightgray}}
\begin{document}
\begin{tikzpicture}[
 extended line/.style={shorten >=-#1,shorten <=-#1},
/pgf/declare function={f(\x)=  1000*(\x +5)*exp(-0.2*\x);}]
\begin{axis}[
     xmax=22, xmin=0,
     ymax=6000, ymin=0,
     x=0.6cm,
     y=0.0012cm,
     axis x line=bottom,
     axis y line=left,
     major tick style=black,
     axis line style = ultra thick,
     tick align=outside,
     tickwidth=0.14cm,
     tick style=thick,
     minor x tick num=4,
     xtick={0,2,...,22},
     xticklabels = {0,2,...,20,},         % <----
     ytick={0,1000,...,6000},
     yticklabels={0,1000,2000,...,5000,},  % <----
     xlabel=$x$,ylabel=$f(x)$,
     minor y tick num=4,
     grid,
     samples=40,
     >=stealth,
     ]
    \addplot [ultra thick,domain=0:20] {f(x)};
    \end{axis}
    \end{tikzpicture}
    \end{document}

A: xtick={0,2,...,22},
         ytick={0,1000,...,6000} should allow what you need
unrelated to your question add also \pgfplotsset{compt=1.15} int the preamble
\documentclass[border=10pt]{standalone}
 \usepackage{pgfplots}
 \usetikzlibrary{intersections}
  \usepgfplotslibrary{fillbetween}
  \pgfplotsset{compt=1.15} % <-------
  \pgfplotsset{major grid style={thick,darkgray}}
  \pgfplotsset{minor grid style={lightgray}}
\begin{document}
\begin{tikzpicture}[
 extended line/.style={shorten >=-#1,shorten <=-#1},
/pgf/declare function={f(\x)=  1000*(\x +5)*exp(-0.2*\x);}]
\begin{axis}[
     restrict x to domain=0:22, xmax=22, xmin=0,
     restrict y to domain=0:6000, ymax=6000, ymin=0,
     x=0.6cm,
     y=0.0012cm,
     axis x line=bottom,
     axis y line=left,
     major tick style=black,
     axis line style = ultra thick,
     tick align=outside,
     tickwidth=0.14cm,
     tick style=thick,
     minor x tick num=4,
     minor y tick num=4,
     grid=both,
     xtick={0,2,...,22}, % <--------
     ytick={0,1000,...,6000}, % <-----------
     y tick label style={/pgf/number format/1000 sep={}},
     extra x ticks={20.4,20.8,21.2,21.6,22},
     extra x tick label={\null},
     extra y ticks={5200,5400,5600,5800,6000},
     extra y tick label={\null},
     extra x tick style={grid=minor,tick style={draw=none}},
     extra y tick style={grid=minor,tick style={draw=none}},
     xlabel=$x$,ylabel=$f(x)$,
     every axis x label/.style={
     at={(ticklabel* cs:1.01)},anchor=west},
     every axis y label/.style={
     at={(ticklabel* cs:1.01)}, anchor=south},
     samples=3000,
     axis on top=false,
     >=stealth,
     ]
    \addplot [ultra thick,domain=0:20] {f(x)};
    \end{axis}
    \end{tikzpicture}
    \end{document}


text:
Q: Using Polymer in a Dart Chrome App I am trying to build an app with Dart and Polymer. But polymer scripts seem to be using eval() in web_components/platform.js:32. Has anyone managed to do this? I tried to change CSP but that helped in first place.
Does anyone have a working example?
Regards and Thanks
Robert
EDIT
manifest.json:
{
  "name": "Animatr app",
  "version": "1",

  "author": "Robert Hartung",

  "manifest_version": 2,

  "icons": {"128": "animatr_icon.png"},

  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },

  "content_security_policy": "script-src 'self' unsafe-inline;"
}

main.html:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Animatr app</title>
    <link rel="stylesheet" href="animatr_chrome_app.css">
    <link rel="import" href="packages/polymer/polymer.html">
  </head>
  <body>

    <script src="packages/chrome/bootstrap.js" defer></script>
    <script src="my_chrome_app.dart" type="application/dart;component=1"></script>
  </body>
</html>

ERROR:
Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback. (chrome-extension://ofkfcbfhgkoglbgldcdokficikimdjji/packages/web_components/platform.js:32)
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

pubspec.yaml:
name: animatr_app
description: A sample Chrome packaged application
dependencies:
  chrome: any
  polymer: any
transformers:
- chrome
- polymer:
    entry_points:
    - app/animatr_chrome_app.html
    csp: 'true'

The app does not recognize polymer elements correctly.

A: I have been struggling with the same issue, trying to run the simple wizard generated polymer app (the one with the counter) as a chrome packaged app.
I have finally managed to at least run the javascript built version of it, trying to understand the csp issues.
For many reason, it sounds like it cannot run native as the packaged app is loaded from the file system and not through pub serve. Loading the unpackaged extension from web/build was not working neither as is. The solution was to load xxx.html_bootstrap.dart.precompiled.js instead of xxx.html_bootstrap.js from the generated html file
What i did was:

*

*remove the chrome transformer as the polymer transformer already replace the dart script reference by a javascript script reference

*add csp: true in the polymer transformer option (although it did work without it)

*to avoid having to change manually the generated html to load the precompiled.js version, I wrote a simple transformer.

*I can then load in Chrome (does not have to be Dartium as it is javascript) the unpacked extension from web/build once I run pub build (release mode needed)

I now simply have this warning:
Deprecation: Automatic generation of output for Content Security
Policy is deprecated and will be removed with the next development
release. Use the --csp option to generate CSP restricted output.

which means likely I would have to find a new hack soon...

A: You can take a look at https://github.com/dart-lang/spark/tree/master/ide for an example Dart Chrome-Packaged-App. They also make heavily use of Polymer.
Maybe this is related https://github.com/Polymer/polymer/issues/252
It seems this is the related Dart bug https://code.google.com/p/dart/issues/detail?id=17409


text:
Q: Cannot add edit themes and add plugins after multisite update After updating a multisite installation to WP 3.8, when in the My Sites Dashboard, hovering over "Themes" or "Plugins", no submenu pops out.
There are however submenus popping out of "Sites", "Users", and "Settings".
I found advice elsewhere to disable plugins one by one, and make sure a standard theme is being used. However, with a multisite installation I suppose there is no way to make sure a standard theme is being used (unless all sites are changed to that theme).
Any ideas how to understand and fix this situation?
Is there anywhere to locate an error message?
I should mention that one of the sites is using a private plugin that I wrote, but it does not seem to have any problems as far as I can tell.

A: This is a wildshot but generally this happens when the correct version of jQuery is not loading for the dashboard.
While logged in you could check this in your browser. I.e. in Chrome right click and choose inspect element - go to the console tab and see if there are any undefined errors thrown this will confirm the issue.
Or, in the Elements tab search for jQuery and ensure the correct version is loaded.
WP 3.9 should have jQuery V1.11.0
WP 3.8 should have jQuery V1.10.2
We can further help confirm JS is the error by placing: define('SCRIPT_DEBUG', true); in your wp-config file in the root of your install and see if your issue "goes away".


text:
Q: Identify Xpath in a dynamic table using xpath axes tableenter image description hereI want to write an xpath using axes for the a column value in the table, corresponding to a particular value in the same row.
e.g. I want to print last column value for HDIL.
Xpath that i have tried :
//a[contains (text(), 'HDIL')]/following-sibling::td[@class='green']

HTML

                    HDIL

                    A
                    564.6
                    68.8
                +   6.1

A: You may find 'table row' with text = 'HDIL' and from this row get the last table cell. E.g. like this:
//tr[td[contains(string(), 'HDIL')]]/td[last()]

or
//tr[td[contains(string(), 'HDIL')]]/td[font]

Or using webDriver I would find all cells for needed row and get the last one:
// C# code;
var lastCell = driver.FindElements(By.XPath("//tr[td[contains(string(), 'HDIL')]]/td")).Last();

A: Your xpath is written in the way of taking siblings from a but you should take siblings of td that contains a. Your xpath also implies that class='green' is the attribute of td but in fact (according to your example) it is the attribute of font that is child of td.
So the proper xpath would be: //td[a[contains (text(), 'HDIL')]]/following-sibling::td[font[@class='green']].
See test here.