Programs & Examples On #Suds

Suds is a SOAP services library for Python & JavaScript.

pip install failing with: OSError: [Errno 13] Permission denied on directory

If you need permissions, you cannot use 'pip' with 'sudo'. You can do a trick, so that you can use 'sudo' and install package. Just place 'sudo python -m ...' in front of your pip command.

sudo python -m pip install --user -r package_name

How can I consume a WSDL (SOAP) web service in Python?

Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.

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.

'tsc command not found' in compiling typescript

None of above answer solve my problem. The fact is that my project did not have type script installed. But locally I had run npm install -g typescript. So I did not notice that typescript node dependency was not in my package json.

When I pushed it to server side, and run npm install, then npx tsc I get a tsc not found. In facts remote server did not have typescript installed. That was hidden because of my local global typescript install.

Replace Fragment inside a ViewPager

I found simple solution, which works fine even if you want add new fragments in the middle or replace current fragment. In my solution you should override getItemId() which should return unique id for each fragment. Not position as by default.

There is it:

public class DynamicPagerAdapter extends FragmentPagerAdapter {

private ArrayList<Page> mPages = new ArrayList<Page>();
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();

public DynamicPagerAdapter(FragmentManager fm) {
    super(fm);
}

public void replacePage(int position, Page page) {
    mPages.set(position, page);
    notifyDataSetChanged();
}

public void setPages(ArrayList<Page> pages) {
    mPages = pages;
    notifyDataSetChanged();
}

@Override
public Fragment getItem(int position) {
    if (mPages.get(position).mPageType == PageType.FIRST) {
        return FirstFragment.newInstance(mPages.get(position));
    } else {
        return SecondFragment.newInstance(mPages.get(position));
    }
}

@Override
public int getCount() {
    return mPages.size();
}

@Override
public long getItemId(int position) {
    // return unique id
    return mPages.get(position).getId();
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    while (mFragments.size() <= position) {
        mFragments.add(null);
    }
    mFragments.set(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    super.destroyItem(container, position, object);
    mFragments.set(position, null);
}

@Override
public int getItemPosition(Object object) {
    PagerFragment pagerFragment = (PagerFragment) object;
    Page page = pagerFragment.getPage();
    int position = mFragments.indexOf(pagerFragment);
    if (page.equals(mPages.get(position))) {
        return POSITION_UNCHANGED;
    } else {
        return POSITION_NONE;
    }
}
}

Notice: In this example FirstFragment and SecondFragment extends abstract class PageFragment, which has method getPage().

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

How do I clone a generic list in C#?

I use automapper to copy an object. I just setup a mapping that maps one object to itself. You can wrap this operation any way you like.

http://automapper.codeplex.com/

Responsive design with media query : screen size?

Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience

When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.

If you want to style your site per device, you can use the user agent value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.

You can see some standard resolutions in this link.

BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.

Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.

TIPS

  1. When designing a responsive page, open it in your desktop browser and change the width of the browser to see how the width of the screen affects your layout and style.
  2. Use percentage instead of pixels, it will make your work easier.

Example

I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.


State of mind

Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.

Declaring variables inside loops, good practice or bad practice?

Since your second question is more concrete, I'm going to address it first, and then take up your first question with the context given by the second. I wanted to give a more evidence-based answer than what's here already.

Question #2: Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?

You can answer this question for yourself by stopping your compiler before the assembler is run and looking at the asm. (Use the -S flag if your compiler has a gcc-style interface, and -masm=intel if you want the syntax style I'm using here.)

In any case, with modern compilers (gcc 10.2, clang 11.0) for x86-64, they only reload the variable on each loop pass if you disable optimizations. Consider the following C++ program—for intuitive mapping to asm, I'm keeping things mostly C-style and using an integer instead of a string, although the same principles apply in the string case:

#include <iostream>

static constexpr std::size_t LEN = 10;

void fill_arr(int a[LEN])
{
    /* *** */
    for (std::size_t i = 0; i < LEN; ++i) {
        const int t = 8;

        a[i] = t;
    }
    /* *** */
}

int main(void)
{
    int a[LEN];

    fill_arr(a);

    for (std::size_t i = 0; i < LEN; ++i) {
        std::cout << a[i] << " ";
    }

    std::cout << "\n";

    return 0;
}

We can compare this to a version with the following difference:

    /* *** */
    const int t = 8;

    for (std::size_t i = 0; i < LEN; ++i) {
        a[i] = t;
    }
    /* *** */

With optimization disabled, gcc 10.2 puts 8 on the stack on every pass of the loop for the declaration-in-loop version:

    mov QWORD PTR -8[rbp], 0
.L3:
    cmp QWORD PTR -8[rbp], 9
    ja  .L4
    mov DWORD PTR -12[rbp], 8 ;?

whereas it only does it once for the out-of-loop version:

    mov DWORD PTR -12[rbp], 8 ;?
    mov QWORD PTR -8[rbp], 0
.L3:
    cmp QWORD PTR -8[rbp], 9
    ja  .L4

Does this make a performance impact? I didn't see an appreciable difference in runtime between them with my CPU (Intel i7-7700K) until I pushed the number of iterations into the billions, and even then the average difference was less than 0.01s. It's only a single extra operation in the loop, after all. (For a string, the difference in in-loop operations is obviously a bit greater, but not dramatically so.)

What's more, the question is largely academic, because with an optimization level of -O1 or higher gcc outputs identical asm for both source files, as does clang. So, at least for simple cases like this, it's unlikely to make any performance impact either way. Of course, in a real-world program, you should always profile rather than make assumptions.

Question #1: Is declaring a variable inside a loop a good practice or bad practice?

As with practically every question like this, it depends. If the declaration is inside a very tight loop and you're compiling without optimizations, say for debugging purposes, it's theoretically possible that moving it outside the loop would improve performance enough to be handy during your debugging efforts. If so, it might be sensible, at least while you're debugging. And although I don't think it's likely to make any difference in an optimized build, if you do observe one, you/your pair/your team can make a judgement call as to whether it's worth it.

At the same time, you have to consider not only how the compiler reads your code, but also how it comes off to humans, yourself included. I think you'll agree that a variable declared in the smallest scope possible is easier to keep track of. If it's outside the loop, it implies that it's needed outside the loop, which is confusing if that's not actually the case. In a big codebase, little confusions like this add up over time and become fatiguing after hours of work, and can lead to silly bugs. That can be much more costly than what you reap from a slight performance improvement, depending on the use case.

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

If you use

android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"

in your AndroidManifest.xml file for the Activity to launch, you have to use the following in your intent:

Intent notificationClick = new Intent(context, NotifyActivity.class);
    Bundle bdl = new Bundle();
    bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
    notificationClick.putExtras(bdl);
    notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
    notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);  // schließt tasks der app und startet einen seperaten neuen

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NotifyActivity.class);
    stackBuilder.addNextIntent(notificationClick);

    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(notificationPendingIntent);

Important is to set unique data e.g. using an unique id like:

notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));

Gradle proxy configuration

For me, works adding this configuration in the gradle.properties file of the project, where the build.gradle file is:

systemProp.http.proxyHost=proxyURL
systemProp.http.proxyPort=proxyPort
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PASSWORD
systemProp.https.proxyHost=proxyUrl 
systemProp.https.proxyPort=proxyPort
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PASSWORD

Where : proxyUrl is the url of the proxy server (http://.....)

proxyPort is the port (usually 8080)

USER is my domain user

PASSWORD, my password

In this case, the proxy for http and https is the same

Combining INSERT INTO and WITH/CTE

The WITH clause for Common Table Expressions go at the top.

Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.

Spot the mistake:

WITH _INSERT_ AS (
  SELECT
    [BatchID]      = blah
   ,[APartyNo]     = blahblah
   ,[SourceRowID]  = blahblahblah
  FROM Table1 AS t1
)
INSERT Table2
      ([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]   
FROM _INSERT_

Same mistake:

INSERT Table2 (
  [BatchID]
 ,[SourceRowID]
 ,[APartyNo]
)
SELECT
  [BatchID]      = blah
 ,[APartyNo]     = blahblah
 ,[SourceRowID]  = blahblahblah
FROM Table1 AS t1

A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.

Best way to detect when a user leaves a web page?

Mozilla Developer Network has a nice description and example of onbeforeunload.

If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):

window.addEventListener('beforeunload', function(e) {
  var myPageIsDirty = ...; //you implement this logic...
  if(myPageIsDirty) {
    //following two lines will cause the browser to ask the user if they
    //want to leave. The text of this dialog is controlled by the browser.
    e.preventDefault(); //per the standard
    e.returnValue = ''; //required for Chrome
  }
  //else: user is allowed to leave without a warning dialog
});

How to delete shared preferences data from App in Android

The Kotlin ktx way to clear all preferences:

val prefs: SharedPreferences = getSharedPreferences("prefsName", Context.MODE_PRIVATE)
prefs.edit(commit = true) {
    clear()
}

Click here for all Shared preferences operations with examples

What Does This Mean in PHP -> or =>

=> is used in associative array key value assignment. Take a look at:

http://php.net/manual/en/language.types.array.php.

-> is used to access an object method or property. Example: $obj->method().

Removing Duplicate Values from ArrayList

List<String> list = new ArrayList<String>();
        list.add("Krishna");
        list.add("Krishna");
        list.add("Kishan");
        list.add("Krishn");
        list.add("Aryan");
        list.add("Harm");

HashSet<String> hs=new HashSet<>(list);

System.out.println("=========With Duplicate Element========");
System.out.println(list);
System.out.println("=========Removed Duplicate Element========");
System.out.println(hs);

Format date as dd/MM/yyyy using pipes

If anyone looking with time and timezone, this is for you

 {{data.ct | date :'dd-MMM-yy h:mm:ss a '}}

add z for time zone at the end of date and time format

 {{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}

Add/remove class with jquery based on vertical scroll?

Here's pure javascript example of handling classes during scrolling.

You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle from lodash lib comes in handy.

And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener once they're not needed (eg during onDestroy lifecycle hook of your component, like destroyed() for Vue, or maybe return function of useEffect hook for React).

_x000D_
_x000D_
const navbar = document.getElementById('navbar')_x000D_
_x000D_
// OnScroll event handler_x000D_
const onScroll = () => {_x000D_
_x000D_
  // Get scroll value_x000D_
  const scroll = document.documentElement.scrollTop_x000D_
_x000D_
  // If scroll value is more than 0 - add class_x000D_
  if (scroll > 0) {_x000D_
    navbar.classList.add("scrolled");_x000D_
  } else {_x000D_
    navbar.classList.remove("scrolled")_x000D_
  }_x000D_
}_x000D_
_x000D_
// Optional - throttling onScroll handler at 100ms with lodash_x000D_
const throttledOnScroll = _.throttle(onScroll, 100, {})_x000D_
_x000D_
// Use either onScroll or throttledOnScroll_x000D_
window.addEventListener('scroll', onScroll)
_x000D_
#navbar {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  width: 100%;_x000D_
  height: 60px;_x000D_
  background-color: #89d0f7;_x000D_
  box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);_x000D_
  transition: box-shadow 500ms;_x000D_
}_x000D_
_x000D_
#navbar.scrolled {_x000D_
  box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
#content {_x000D_
  height: 3000px;_x000D_
  margin-top: 60px;_x000D_
}
_x000D_
<!-- Optional - lodash library, used for throttlin onScroll handler-->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>_x000D_
<header id="navbar"></header>_x000D_
<div id="content"></div>
_x000D_
_x000D_
_x000D_

Why should I use core.autocrlf=true in Git?

Update 2:

Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.

I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.

For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false), and led to many "EOL" commit messages and eventually to my writing a git pre-commit hook to check for/prevent introducing mixed line endings.

Update:

Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.

Original:

One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:

// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>

This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.

The other thing* we've found, is that when using git diff to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:

    // Not changed

+   // New line added in^M
+^M
    // Not changed
    // Not changed

* It doesn't really merit the term: "issue".

A hex viewer / editor plugin for Notepad++?

There is an old plugin called HEX Editor here.

According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.

How to merge two PDF files into one in Java?

Why not use the PDFMergerUtility of pdfbox?

PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource(...);
ut.addSource(...);
ut.addSource(...);
ut.setDestinationFileName(...);
ut.mergeDocuments();

Creating a Custom Event

Yes you can create events on objects, here is an example;

public class Foo
{
    public delegate void MyEvent(object sender, object param);
    event MyEvent OnMyEvent;

    public Foo()
    {
        this.OnMyEvent += new MyEvent(Foo_OnMyEvent);
    }

    void Foo_OnMyEvent(object sender, object param)
    {
        if (this.OnMyEvent != null)
        {
            //do something
        }
    }



    void RaiseEvent()
    {
        object param = new object();
        this.OnMyEvent(this,param);
    }
}

Printing Even and Odd using two Threads in Java

Use this following very simple JAVA 8 Runnable Class feature

public class MultiThreadExample {

static AtomicInteger atomicNumber = new AtomicInteger(1);

public static void main(String[] args) {
    Runnable print = () -> {
        while (atomicNumber.get() < 10) {
            synchronized (atomicNumber) {
                if ((atomicNumber.get() % 2 == 0) && "Even".equals(Thread.currentThread().getName())) {
                    System.out.println("Even" + ":" + atomicNumber.getAndIncrement());
                } else if ((atomicNumber.get() % 2 != 0) && "Odd".equals(Thread.currentThread().getName())) {
                    System.out.println("Odd" + ":" + atomicNumber.getAndIncrement());
                }
            }
        }
    };

    Thread t1 = new Thread(print);
    t1.setName("Even");
    t1.start();
    Thread t2 = new Thread(print);
    t2.setName("Odd");
    t2.start();

}
}

Confirm postback OnClientClick button ASP.NET

You can put the above answers into one line like this. And you don't need to write the function.

    <asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
         OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1"
OnClientClick="if ( !confirm('Are you sure you want to delete this user?')) return false;"  />

Convert number to month name in PHP

This is how I did it

// sets Asia/Calcutta time zone
date_default_timezone_set("Asia/Calcutta");

//fetches current date and time
$date = date("Y-m-d H:i:s");

$dateArray = date_parse_from_format('Y/m/d', $date);
$month = DateTime::createFromFormat('!m', $dateArray['month'])->format('F');
$dateString = $dateArray['day'] . " " . $month  . " " . $dateArray['year'];

echo $dateString;

returns 30 June 2019

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

How to set column widths to a jQuery datatable?

In java script calculate width using following code

var scrollX = $(window).width()*58/100;
var oTable = $('#reqAllRequestsTable').dataTable({
    "sScrollX": scrollX
    } );

The difference between the Runnable and Callable interfaces in Java

Let us look at where one would use Runnable and Callable.

Runnable and Callable both run on a different thread than the calling thread. But Callable can return a value and Runnable cannot. So where does this really apply.

Runnable : If you have a fire and forget task then use Runnable. Put your code inside a Runnable and when the run() method is called, you can perform your task. The calling thread really does not care when you perform your task.

Callable : If you are trying to retrieve a value from a task, then use Callable. Now callable on its own will not do the job. You will need a Future that you wrap around your Callable and get your values on future.get (). Here the calling thread will be blocked till the Future comes back with results which in turn is waiting for Callable's call() method to execute.

So think about an interface to a target class where you have both Runnable and Callable wrapped methods defined. The calling class will randomly call your interface methods not knowing which is Runnable and which is Callable. The Runnable methods will execute asynchronously, till a Callable method is called. Here the calling class's thread will block since you are retrieving values from your target class.

NOTE : Inside your target class you can make the calls to Callable and Runnable on a single thread executor, making this mechanism similar to a serial dispatch queue. So as long as the caller calls your Runnable wrapped methods the calling thread will execute really fast without blocking. As soon as it calls a Callable wrapped in Future method it will have to block till all the other queued items are executed. Only then the method will return with values. This is a synchronization mechanism.

How to make a owl carousel with arrows instead of next previous

If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.

$('.your-class').owlCarousel({
        loop: true,
        items: 1, // Select Item Number
        autoplay:true,
        dots: false,
        nav: true,
        navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],

    });

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

Git vs Team Foundation Server

I think, the statement

everyone hates it except me

makes any further discussion waste: when you keep using Git, they will blame you if anything goes wrong.

Apart from this, for me Git has two advantages over a centralized VCS that I appreciate most (as partly described by Rob Sobers):

  • automatic backup of the whole repo: everytime someone pulls from the central repo, he/she gets a full history of the changes. When one repo gets lost: don't worry, take one of those present on every workstation.
  • offline repo access: when I'm working at home (or in an airplane or train), I can see the full history of the project, every single checkin, without starting up my VPN connection to work and can work like I were at work: checkin, checkout, branch, anything.

But as I said: I think that you're fighting a lost battle: when everyone hates Git, don't use Git. It could help you more to know why they hate Git instead of trying them to convince them.

If they simply don't want it 'cause it's new to them and are not willing to learn something new: are you sure that you will do successful development with that staff?

Does really every single person hate Git or are they influenced by some opinion leaders? Find the leaders and ask them what's the problem. Convince them and you'll convince the rest of the team.

If you cannot convince the leaders: forget about using Git, take the TFS. Will make your life easier.

Show SOME invisible/whitespace characters in Eclipse

Navigate to Window > Preferences > General > Editors > Text Editors

Click on the CheckBox "Show whitespace characters".

enter image description here

Thats all.!!!

How to get last key in an array?

Since PHP 7.3 (2018) there is (finally) function for this: http://php.net/manual/en/function.array-key-last.php

$array = ['apple'=>10,'grape'=>15,'orange'=>20];
echo array_key_last ( $array )

will output

orange

How do you create a Swift Date object?

According to Apple documentation

Example :

var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow

How to get disk capacity and free space of remote computer

Get-PSDrive C | Select-Object @{ E={$_.Used/1GB}; L='Used' }, @{ E={$_.Free/1GB}; L='Free' }

git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

https://twitter.com/Beanstalkapp/status/306129447885631488

How to call a method in MainActivity from another class?

You can make this method static.

public static void startChronometer(){
        mChronometer.start();
        showElapsedTime();
    } 

you can call this function in other class as below:

MainActivity.startChronometer();

OR

You can make an object of the main class in second class like,

MainActivity mActivity = new MainActivity();
mActivity.startChronometer();

rewrite a folder name using .htaccess

try:

RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.

See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/

There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php

to redirect from /folder1 to /apple try this:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]

to redirect and then rewrite just combine the above in the htaccess file:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

One thing that might not always be obvious to some is that a cross join with an empty table (or result set) results in empty table (M x N; hence M x 0 = 0)

A full outer join will always have rows unless both M and N are 0.

What is the difference between x86 and x64

x86 is for a 32-bit OS, and x64 is for a 64-bit OS

Difference between app.use and app.get in express.js

Difference between app.use & app.get:

app.use ? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.

app.get ? It is only for handling GET HTTP requests.

Now, there is a confusion between app.use & app.all. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests. But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.

  1. app.use() ? It takes only one callback.
    app.all() ? It can take multiple callbacks.

  2. app.use() will only see whether url starts with specified path.
    But, app.all() will match the complete path.

For example,

app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject

app.all( "/book" , handler);
// will match /book
// won't match /book/author   
// won't match /book/subject    

app.all( "/book/*" , handler);
// won't match /book        
// will match /book/author
// will match /book/subject
  1. next() call inside the app.use() will call either the next middleware or any route handler, but next() call inside app.all() will invoke the next route handler (app.all(), app.get/post/put... etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.

php $_POST array empty upon form submission

My problem was that I was using the HTML <base> tag to change the base URL of my test site. Once I removed that tag from the header, the $_POST data came back.

Add to python path mac os x

Modifications to sys.path only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH environment variable:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

Note that PATH is the system path for executables, which is completely separate.

**You can write the above in ~/.bash_profile and the source it using source ~/.bash_profile

TypeError: '<=' not supported between instances of 'str' and 'int'

If you're using Python3.x input will return a string,so you should use int method to convert string to integer.

Python3 Input

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

By the way,it's a good way to use try catch if you want to convert string to int:

try:
  i = int(s)
except ValueError as err:
  pass 

Hope this helps.

How to add class active on specific li on user click with jQuery

You specified both jQuery and Javascript in the tags so here's both approaches.

jQuery

var selector = '.nav li';

$(selector).on('click', function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

Fiddle: http://jsfiddle.net/bvf9u/


Pure Javascript:

var selector, elems, makeActive;

selector = '.nav li';

elems = document.querySelectorAll(selector);

makeActive = function () {
    for (var i = 0; i < elems.length; i++)
        elems[i].classList.remove('active');

    this.classList.add('active');
};

for (var i = 0; i < elems.length; i++)
    elems[i].addEventListener('mousedown', makeActive);

Fiddle: http://jsfiddle.net/rn3nc/1


jQuery with event delegation:

Please note that in approach 1, the handler is directly bound to that element. If you're expecting the DOM to update and new lis to be injected, it's better to use event delegation and delegate to the next element that will remain static, in this case the .nav:

$('.nav').on('click', 'li', function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
});

Fiddle: http://jsfiddle.net/bvf9u/1/

The subtle difference is that the handler is bound to the .nav now, so when you click the li the event bubbles up the DOM to the .nav which invokes the handler if the element clicked matches your selector argument. This means new elements won't need a new handler bound to them, because it's already bound to an ancestor.

It's really quite interesting. Read more about it here: http://api.jquery.com/on/

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

How to install the Six module in Python2.7

You need to install this

https://pypi.python.org/pypi/six

If you still don't know what pip is , then please also google for pip install

Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/

Twitter bootstrap float div right

bootstrap 3 has a class to align the text within a div

<div class="text-right">

will align the text on the right

<div class="pull-right">

will pull to the right all the content not only the text

Update query with PDO and MySQL

Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

$sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";

Java Singleton and Synchronization

Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:

Draconian synchronization:

private static YourObject instance;

public static synchronized YourObject getInstance() {
    if (instance == null) {
        instance = new YourObject();
    }
    return instance;
}

This solution requires that every thread be synchronized when in reality only the first few need to be.

Double check synchronization:

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

Initialization on Demand:

private static class InstanceHolder {
    private static final YourObject instance = new YourObject();
}

public static YourObject getInstance() {
    return InstanceHolder.instance;
}

This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.

How to select the first, second, or third element with a given class name?

This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.

I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type which, for my situation, worked. (So, thanks for that, @Bdwey.)

I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.

Turns out as follows: div.myclass:nth-of-type(2) does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening divs between your div.myclass instances.

It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1, h2, h3 and h4 elements to essentially be divs. I've put an A class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?). (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h level) or similar (i.e. same h level) un-classed element into some of the groups.

Note, in particular, the last grouping of 3. Here, an un-classed h3 element is inserted between the first and second h3.A elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A. This shows that the n in h3.A:nth-of-type(n) is counting the h3s, not the h3.As.

Well, hope that helps. And thanks, @BoltClock.

_x000D_
_x000D_
div {_x000D_
  margin-bottom: 2em;_x000D_
  border: red solid 1px;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
  font-size: 12pt;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
  background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
  background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
  <h1 class="A">h1.A #1</h1>_x000D_
  <h1 class="A">h1.A #2</h1>_x000D_
  <h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h2 class="A">h2.A #1</h2>_x000D_
  <h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
  <h2 class="A">h2.A #2</h2>_x000D_
  <h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h3 class="A">h3.A #1</h3>_x000D_
  <h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
  <h3 class="A">h3.A #2</h3>_x000D_
  <h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In where shall I use isset() and !empty()

I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the @ prefix you can safely check if is not empty and avoid the notice if the var is not set:

if( isset($_GET['var']) && @$_GET['var']!='' ){
    //Is not empty, do something
}

How to insert &nbsp; in XSLT

XSLT stylesheets must be well-formed XML. Since "&nbsp;" is not one of the five predefined XML entities, it cannot be directly included in the stylesheet. So coming back to your solution "&#160;" is a perfect replacement of "&nbsp;" you should use.

Example:

<xsl:value-of select="$txtFName"/>&#160;<xsl:value-of select="$txtLName"/>

How to apply multiple transforms in CSS?

You have to put them on one line like this:

li:nth-child(2) {
    transform: rotate(15deg) translate(-20px,0px);
}

When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.


Keep in mind multiple transform one line directives are applied from right to left.

This: transform: scale(1,1.5) rotate(90deg);
and: transform: rotate(90deg) scale(1,1.5);

will not produce the same result:

_x000D_
_x000D_
.orderOne, .orderTwo {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 22px;_x000D_
  color: #000;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.orderOne {_x000D_
  transform: scale(1, 1.5) rotate(90deg);_x000D_
}_x000D_
_x000D_
.orderTwo {_x000D_
  transform: rotate(90deg) scale(1, 1.5);_x000D_
}
_x000D_
<div class="orderOne">_x000D_
  A_x000D_
</div>_x000D_
_x000D_
<div class="orderTwo">_x000D_
  A_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get ID of button user just clicked?

With pure javascript:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
    };
}?

http://jsfiddle.net/TKKBV/2/

Angular-Material DateTime Picker Component?

For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.

I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:

When no input has been given yet, I would advise:

  • On-click of the component, the datepicker should always be triggered first.
  • After the datepicker closes, have the timepicker automatically popup.
  • Use touchUi = true on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.
  • Make sure the datepicker also shows up when clicking on the form (instead of only on the icon which is the default).
  • Use this solution to use the timepicker also in a material form, when placing them behind each other, it looks like it is one form.

After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.

My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.

Edit: Result

enter image description here

<div fxLayout="row">
  <div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
    <mat-form-field>
      <input matInput [ngxTimepicker]="endTime" [format]="24"  placeholder="{{placeholderTime}}" formControlName="endTime" />
    </mat-form-field>
    <ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
  </div>
  <div>
    <mat-form-field>
      <input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
             [min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
    </mat-form-field>
  </div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';

import * as moment_ from 'moment';

const moment = moment_;

import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

class DateConfig {
  startView: 'month' | 'year' | 'multi-year';
  touchUi: boolean;
  minDate: moment_.Moment;
  maxDate: moment_.Moment;
}

@Component({
  selector: 'cb-datetimepicker',
  templateUrl: './cb-datetimepicker.component.html',
  styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {

  @Input() disabled: boolean;
  @Input() placeholderDate: string;
  @Input() placeholderTime: string;
  @Input() model: Date;
  @Input() purpose: string;
  @Input() dateOnly: boolean;

  @Output() dateUpdate = new EventEmitter<Date>();

  public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);

  public dateForm: FormControl;
  public timeFormGroup: FormGroup;
  public endTime: FormControl;

  public momentDate: moment_.Moment;
  public config: DateConfig;

  //myGroup: FormGroup;


  constructor(private adapter : DateAdapter<any>) { }

  ngOnInit() {

    this.adapter.setLocale("nl-NL");//todo: configurable
    this.config = new DateConfig();
    if (this.purpose === "birthday") {
      this.config.startView = 'multi-year';
      this.config.maxDate = moment().add('year', -15);
      this.config.minDate = moment().add('year', -90);
      this.dateOnly = true;
    } //add more configurations
    else {
      this.config.startView = 'month';
      this.config.maxDate = moment().add('year', 100);
      this.config.minDate = moment().add('year', -100);
    }


    if (window.screen.width < 767) {
      this.config.touchUi = true;
    }



    if (this.model) {
      var mom = moment(this.model);
      if (mom.isBefore(moment('1900-01-01'))) {
        this.momentDate = moment();
      } else {
        this.momentDate = mom;
      }
    } else {
      this.momentDate = moment();
    }

    this.dateForm = new FormControl(this.momentDate);
    if (this.disabled) {
      this.dateForm.disable();
    }
    this.endTime = new FormControl(this.momentDate.format("HH:mm"));

    this.timeFormGroup = new FormGroup({
      endTime: this.endTime
    });


  }


  public dateChange(date: MatDatepickerInputEvent<any>) {

    if (moment.isMoment(date.value)) {
      this.momentDate = moment(date.value);
      if (this.dateOnly) {
        this.momentDate = this.momentDate.utc(true);
      } 
      var newDate = this.momentDate.toDate();
      this.model = newDate;
      this.dateUpdate.emit(newDate);
    }

    console.log("datechange",date);
  }

  public timeChange(time: string) {

    var splitted = time.split(':');
    var hour = splitted[0];
    var minute = splitted[1];

    console.log("time change", time);
   this.momentDate = this.momentDate.set('hour', parseInt(hour));
    this.momentDate = this.momentDate.set('minute', parseInt(minute));

    var newDate = this.momentDate.toDate();
    this.model = newDate;
    this.dateUpdate.emit(newDate);
  }
}

One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126

I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).

Adding backslashes without escaping [Python]

>>> '\\&' == '\&'
True
>>> len('\\&')
2
>>> print('\\&')
\&

Or in other words: '\\&' only contains one backslash. It's just escaped in the python shell's output for clarity.

How to set a background image in Xcode using swift?

You can try this as well, which is really a combination of previous answers from other posters here :

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "RubberMat")
    backgroundImage.contentMode =  UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

Abstract variables in Java?

No such thing as abstract variables in Java (or C++).

If the parent class has a variable, and a child class extends the parent, then the child doesn't need to implement the variable. It just needs access to the parent's instance. Either get/set or protected access will do.

"...so I should be prompted to implement the abstracts"? If you extend an abstract class and fail to implement an abstract method the compiler will tell you to either implement it or mark the subclass as abstract. That's all the prompting you'll get.

linq where list contains any in list

I guess this is also possible like this?

var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));

Is "TakeWhile" worse than "Where" in sense of performance or clarity?

Java Swing - how to show a panel on top of another panel?

I just thought that I'd add that there is a notion of Z-order in Swing, see [java.awt.Component#setComponentZOrder][1]

which affects the positions of a component in its parents component array, which determines the painting order.

Note that you should override javax.swing.JComponent#isOptimizedDrawingEnabled to return false in the parent container to get your overlapping components to repaint correctly, otherwise their repaints will clobber each other. (JComponents assume no overlapping children unless isOptimizedDrawingEnabled returns false)

[1]: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html#setComponentZOrder(java.awt.Component, int)

Side-by-side plots with ggplot2

You can use the following multiplot function from Winston Chang's R cookbook

multiplot(plot1, plot2, cols=2)

multiplot <- function(..., plotlist=NULL, cols) {
    require(grid)

    # Make a list from the ... arguments and plotlist
    plots <- c(list(...), plotlist)

    numPlots = length(plots)

    # Make the panel
    plotCols = cols                          # Number of columns of plots
    plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols

    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
    vplayout <- function(x, y)
        viewport(layout.pos.row = x, layout.pos.col = y)

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
        curRow = ceiling(i/plotCols)
        curCol = (i-1) %% plotCols + 1
        print(plots[[i]], vp = vplayout(curRow, curCol ))
    }

}

How do I use CREATE OR REPLACE?

Does not work with Tables, only functions etc.

Here is a site with some examples.

How can I use SUM() OVER()

if you are using SQL 2012 you should try

SELECT  ID, 
        AccountID, 
        Quantity, 
        SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY AccountID rows between unbounded preceding and current row ) AS TopBorcT, 
FROM tCariH

if available, better order by date column.

Difference between Eclipse Europa, Helios, Galileo

To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release

  • Release Date Platform version
  • Juno ?? June 2012 4.2?
  • Indigo 22 June 2011 3.7
  • Helios 23 June 2010 3.6
  • Galileo 24 June 2009 3.5
  • Ganymede 25 June 2008 3.4
  • Europa 29 June 2007 3.3
  • Callisto 30 June 2006 3.2
  • Eclipse 3.1 28 June 2005 3.1
  • Eclipse 3.0 21 June 2004 3.0

I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:

  • eclipse-java-indigo-SR1-linux-gtk.tar.gz
  • eclipse-java-helios-linux-gtk.tar.gz

But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:

  • eclipse-3.7.1-java-indigo-SR1-linux-gtk.tar.gz
  • eclipse-3.6-java-helios-linux-gtk.tar.gz

This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).

Counting number of occurrences in column?

=COUNTIF(A:A;"lisa")

You can replace the criteria with cell references from Column B

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Adding a view controller as a subview in another view controller

This code will work for Swift 4.2.

let controller:SecondViewController = 
self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as! 
SecondViewController
controller.view.frame = self.view.bounds;
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)

Eclipse: Frustration with Java 1.7 (unbound library)

To set JDK you can watch this video : how to set JDK . Then when you'll have JDK:

  1. Right click on build path and select "Build Path"
  2. Choose "Configure Build Path"
  3. Click on "JRE System Library [JavaSE-1.7] (unbound)"
  4. Edit it
  5. Choose "Alternate JRE"
  6. Click on "Installed JREs.." button
  7. Press Add
  8. Choose to add "Standard VM"
  9. Choose JRE Home directory - usually it is locates in "C:\Program Files\Java\jre7" directory
  10. Press "Finish"
  11. Re-check newly appeared "Jre7": Verify that now when you edit "JRE System Library [JavaSE-1.7]" "Alternate JRE" is chosen for jre7.

How to click on hidden element in Selenium WebDriver?

I did it with jQuery:

page.execute_script %Q{ $('#some_id').prop('checked', true) }

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

Compare a date string to datetime in SQL Server?

Date can be compared in sqlserver using string comparision: e.g.

DECLARE @strDate VARCHAR(15)
SET @strDate ='07-12-2010'


SELECT * FROM table
WHERE CONVERT(VARCHAR(15),dtInvoice, 112)>= CONVERT(VARCHAR(15),@strDate , 112)

jquery stop child triggering parent event

The simplest solution is to add this CSS to the children:

.your-child {
    pointer-events: none;
}

How to change resolution (DPI) of an image?

You have to copy the bits over a new image with the target resolution, like this:

    using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
    {
        using (Bitmap newBitmap = new Bitmap(bitmap))
        {
            newBitmap.SetResolution(300, 300);
            newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
        }
    }

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Here's a solution using a negative lookahead (not supported in all regex engines):

^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$

Test that it works as expected:

import re
tests = [
   ('a', True),
   ('_', False),
   ('zz', True),
   ('a0', True),
   ('A_', False),
   ('a0_b', True),
   ('a__b', False),
   ('a_1_c', True),
]

regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
   is_match = re.match(regex, test[0]) is not None
   if is_match != test[1]:
       print "fail: "  + test[0]

Add centered text to the middle of a <hr/>-like line

please try this with bootstrap:

<div class="text-center d-flex">
  <hr className="flex-grow-1" />
  <span className="px-2 font-weight-lighter small align-self-center">
    Hello
  </span>
  <hr className="flex-grow-1" />
</div>

here is result

How can I list all cookies for the current page with Javascript?

No there isn't. You can only read information associated with the current domain.

How to programmatically set the Image source

{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

For each row return the column name of the largest value

One option from dplyr 1.0.0 could be:

DF %>%
 rowwise() %>%
 mutate(row_max = names(.)[which.max(c_across(everything()))])

     V1    V2    V3 row_max
  <dbl> <dbl> <dbl> <chr>  
1     2     7     9 V3     
2     8     3     6 V1     
3     1     5     4 V2     

Sample data:

DF <- structure(list(V1 = c(2, 8, 1), V2 = c(7, 3, 5), V3 = c(9, 6, 
4)), class = "data.frame", row.names = c(NA, -3L))

Understanding checked vs unchecked exceptions in Java

My absolute favorite description of the difference between unchecked and checked exceptions is provided by the Java Tutorial trail article, "Unchecked Exceptions - the Controversy" (sorry to get all elementary on this post - but, hey, the basics are sometimes the best):

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception

The heart of "what type of exception to throw" is semantic (to some degree) and the above quote provides and excellent guideline (hence, I am still blown away by the notion that C# got rid of checked exceptions - particularly as Liskov argues for their usefulness).

The rest then becomes logical: to which exceptions does the compiler expect me to respond, explicitly? The ones from which you expect client to recover.

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

Login to Microsoft SQL Server Error: 18456

Just happened to me, and turned out to be different than all other cases listed here.

I happen to have two virtual servers hosted in the same cluster, each with it own IP address. The host configured one of the servers to be the SQL Server, and the other to be the Web server. However, SQL Server is installed and running on both. The host forgot to mention which of the servers is the SQL and which is the Web, so I just assumed the first is Web, second is SQL.

When I connected to the (what I thought is) SQL Server and tried to connect via SSMS, choosing Windows Authentication, I got the error mentioned in this question. After pulling lots of hairs, I went over all the setting, including SQL Server Network Configuration, Protocols for MSSQLSERVER:

screenshot of TCP/IP configuration

Double clicking the TCP/IP gave me this:

TCP/IP properties, showing wrong IP address

The IP address was of the other virtual server! This finally made me realize I simply confused between the servers, and all worked well on the second server.

How to output MySQL query results in CSV format?

Unix/Cygwin only, pipe it through 'tr':

mysql <database> -e "<query here>" | tr '\t' ',' > data.csv

N.B.: This handles neither embedded commas, nor embedded tabs.

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

For MIUI 9.6 works:
1. Become a developer: Settings >> About phone >> MIUI version tap 7 times.

2. Again Settings >> Additional settings >> Developer options (turn on) >> USB debugging (turn on) >> Install via USB (turn on).

3. You will be asked for permission through your MI account. Confirm permission.

4. Note: During the installation of the application, your device will give you 7 seconds to confirm the installation. Don't miss it!

Select first row in each GROUP BY group?

In PostgreSQL, another possibility is to use the first_value window function in combination with SELECT DISTINCT:

select distinct customer_id,
                first_value(row(id, total)) over(partition by customer_id order by total desc, id)
from            purchases;

I created a composite (id, total), so both values are returned by the same aggregate. You can of course always apply first_value() twice.

How to sort an array of objects by multiple fields?

Here's a generic multidimensional sort, allowing for reversing and/or mapping on each level.

Written in Typescript. For Javascript, check out this JSFiddle

The Code

type itemMap = (n: any) => any;

interface SortConfig<T> {
  key: keyof T;
  reverse?: boolean;
  map?: itemMap;
}

export function byObjectValues<T extends object>(keys: ((keyof T) | SortConfig<T>)[]): (a: T, b: T) => 0 | 1 | -1 {
  return function(a: T, b: T) {
    const firstKey: keyof T | SortConfig<T> = keys[0];
    const isSimple = typeof firstKey === 'string';
    const key: keyof T = isSimple ? (firstKey as keyof T) : (firstKey as SortConfig<T>).key;
    const reverse: boolean = isSimple ? false : !!(firstKey as SortConfig<T>).reverse;
    const map: itemMap | null = isSimple ? null : (firstKey as SortConfig<T>).map || null;

    const valA = map ? map(a[key]) : a[key];
    const valB = map ? map(b[key]) : b[key];
    if (valA === valB) {
      if (keys.length === 1) {
        return 0;
      }
      return byObjectValues<T>(keys.slice(1))(a, b);
    }
    if (reverse) {
      return valA > valB ? -1 : 1;
    }
    return valA > valB ? 1 : -1;
  };
}

Usage Examples

Sorting a people array by last name, then first name:

interface Person {
  firstName: string;
  lastName: string;
}

people.sort(byObjectValues<Person>(['lastName','firstName']));

Sort language codes by their name, not their language code (see map), then by descending version (see reverse).

interface Language {
  code: string;
  version: number;
}

// languageCodeToName(code) is defined elsewhere in code

languageCodes.sort(byObjectValues<Language>([
  {
    key: 'code',
    map(code:string) => languageCodeToName(code),
  },
  {
    key: 'version',
    reverse: true,
  }
]));

Has Facebook sharer.php changed to no longer accept detailed parameters?

Starting from July 18, 2017 Facebook has decided to disregard custom parameters set by users. This choice blocks many of the possibilities offered by this answer and it also breaks buttons used on several websites.

The quote and hashtag parameters work as of Dec 2018.


Does anyone know if there have been recent changes which could have suddenly stopped this from working?

The parameters have changed. The currently accepted answer states:

Facebook no longer supports custom parameters in sharer.php

But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:

  • URL (of course) ? u
  • custom image ? picture
  • custom title ? title
  • custom quote ? quote
  • custom description ? description
  • caption (aka website name) ? caption

For instance, you can share this very question with the following URL:

https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fstackoverflow.com%2Fq%2F20956229%2F1101509&picture=http%3A%2F%2Fwww.applezein.net%2Fwordpress%2Fwp-content%2Fuploads%2F2015%2F03%2Ffacebook-logo.jpg&title=A+nice+question+about+Facebook&quote=Does+anyone+know+if+there+have+been+recent+changes+which+could+have+suddenly+stopped+this+from+working%3F&description=Apparently%2C+the+accepted+answer+is+not+correct.

Try it!

I've built a tool which makes it easier to share URLs on Facebook with custom parameters. You can use it to generate your sharer.php link, just press the button and copy the URL from the tab that opens.

End-line characters from lines read from text file, using Python

Simple. Use splitlines()

L = open("myFile.txt", "r").read().splitlines();
for line in L: 
    process(line) # this 'line' will not have '\n' character at the end

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

A simpler solution on recent versions of tmux (tested on 1.9) you can now do :

tmux detach -a

-a is for all other client on this session except the current one

You can alias it in your .[bash|zsh]rc

alias takeover="tmux detach -a"

Workflow: You can connect to your session normally, and if you are bothered by another session that forced down your tmux window size you can simply call takeover.

How to set cache: false in jQuery.get call

I'm very late in the game, but this might help others. I hit this same problem with $.get and I didn't want to blindly turn off caching and I didn't like the timestamp patch. So after a little research I found that you can simply use $.post instead of $.get which does NOT use caching. Simple as that. :)

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

How to write log base(2) in c/c++

Improved version of what Ustaman Sangat did

static inline uint64_t
log2(uint64_t n)
{
    uint64_t val;
    for (val = 0; n > 1; val++, n >>= 1);

    return val;
}

Check if a folder exist in a directory and create them using C#

if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
     System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}

Parameter in like clause JPQL

  1. Use below JPQL query.
select i from Instructor i where i.address LIKE CONCAT('%',:address ,'%')");
  1. Use below Criteria code for the same:
@Test
public void findAllHavingAddressLike() {
    CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
    CriteriaQuery<Instructor> cq = cb.createQuery(Instructor.class);
    Root<Instructor> root = cq.from(Instructor.class);
    printResultList(cq.select(root).where(
        cb.like(root.get(Instructor_.address), "%#1074%")));
}

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

Visual Studio debugger error: Unable to start program Specified file cannot be found

I think that what you have to check is:

  1. if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).

  2. dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).

Excel VBA date formats

To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.

Sub test_date_or_String()
 Set c = ActiveCell
 c.NumberFormat = "@"
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
 c.NumberFormat = "m/d/yyyy"
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date    
End Sub

How do I create an .exe for a Java program?

Most of the programs that convert java applications to .exe files are just wrappers around the program, and the end user will still need the JRE installed to run it. As far as I know there aren't any converters that will make it a native executable from bytecode (There have been attempts, but if any turned out successful you would hear of them by now).

As for wrappers, the best ones i've used (as previously suggested) are:

JSmooth

and

Launch4j

best of luck!

Ruby - ignore "exit" in code

One hackish way to define an exit method in context:

class Bar; def exit; end; end 

This works because exit in the initializer will be resolved as self.exit1. In addition, this approach allows using the object after it has been created, as in: b = B.new.

But really, one shouldn't be doing this: don't have exit (or even puts) there to begin with.

(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)


1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit normally resolves to Object#exit. However, this can be changed by introducing an overridden method as shown - nothing fancy.

When do I need to do "git pull", before or after "git add, git commit"?

I'd suggest pulling from the remote branch as often as possible in order to minimise large merges and possible conflicts.

Having said that, I would go with the first option:

git add foo.js
git commit foo.js -m "commit"
git pull
git push

Commit your changes before pulling so that your commits are merged with the remote changes during the pull. This may result in conflicts which you can begin to deal with knowing that your code is already committed should anything go wrong and you have to abort the merge for whatever reason.

I'm sure someone will disagree with me though, I don't think there's any correct way to do this merge flow, only what works best for people.

Is there a Java equivalent or methodology for the typedef keyword in C++?

You could use an Enum, although that's semantically a bit different than a typedef in that it only allows a restricted set of values. Another possible solution is a named wrapper class, e.g.

public class Apple {
      public Apple(Integer i){this.i=i; }
}

but that seems way more clunky, especially given that it's not clear from the code that the class has no other function than as an alias.

how can I check if a file exists?

an existing folder will FAIL with FileExists

Function FileExists(strFileName)
' Check if a file exists - returns True or False

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists

Create HTTP post request and receive response using C# console application

For this you can simply use the "HttpWebRequest" and "HttpWebResponse" classes in .net.

Below is a sample console app I wrote to demonstrate how easy this is.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "www.somewhere.com";       
            string fileName = @"C:\output.file";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 5000;

            try
            {
                using (WebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                        byte[] bytes = ReadFully(response.GetResponseStream());

                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (WebException)
            {
                Console.WriteLine("Error Occured");
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}

Enjoy!

Java ByteBuffer to String

The answers referring to simply calling array() are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):

if (myByteBuffer.hasArray()) {
    return new String(myByteBuffer.array(),
        myByteBuffer.arrayOffset() + myByteBuffer.position(),
        myByteBuffer.remaining());
} else {
    final byte[] b = new byte[myByteBuffer.remaining()];
    myByteBuffer.duplicate().get(b);
    return new String(b);
}

For the concerns related to encoding, see Andy Thomas' answer.

How can I install MacVim on OS X?

That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead

See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim script for launching from the command line

Sorting arrays in NumPy by column

import numpy as np
a=np.array([[21,20,19,18,17],[16,15,14,13,12],[11,10,9,8,7],[6,5,4,3,2]])
y=np.argsort(a[:,2],kind='mergesort')# a[:,2]=[19,14,9,4]
a=a[y]
print(a)

Desired output is [[6,5,4,3,2],[11,10,9,8,7],[16,15,14,13,12],[21,20,19,18,17]]

note that argsort(numArray) returns the indices of an numArray as it was supposed to be arranged in a sorted manner.

example

x=np.array([8,1,5]) 
z=np.argsort(x) #[1,3,0] are the **indices of the predicted sorted array**
print(x[z]) #boolean indexing which sorts the array on basis of indices saved in z

answer would be [1,5,8]

How do I filter ForeignKey choices in a Django ModelForm?

A more public way is by calling get_form in Admin classes. It also works for non-database fields too. For example here i have a field called '_terminal_list' on the form that can be used in special cases for choosing several terminal items from get_list(request), then filtering based on request.user:

class ChangeKeyValueForm(forms.ModelForm):  
    _terminal_list = forms.ModelMultipleChoiceField( 
queryset=Terminal.objects.all() )

    class Meta:
        model = ChangeKeyValue
        fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time',  ] 

class ChangeKeyValueAdmin(admin.ModelAdmin):
    form = ChangeKeyValueForm
    list_display = ('terminal','task_list', 'plugin','last_update_time')
    list_per_page =16

    def get_form(self, request, obj = None, **kwargs):
        form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)
        qs, filterargs = Terminal.get_list(request)
        form.base_fields['_terminal_list'].queryset = qs
        return form

PHP - Getting the index of a element from a array

You should use the key() function.

key($array)

should return the current key.

If you need the position of the current key:

array_search($key, array_keys($array));

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

IOException: The process cannot access the file 'file path' because it is being used by another process

I had the following scenario that was causing the same error:

  • Upload files to the server
  • Then get rid of the old files after they have been uploaded

Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.

It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":

using (var wc = new WebClient())
{
   var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
   tskResult.Wait(); 
}

Appending to an existing string

Here's another way:

fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"

How to do select from where x is equal to multiple values?

Put parentheses around the "OR"s:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND
(
    ads.county_id = 2
    OR ads.county_id = 5
    OR ads.county_id = 7
    OR ads.county_id = 9
)

Or even better, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)

How do I decrease the size of my sql server log file?

You have to shrink & backup the log a several times to get the log file to reduce in size, this is because the the log file pages cannot be re-organized as data files pages can be, only truncated. For a more detailed explanation check this out.

WARNING : Detaching the db & deleting the log file is dangerous! don't do this unless you'd like data loss

How to send email from MySQL 5.1

I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.

It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.

How to save password when using Subversion from the console

All methods mention here are not working for me. I built Subversion from source, and I found out, I must run configure with --enable-plaintext-password-storage to support this feature.

All combinations of a list of lists

The most elegant solution is to use itertools.product in python 2.6.

If you aren't using Python 2.6, the docs for itertools.product actually show an equivalent function to do the product the "manual" way:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

Is there an easy way to check the .NET Framework version?

I find it easier to work with the Version class:

using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace System.Runtime.InteropServices {
  public static class RuntimeInformationEx {

    public static Version? GetDotnetFrameworkVersion() {
      using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full");
      if (key is object) {
        if (!Int32.TryParse(key.GetValue("Release", "").ToString(), out var release)) return null;
        return release switch
        {
          378389 => new Version(4, 5, 0),
          378675 => new Version(4, 5, 1),
          378758 => new Version(4, 5, 1),
          379893 => new Version(4, 5, 2),
          393295 => new Version(4, 6, 0),
          393297 => new Version(4, 6, 0),
          394254 => new Version(4, 6, 1),
          394271 => new Version(4, 6, 1),
          394802 => new Version(4, 6, 2),
          394806 => new Version(4, 6, 2),
          460798 => new Version(4, 7, 0),
          460805 => new Version(4, 7, 0),
          461308 => new Version(4, 7, 1),
          461310 => new Version(4, 7, 1),
          461808 => new Version(4, 7, 2),
          461814 => new Version(4, 7, 2),
          528040 => new Version(4, 8, 0),
          528209 => new Version(4, 8, 0),
          528049 => new Version(4, 8, 0),
          _ => null
        };

      } else { // .NET version < 4.5
        using var key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
        if (key1 is null) return null;
        var parts = key1.GetSubKeyNames()[^1].Substring(1).Split('.'); // get lastsub key, remove 'v' prefix, and split
        if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
        if (parts.Length != 3) return null;
        Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
        try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
      }
    }

    public static Version? GetDotnetCoreVersion() {
      if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Core ")) return null;
      var parts = RuntimeInformation.FrameworkDescription.Substring(10).Split('.');
      if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
      if (parts.Length != 3) return null;
      Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
      try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
    }
  }
}

(code is C#8)

Visual Studio : short cut Key : Duplicate Line

While I realize this is not a keyboard shortcut, I figured I would add this, as it does not require the usage of the clipboard and might help some people.

Highlight the row you want to duplicate. Press control, mouse click the highlighted text, and drag to where you want to go to. It will duplicate the highlighted text.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

It turns out there is no one mentioning set spring.jpa.database=mysql in application.properties file, if you use Spring JPA. This is the simplest answer to me and I want to share in this question.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) occurred because dispatch_group_t was released while it was still locking (waiting for dispatch_group_leave).

According to what you found, this was what happened :

  • dispatch_group_t group was created. group's retain count = 1.
  • -[self webservice:onCompletion:] captured the group. group's retain count = 2.
  • dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... }); captured the group again. group's retain count = 3.
  • Exit the current scope. group was released. group's retain count = 2.
  • dispatch_group_leave was never called.
  • dispatch_group_wait was timeout. The dispatch_async block was completed. group was released. group's retain count = 1.
  • You called this method again. When -[self webservice:onCompletion:] was called again, the old onCompletion block was replaced with the new one. So, the old group was released. group's retain count = 0. group was deallocated. That resulted to EXC_BAD_INSTRUCTION.

To fix this, I suggest you should find out why -[self webservice:onCompletion:] didn't call onCompletion block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.


In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group for you :

  • You can change the timeout from 2 seconds to DISPATCH_TIME_FOREVER or a reasonable amount of time that all -[self webservice:onCompletion] should call their onCompletion blocks by the time. So that the block in dispatch_async(...) will hold it for you.
    OR
  • You can add group into a collection, such as NSMutableArray.

I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t or dispatch_semaphore_t.

C: scanf to array

int main()
{
  int array[11];
  printf("Write down your ID number!\n");
  for(int i=0;i<id_length;i++)
  scanf("%d", &array[i]);
  if (array[0]==1)
  {
    printf("\nThis person is a male.");
  }
  else if (array[0]==2)
  {
    printf("\nThis person is a female.");
  }
  return 0;
}

How to use background thread in swift?

Swift 4.x

Put this in some file:

func background(work: @escaping () -> ()) {
    DispatchQueue.global(qos: .userInitiated).async {
        work()
    }
}

func main(work: @escaping () -> ()) {
    DispatchQueue.main.async {
        work()
    }
}

and then call it where you need:

background {
     //background job
     main {
       //update UI (or what you need to do in main thread)
     }
}

Using Helvetica Neue in a Website

They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).

In your example "HelveticaNeue-Light" will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light" and finally "Helvetica Neue".

As far as I'm aware "Helvetica Neue" isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif" or "sans-serif" as a final default position.

In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.

A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.

Cross browser JavaScript (not jQuery...) scroll to top animation

Building on some of the answers here, but using some simple math for a smooth transition using a sine curve:

scrollTo(element, from, to, duration, currentTime) {
       if (from <= 0) { from = 0;}
       if (to <= 0) { to = 0;}
       if (currentTime>=duration) return;
       let delta = to-from;
       let progress = currentTime / duration * Math.PI / 2;
       let position = delta * (Math.sin(progress));
       setTimeout(() => {
           element.scrollTop = from + position;
           this.scrollTo(element, from, to, duration, currentTime + 10);
       }, 10);
   }

Usage:

// Smoothly scroll from current position to new position in 1/2 second.
scrollTo(element, element.scrollTop, element.scrollTop + 400, 500, 0);

PS. take note of ES6 style

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Can't find AVD or SDK manager in Eclipse

Chances are that you may be running your eclipse using Java 1.5.

Latest Plugin requires that the JRE be 1.6 or higher. 

You will have to use Eclipse that runs on JRE 1.6

Edit: I had run into same problems. If it is not JRE problem then you can debug this. Follow below procedure:

  1. Window -> show View -> other -> Plugin Development -> Plugin Registry
  2. In the plugin registry search for com.android.ide.eclipse.adt or any other plugin related to android (depending on your installation there maybe 7-8)
  3. Select , Right Click -> Diagnose. This will show the problem why the plugin was not loaded

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

How to build a 'release' APK in Android Studio?

Click \Build\Select Build Variant... in Android Studio. And choose release.

How do I convert a PDF document to a preview image in PHP?

If you're loading the PDF from a blob this is how you get the first page instead of the last page:

$im->readimageblob($blob);
$im->setiteratorindex(0);

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

None of the answers they gave you was exhaustive. The problem lies in the Multidex. You must add the library in the app gradle :

implementation 'com.android.support:multidex:1.0.3'

After, add in the defaultConfig of the app gradle :

multiDexEnabled true

Your Application must be of the Multidex type.. You must write it in the manifest :

android:name=".MyApplication"

"MyApplication" must be either the Multidex class, or it must extend it.

Jquery resizing image

imgLiquid (a jQuery Plugin) seems to do what you ask.

Demo:
http://goo.gl/Wk8bU

JsFiddle example:
http://jsfiddle.net/karacas/3CRx7/#base

Javascript

$(function() {

    $(".imgLiquidFill").imgLiquid({
        fill: true,
        horizontalAlign: "center",
        verticalAlign: "top"
    });

    $(".imgLiquidNoFill").imgLiquid({
        fill: false,
        horizontalAlign: "center",
        verticalAlign: "50%"
    });
     });

Html

<div class="boxSep" >
    <div class="imgLiquidNoFill imgLiquid" style="width:250px; height:250px;">
        <img alt="" src="http://www.juegostoystory.net/files/image/2010_Toy_Story_3_USLC12_Woody.jpg"/>
    </div>
</div>

MessageBox Buttons?

Check this:

                     if (
 MessageBox.Show(@"Are you Alright?", @"My Message Box",MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //YES ---> Ok IM ALRIGHHT
                    }
                    else
                   {
                   //NO --->NO IM STUCK
                    }

Regards

HTML Text with tags to formatted text in an Excel cell

I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below

  1. First enable developer mode in Excel: Link
  2. Select the Developer Tab > Visual Basic
  3. Click View > Code
  4. Paste the code below updating the lines that require cell references to be correct.
  5. Click the Green Run Arrow or press F5
Sub Sample()
    Dim Ie As Object
    Set Ie = CreateObject("InternetExplorer.Application")
    With Ie
        .Visible = False
        .Navigate "about:blank"
        .document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
             'update to the cell that contains HTML you want converted
        .ExecWB 17, 0
             'Select all contents in browser
        .ExecWB 12, 2
             'Copy them
        ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
             'update to cell you want converted HTML pasted in
        .Quit
    End With
End Sub

Setting user agent of a java URLConnection

HTTP Servers tend to reject old browsers and systems.

The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection or the system property "http.agent".

How to parse Excel (XLS) file in Javascript/HTML5

Below Function converts the Excel sheet (XLSX format) data to JSON. you can add promise to the function.

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script>
var ExcelToJSON = function() {

  this.parseExcel = function(file) {
    var reader = new FileReader();

    reader.onload = function(e) {
      var data = e.target.result;
      var workbook = XLSX.read(data, {
        type: 'binary'
      });

      workbook.SheetNames.forEach(function(sheetName) {
        // Here is your object
        var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
        var json_object = JSON.stringify(XL_row_object);
        console.log(json_object);

      })

    };

    reader.onerror = function(ex) {
      console.log(ex);
    };

    reader.readAsBinaryString(file);
  };
};
</script>

Below post has the code for XLS format Excel to JSON javascript code?

How to get an object's properties in JavaScript / jQuery?

Scanning object for first intance of a determinated prop:

var obj = {a:'Saludos',
            b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
           d:'Hasta luego'
            }
function scan (element,list){
    var res;
    if (typeof(list) != 'undefined'){
        if (typeof(list) == 'object'){
            for(key in list){
               if (typeof(res) == 'undefined'){
                res = (key == element)?list[key]:scan(element,list[key]);
               }
            });
        }
    }
    return res;
}
console.log(scan('a',obj));

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):

fetch(request, {mode: 'cors'});

However this still requires the server to enable CORS as well, and allow your domain to request the resource.

Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.

You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>):

fetch(request, {mode: 'no-cors'})
.then(function(response) {
  console.log(response); 
}).catch(function(error) {  
  console.log('Request failed', error)  
});

How to display text in pygame?

There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.

Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.

You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.

import pygame
import pygame.freetype  # Import the freetype module.


pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running =  True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255,255,255))
    # You can use `render` and then blit the text surface ...
    text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
    screen.blit(text_surface, (40, 250))
    # or just `render_to` the target surface.
    GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))

    pygame.display.flip()

pygame.quit()

Put search icon near textbox using bootstrap

Here are three different ways to do it:

screenshot

Here's a working Demo in Fiddle Of All Three

Validation:

You can use native bootstrap validation states (No Custom CSS!):

<div class="form-group has-feedback">
    <label class="control-label" for="inputSuccess2">Name</label>
    <input type="text" class="form-control" id="inputSuccess2"/>
    <span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>

For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box

Input Group:

You can use the .input-group class like this:

<div class="input-group">
    <input type="text" class="form-control"/>
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box

Unstyled Input Group:

You can still use .input-group for positioning but just override the default styling to make the two elements appear separate.

Use a normal input group but add the class input-group-unstyled:

<div class="input-group input-group-unstyled">
    <input type="text" class="form-control" />
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

Then change the styling with the following css:

.input-group.input-group-unstyled input.form-control {
    -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
            border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
    border-radius: 4px;
    border: 0px;
    background-color: transparent;
}

Also, these solutions work for any input size

How can I close a dropdown on click outside?

I also did a little workaround of my own.

I created a (dropdownOpen) event which I listen to at my ng-select element component and call a function which will close all the other SelectComponent's opened apart from the currently opened SelectComponent.

I modified one function inside the select.ts file like below to emit the event:

private open():void {
    this.options = this.itemObjects
        .filter((option:SelectItem) => (this.multiple === false ||
        this.multiple === true && !this.active.find((o:SelectItem) => option.text === o.text)));

    if (this.options.length > 0) {
        this.behavior.first();
    }
    this.optionsOpened = true;
    this.dropdownOpened.emit(true);
}

In the HTML I added an event listener for (dropdownOpened):

<ng-select #elem (dropdownOpened)="closeOtherElems(elem)"
    [multiple]="true"
    [items]="items"
    [disabled]="disabled"
    [isInputAllowed]="true"
    (data)="refreshValue($event)"
    (selected)="selected($event)"
    (removed)="removed($event)"
    placeholder="No city selected"></ng-select>

This is my calling function on event trigger inside the component having ng2-select tag:

@ViewChildren(SelectComponent) selectElem :QueryList<SelectComponent>;

public closeOtherElems(element){
    let a = this.selectElem.filter(function(el){
                return (el != element)
            });

    a.forEach(function(e:SelectComponent){
        e.closeDropdown();
    })
}

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

how to use sqltransaction in c#

First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

sqlCommand.Transaction = transaction;

And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();

What is href="#" and why is it used?

Unordered lists are often created with the intent of using them as a menu, but an li list item is text. Because the list li item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a inside of the li tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.

<ul id="menu">
   <li><a href="#">Menu Item 1</a></li>
   <li><a href="#">Menu Item 2</a></li>
   <li><a href="#">Menu Item 3</a></li>
   <li><a href="#">Menu Item 4</a></li>
</ul>

If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href attribute, text in the <a> tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href, but you don't need a link to anywhere.

You could use lots of div or p tags for a menu list, but the mouse pointer would be an I-cursor for them also.

You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#" that points to nowhere is used in anchor tags inside of list tags.

You can set the pointer style in CSS, so that is another option. The href="#" to nowhere might just be the lazy way to set some styling.

How to set max and min value for Y axis

_x000D_
_x000D_
var config = {_x000D_
            type: 'line',_x000D_
            data: {_x000D_
                labels: ["January", "February", "March", "April", "May", "June", "July"],_x000D_
                datasets: [{_x000D_
                        label: "My First dataset",_x000D_
                        data: [10, 80, 56, 60, 6, 45, 15],_x000D_
                        fill: false,_x000D_
                        backgroundColor: "#eebcde ",_x000D_
                        borderColor: "#eebcde",_x000D_
                        borderCapStyle: 'butt',_x000D_
                        borderDash: [5, 5],_x000D_
                    }]_x000D_
            },_x000D_
            options: {_x000D_
                responsive: true,_x000D_
                legend: {_x000D_
                    position: 'bottom',_x000D_
                },_x000D_
                hover: {_x000D_
                    mode: 'label'_x000D_
                },_x000D_
                scales: {_x000D_
                    xAxes: [{_x000D_
                            display: true,_x000D_
                            scaleLabel: {_x000D_
                                display: true,_x000D_
                                labelString: 'Month'_x000D_
                            }_x000D_
                        }],_x000D_
                    yAxes: [{_x000D_
                            display: true,_x000D_
                            ticks: {_x000D_
                                beginAtZero: true,_x000D_
                                steps: 10,_x000D_
                                stepValue: 5,_x000D_
                                max: 100_x000D_
                            }_x000D_
                        }]_x000D_
                },_x000D_
                title: {_x000D_
                    display: true,_x000D_
                    text: 'Chart.js Line Chart - Legend'_x000D_
                }_x000D_
            }_x000D_
        };_x000D_
_x000D_
        var ctx = document.getElementById("canvas").getContext("2d");_x000D_
       new Chart(ctx, config);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.bundle.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
  <canvas id="canvas"></canvas>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to put a horizontal divisor line between edit text's in a activity

Use This..... You will love it

 <TextView
    android:layout_width="fill_parent"
    android:layout_height="1px"
    android:text=" "
    android:background="#anycolor"
    android:id="@+id/textView"/>

How to get distinct results in hibernate with joins and row-based limiting (paging)?

You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.

Simply add this to your criteria:

criteria.setProjection(Projections.distinct(Projections.property("id")));

Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check as part of the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness after the sql query has been performed.

Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.

Javascript form validation with password confirming

Just add onsubmit event handler for your form:

<form  action="insert.php" onsubmit="return myFunction()" method="post">

Remove onclick from button and make it input with type submit

<input type="submit" value="Submit">

And add boolean return statements to your function:

function myFunction() {
    var pass1 = document.getElementById("pass1").value;
    var pass2 = document.getElementById("pass2").value;
    var ok = true;
    if (pass1 != pass2) {
        //alert("Passwords Do not match");
        document.getElementById("pass1").style.borderColor = "#E34234";
        document.getElementById("pass2").style.borderColor = "#E34234";
        return false;
    }
    else {
        alert("Passwords Match!!!");
    }
    return ok;
}

Absolute positioning ignoring padding of parent

First, let's see why this is happening.

The reason is that, surprisingly, when a box has position: absolute its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.

Here is the relevant part of the CSS specification:

In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.

The simplest approach—as suggested in Winter's answer—is to use padding: inherit on the absolutely positioned div. It only works, though, if you don't want the absolutely positioned div to have any additional padding of its own. I think the most general-purpose solutions (in that both elements can have their own independent padding) are:

  1. Add an extra relatively positioned div (with no padding) around the absolutely positioned div. That new div will respect the padding of its parent, and the absolutely positioned div will then fill it.

    The downside, of course, is that you're messing with the HTML simply for presentational purposes.

  2. Repeat the padding (or add to it) on the absolutely positioned element.

    The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like SASS or LESS you can avoid that problem by using a variable. This is the method I personally use.

How to display gpg key details without importing it?

To get the key IDs (8 bytes, 16 hex digits), this is the command which worked for me in GPG 1.4.16, 2.1.18 and 2.2.19:

gpg --list-packets <key.asc | awk '$1=="keyid:"{print$2}'

To get some more information (in addition to the key ID):

gpg --list-packets <key.asc

To get even more information:

gpg --list-packets -vvv --debug 0x2 <key.asc

The command

gpg --dry-run --import <key.asc

also works in all 3 versions, but in GPG 1.4.16 it prints only a short (4 bytes, 8 hex digits) key ID, so it's less secure to identify keys.

Some commands in other answers (e.g. gpg --show-keys, gpg --with-fingerprint, gpg --import --import-options show-only) don't work in some of the 3 GPG versions above, thus they are not portable when targeting multiple versions of GPG.

&& (AND) and || (OR) in IF statements

Java has 5 different boolean compare operators: &, &&, |, ||, ^

& and && are "and" operators, | and || "or" operators, ^ is "xor"

The single ones will check every parameter, regardless of the values, before checking the values of the parameters. The double ones will first check the left parameter and its value and if true (||) or false (&&) leave the second one untouched. Sound compilcated? An easy example should make it clear:

Given for all examples:

 String aString = null;

AND:

 if (aString != null & aString.equals("lala"))

Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.

 if (aString != null && aString.equals("lala"))

The first parameter is checked and it returns false, so the second paramter won't be checked, because the result is false anyway.

The same for OR:

 if (aString == null | !aString.equals("lala"))

Will raise NullPointerException, too.

 if (aString == null || !aString.equals("lala"))

The first parameter is checked and it returns true, so the second paramter won't be checked, because the result is true anyway.

XOR can't be optimized, because it depends on both parameters.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to check SQL Server version

Following are possible ways to see the version:

Method 1: Connect to the instance of SQL Server, and then run the following query:

Select @@version

An example of the output of this query is as follows:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 
10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Express 
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.

Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files. The entries may resemble the following:

2011-03-27 22:31:33.50 Server      Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)                 Mar 29 2009 10:11:52                 Copyright (c) 1988-2008 Microsoft Corporation                Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.

Method 4: Connect to the instance of SQL Server, and then run the following query:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Note This query works with any instance of SQL Server 2000 or of a later version

How to extract code of .apk file which is not working?

Click here this is a good tutorial for both window/ubuntu.

  1. apktool1.5.1.jar download from here.

  2. apktool-install-linux-r05-ibot download from here.

  3. dex2jar-0.0.9.15.zip download from here.

  4. jd-gui-0.3.3.linux.i686.tar.gz (java de-complier) download from here.

  5. framework-res.apk ( Located at your android device /system/framework/)

Procedure:

  1. Rename the .apk file and change the extension to .zip ,

it will become .zip.

  1. Then extract .zip.

  2. Unzip downloaded dex2jar-0.0.9.15.zip file , copy the contents and paste it to unzip folder.

  3. Open terminal and change directory to unzip “dex2jar-0.0.9.15 “

– cd – sh dex2jar.sh classes.dex (result of this command “classes.dex.dex2jar.jar” will be in your extracted folder itself).

  1. Now, create new folder and copy “classes.dex.dex2jar.jar” into it.

  2. Unzip “jd-gui-0.3.3.linux.i686.zip“ and open up the “Java Decompiler” in full screen mode.

  3. Click on open file and select “classes.dex.dex2jar.jar” into the window.

  4. “Java Decompiler” and go to file > save and save the source in a .zip file.

  5. Create “source_code” folder.

  6. Extract the saved .zip and copy the contents to “source_code” folder.

  7. This will be where we keep your source code.

  8. Extract apktool1.5.1.tar.bz2 , you get apktool.jar

  9. Now, unzip “apktool-install-linux-r05-ibot.zip”

  10. Copy “framework-res.apk” , “.apk” and apktool.jar

  11. Paste it to the unzip “apktool-install-linux-r05-ibot” folder (line no 13).

  12. Then open terminal and type:

    – cd

    – chown -R : ‘apktool.jar’

    – chown -R : ‘apktool’

    – chown -R : ‘aapt’

    – sudo chmod +x ‘apktool.jar’

    – sudo chmod +x ‘apktool’

    – sudo chmod +x ‘aapt’

    – sudo mv apktool.jar /usr/local/bin

    – sudo mv apktool /usr/local/bin

    – sudo mv aapt /usr/local/bin

    – apktool if framework-res.apk – apktool d .apk

Android set height and width of Custom view programmatically

This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.

someView.layoutParams = LinearLayout.LayoutParams(100, 200)

This allows to set the width and height (100 and 200) in a single line.

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Python append() vs. + operator on lists, why do these give different results?

See the documentation:

list.append(x)

  • Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L) - Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

c.append(c) "appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.

c += c is equivalent to extend(c), which appends the elements of c to c.

Reading rows from a CSV file in Python

I just leave my solution here.

import csv
import numpy as np

with open(name, newline='') as f:
    reader = csv.reader(f, delimiter=",")
    # skip header
    next(reader)
    # convert csv to list and then to np.array
    data  = np.array(list(reader))[:, 1:] # skip the first column

print(data.shape) # => (N, 2)

# sum each row
s = data.sum(axis=1)
print(s.shape) # => (N,)

Place input box at the center of div

#the_div input {
  margin: 0 auto;
}

I'm not sure if this works in good ol' IE6, so you might have to do this instead.

/* IE 6 (probably) */
#the_div {
  text-align: center;
}

jQuery loop over JSON result from AJAX Success?

Try jQuery.map function, works pretty well with maps.

_x000D_
_x000D_
var mapArray = {_x000D_
  "lastName": "Last Name cannot be null!",_x000D_
  "email": "Email cannot be null!",_x000D_
  "firstName": "First Name cannot be null!"_x000D_
};_x000D_
_x000D_
$.map(mapArray, function(val, key) {_x000D_
  alert("Value is :" + val);_x000D_
  alert("key is :" + key);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Show/hide widgets in Flutter programmatically

UPDATE: Since this answer was written, Visibility was introduced and provides the best solution to this problem.


You can use Opacity with an opacity: of 0.0 to draw make an element hidden but still occupy space.

To make it not occupy space, replace it with an empty Container().

EDIT: To wrap it in an Opacity object, do the following:

            new Opacity(opacity: 0.0, child: new Padding(
              padding: const EdgeInsets.only(
                left: 16.0,
              ),
              child: new Icon(pencil, color: CupertinoColors.activeBlue),
            ))

Google Developers quick tutorial on Opacity: https://youtu.be/9hltevOHQBw

clearing select using jquery

use .empty()

 $('select').empty().append('whatever');

you can also use .html() but note

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:

alternative: --- If you want only option elements to-be-remove, use .remove()

$('select option').remove();

How to post object and List using postman

In case of simple example if your api is below

@POST
    @Path("update_accounts")
    @Consumes(MediaType.APPLICATION_JSON)
    @PermissionRequired(Permissions.UPDATE_ACCOUNTS)
    void createLimit(List<AccountUpdateRequest> requestList) throws RuntimeException;

where AccountUpdateRequest :

public class AccountUpdateRequest {
    private Long accountId;
    private AccountType accountType;
    private BigDecimal amount;
...
}

then your postman request would be: http://localhost:port/update_accounts

[
         {
            "accountType": "LEDGER",
            "accountId": 11111,
            "amount": 100
         },
         {
            "accountType": "LEDGER",
            "accountId": 2222,
            "amount": 300
          },
         {
            "accountType": "LEDGER",
            "accountId": 3333,
            "amount": 1000
          }
]

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Automatically add all files in a folder to a target using CMake?

Extension for @Kleist answer:

Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB) and file(GLOB_RECURSE). With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.

However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB) or file(GLOB_RECURSE) for collect the sources.

Error handling in Bash

I've used

die() {
        echo $1
        kill $$
}

before; i think because 'exit' was failing for me for some reason. The above defaults seem like a good idea, though.

Docker: adding a file from a parent directory

If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../

            apiVersion: skaffold/v2beta4
            kind: Config
            metadata:
                name: frontend
            build:
                artifacts:
                    - image: nginx-angular-ui
                      context: ../../../
                      sync:
                          # A local build will update dist and sync it to the container
                          manual:
                              - src: './dist/apps'
                                dest: '/usr/share/nginx/html'
                      docker:
                          dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
                    - image: webapi/image
                      context: ../../../../api/
                      docker:
                          dockerfile: ./dockerfile
            deploy:
                kubectl:
                    manifests:
                        - ./.k8s/*.yml

skaffold run -f ./skaffold.yaml

Closure in Java 7

Please see this wiki page for definition of closure.

And this page for closure in Java 8: http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html

Also look at this Q&A: Closures in Java 7

Logging best practices


Update: For extensions to System.Diagnostics, providing some of the missing listeners you might want, see Essential.Diagnostics on CodePlex (http://essentialdiagnostics.codeplex.com/)


Frameworks

Q: What frameworks do you use?

A: System.Diagnostics.TraceSource, built in to .NET 2.0.

It provides powerful, flexible, high performance logging for applications, however many developers are not aware of its capabilities and do not make full use of them.

There are some areas where additional functionality is useful, or sometimes the functionality exists but is not well documented, however this does not mean that the entire logging framework (which is designed to be extensible) should be thrown away and completely replaced like some popular alternatives (NLog, log4net, Common.Logging, and even EntLib Logging).

Rather than change the way you add logging statements to your application and re-inventing the wheel, just extended the System.Diagnostics framework in the few places you need it.

It seems to me the other frameworks, even EntLib, simply suffer from Not Invented Here Syndrome, and I think they have wasted time re-inventing the basics that already work perfectly well in System.Diagnostics (such as how you write log statements), rather than filling in the few gaps that exist. In short, don't use them -- they aren't needed.

Features you may not have known:

  • Using the TraceEvent overloads that take a format string and args can help performance as parameters are kept as separate references until after Filter.ShouldTrace() has succeeded. This means no expensive calls to ToString() on parameter values until after the system has confirmed message will actually be logged.
  • The Trace.CorrelationManager allows you to correlate log statements about the same logical operation (see below).
  • VisualBasic.Logging.FileLogTraceListener is good for writing to log files and supports file rotation. Although in the VisualBasic namespace, it can be just as easily used in a C# (or other language) project simply by including the DLL.
  • When using EventLogTraceListener if you call TraceEvent with multiple arguments and with empty or null format string, then the args are passed directly to the EventLog.WriteEntry() if you are using localized message resources.
  • The Service Trace Viewer tool (from WCF) is useful for viewing graphs of activity correlated log files (even if you aren't using WCF). This can really help debug complex issues where multiple threads/activites are involved.
  • Avoid overhead by clearing all listeners (or removing Default); otherwise Default will pass everything to the trace system (and incur all those ToString() overheads).

Areas you might want to look at extending (if needed):

  • Database trace listener
  • Colored console trace listener
  • MSMQ / Email / WMI trace listeners (if needed)
  • Implement a FileSystemWatcher to call Trace.Refresh for dynamic configuration changes

Other Recommendations:

Use structed event id's, and keep a reference list (e.g. document them in an enum).

Having unique event id's for each (significant) event in your system is very useful for correlating and finding specific issues. It is easy to track back to the specific code that logs/uses the event ids, and can make it easy to provide guidance for common errors, e.g. error 5178 means your database connection string is wrong, etc.

Event id's should follow some kind of structure (similar to the Theory of Reply Codes used in email and HTTP), which allows you to treat them by category without knowing specific codes.

e.g. The first digit can detail the general class: 1xxx can be used for 'Start' operations, 2xxx for normal behaviour, 3xxx for activity tracing, 4xxx for warnings, 5xxx for errors, 8xxx for 'Stop' operations, 9xxx for fatal errors, etc.

The second digit can detail the area, e.g. 21xx for database information (41xx for database warnings, 51xx for database errors), 22xx for calculation mode (42xx for calculation warnings, etc), 23xx for another module, etc.

Assigned, structured event id's also allow you use them in filters.

Q: If you use tracing, do you make use of Trace.Correlation.StartLogicalOperation?

A: Trace.CorrelationManager is very useful for correlating log statements in any sort of multi-threaded environment (which is pretty much anything these days).

You need at least to set the ActivityId once for each logical operation in order to correlate.

Start/Stop and the LogicalOperationStack can then be used for simple stack-based context. For more complex contexts (e.g. asynchronous operations), using TraceTransfer to the new ActivityId (before changing it), allows correlation.

The Service Trace Viewer tool can be useful for viewing activity graphs (even if you aren't using WCF).

Q: Do you write this code manually, or do you use some form of aspect oriented programming to do it? Care to share a code snippet?

A: You may want to create a scope class, e.g. LogicalOperationScope, that (a) sets up the context when created and (b) resets the context when disposed.

This allows you to write code such as the following to automatically wrap operations:

  using( LogicalOperationScope operation = new LogicalOperationScope("Operation") )
  {
    // .. do work here
  }

On creation the scope could first set ActivityId if needed, call StartLogicalOperation and then log a TraceEventType.Start message. On Dispose it could log a Stop message, and then call StopLogicalOperation.

Q: Do you provide any form of granularity over trace sources? E.g., WPF TraceSources allow you to configure them at various levels.

A: Yes, multiple Trace Sources are useful / important as systems get larger.

Whilst you probably want to consistently log all Warning & above, or all Information & above messages, for any reasonably sized system the volume of Activity Tracing (Start, Stop, etc) and Verbose logging simply becomes too much.

Rather than having only one switch that turns it all either on or off, it is useful to be able to turn on this information for one section of your system at a time.

This way, you can locate significant problems from the usually logging (all warnings, errors, etc), and then "zoom in" on the sections you want and set them to Activity Tracing or even Debug levels.

The number of trace sources you need depends on your application, e.g. you may want one trace source per assembly or per major section of your application.

If you need even more fine tuned control, add individual boolean switches to turn on/off specific high volume tracing, e.g. raw message dumps. (Or a separate trace source could be used, similar to WCF/WPF).

You might also want to consider separate trace sources for Activity Tracing vs general (other) logging, as it can make it a bit easier to configure filters exactly how you want them.

Note that messages can still be correlated via ActivityId even if different sources are used, so use as many as you need.


Listeners

Q: What log outputs do you use?

This can depend on what type of application you are writing, and what things are being logged. Usually different things go in different places (i.e. multiple outputs).

I generally classify outputs into three groups:

(1) Events - Windows Event Log (and trace files)

e.g. If writing a server/service, then best practice on Windows is to use the Windows Event Log (you don't have a UI to report to).

In this case all Fatal, Error, Warning and (service-level) Information events should go to the Windows Event Log. The Information level should be reserved for these type of high level events, the ones that you want to go in the event log, e.g. "Service Started", "Service Stopped", "Connected to Xyz", and maybe even "Schedule Initiated", "User Logged On", etc.

In some cases you may want to make writing to the event log a built-in part of your application and not via the trace system (i.e. write Event Log entries directly). This means it can't accidentally be turned off. (Note you still also want to note the same event in your trace system so you can correlate).

In contrast, a Windows GUI application would generally report these to the user (although they may also log to the Windows Event Log).

Events may also have related performance counters (e.g. number of errors/sec), and it can be important to co-ordinate any direct writing to the Event Log, performance counters, writing to the trace system and reporting to the user so they occur at the same time.

i.e. If a user sees an error message at a particular time, you should be able to find the same error message in the Windows Event Log, and then the same event with the same timestamp in the trace log (along with other trace details).

(2) Activities - Application Log files or database table (and trace files)

This is the regular activity that a system does, e.g. web page served, stock market trade lodged, order taken, calculation performed, etc.

Activity Tracing (start, stop, etc) is useful here (at the right granuality).

Also, it is very common to use a specific Application Log (sometimes called an Audit Log). Usually this is a database table or an application log file and contains structured data (i.e. a set of fields).

Things can get a bit blurred here depending on your application. A good example might be a web server which writes each request to a web log; similar examples might be a messaging system or calculation system where each operation is logged along with application-specific details.

A not so good example is stock market trades or a sales ordering system. In these systems you are probably already logging the activity as they have important business value, however the principal of correlating them to other actions is still important.

As well as custom application logs, activities also often have related peformance counters, e.g. number of transactions per second.

In generally you should co-ordinate logging of activities across different systems, i.e. write to your application log at the same time as you increase your performance counter and log to your trace system. If you do all at the same time (or straight after each other in the code), then debugging problems is easier (than if they all occur at diffent times/locations in the code).

(3) Debug Trace - Text file, or maybe XML or database.

This is information at Verbose level and lower (e.g. custom boolean switches to turn on/off raw data dumps). This provides the guts or details of what a system is doing at a sub-activity level.

This is the level you want to be able to turn on/off for individual sections of your application (hence the multiple sources). You don't want this stuff cluttering up the Windows Event Log. Sometimes a database is used, but more likely are rolling log files that are purged after a certain time.

A big difference between this information and an Application Log file is that it is unstructured. Whilst an Application Log may have fields for To, From, Amount, etc., Verbose debug traces may be whatever a programmer puts in, e.g. "checking values X={value}, Y=false", or random comments/markers like "Done it, trying again".

One important practice is to make sure things you put in application log files or the Windows Event Log also get logged to the trace system with the same details (e.g. timestamp). This allows you to then correlate the different logs when investigating.

If you are planning to use a particular log viewer because you have complex correlation, e.g. the Service Trace Viewer, then you need to use an appropriate format i.e. XML. Otherwise, a simple text file is usually good enough -- at the lower levels the information is largely unstructured, so you might find dumps of arrays, stack dumps, etc. Provided you can correlated back to more structured logs at higher levels, things should be okay.

Q: If using files, do you use rolling logs or just a single file? How do you make the logs available for people to consume?

A: For files, generally you want rolling log files from a manageability point of view (with System.Diagnostics simply use VisualBasic.Logging.FileLogTraceListener).

Availability again depends on the system. If you are only talking about files then for a server/service, rolling files can just be accessed when necessary. (Windows Event Log or Database Application Logs would have their own access mechanisms).

If you don't have easy access to the file system, then debug tracing to a database may be easier. [i.e. implement a database TraceListener].

One interesting solution I saw for a Windows GUI application was that it logged very detailed tracing information to a "flight recorder" whilst running and then when you shut it down if it had no problems then it simply deleted the file.

If, however it crashed or encountered a problem then the file was not deleted. Either if it catches the error, or the next time it runs it will notice the file, and then it can take action, e.g. compress it (e.g. 7zip) and email it or otherwise make available.

Many systems these days incorporate automated reporting of failures to a central server (after checking with users, e.g. for privacy reasons).


Viewing

Q: What tools to you use for viewing the logs?

A: If you have multiple logs for different reasons then you will use multiple viewers.

Notepad/vi/Notepad++ or any other text editor is the basic for plain text logs.

If you have complex operations, e.g. activities with transfers, then you would, obviously, use a specialized tool like the Service Trace Viewer. (But if you don't need it, then a text editor is easier).

As I generally log high level information to the Windows Event Log, then it provides a quick way to get an overview, in a structured manner (look for the pretty error/warning icons). You only need to start hunting through text files if there is not enough in the log, although at least the log gives you a starting point. (At this point, making sure your logs have co-ordinated entires becomes useful).

Generally the Windows Event Log also makes these significant events available to monitoring tools like MOM or OpenView.

Others --

If you log to a Database it can be easy to filter and sort informatio (e.g. zoom in on a particular activity id. (With text files you can use Grep/PowerShell or similar to filter on the partiular GUID you want)

MS Excel (or another spreadsheet program). This can be useful for analysing structured or semi-structured information if you can import it with the right delimiters so that different values go in different columns.

When running a service in debug/test I usually host it in a console application for simplicity I find a colored console logger useful (e.g. red for errors, yellow for warnings, etc). You need to implement a custom trace listener.

Note that the framework does not include a colored console logger or a database logger so, right now, you would need to write these if you need them (it's not too hard).

It really annoys me that several frameworks (log4net, EntLib, etc) have wasted time re-inventing the wheel and re-implemented basic logging, filtering, and logging to text files, the Windows Event Log, and XML files, each in their own different way (log statements are different in each); each has then implemented their own version of, for example, a database logger, when most of that already existed and all that was needed was a couple more trace listeners for System.Diagnostics. Talk about a big waste of duplicate effort.

Q: If you are building an ASP.NET solution, do you also use ASP.NET Health Monitoring? Do you include trace output in the health monitor events? What about Trace.axd?

These things can be turned on/off as needed. I find Trace.axd quite useful for debugging how a server responds to certain things, but it's not generally useful in a heavily used environment or for long term tracing.

Q: What about custom performance counters?

For a professional application, especially a server/service, I expect to see it fully instrumented with both Performance Monitor counters and logging to the Windows Event Log. These are the standard tools in Windows and should be used.

You need to make sure you include installers for the performance counters and event logs that you use; these should be created at installation time (when installing as administrator). When your application is running normally it should not need have administration privileges (and so won't be able to create missing logs).

This is a good reason to practice developing as a non-administrator (have a separate admin account for when you need to install services, etc). If writing to the Event Log, .NET will automatically create a missing log the first time you write to it; if you develop as a non-admin you will catch this early and avoid a nasty surprise when a customer installs your system and then can't use it because they aren't running as administrator.

Node Express sending image files as API response

There is an api in Express.

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

Import data.sql MySQL Docker Container

combine https://stackoverflow.com/a/51837876/1078784 and answers in this question, I think the best answer is:

cat {SQL FILE NAME} | docker exec -i {MYSQL CONTAINER NAME} {MYSQL PATH IN CONTAINER} --init-command="SET autocommit=0;"

for example in my system this command should look like:

cat temp.sql | docker exec -i mysql.master /bin/mysql --init-command="SET autocommit=0;"

also you can use pv to moniter progress:

cat temp.sql | pv | docker exec -i mysql.master /bin/mysql --init-command="SET autocommit=0;"

And the most important thing here is "--init-command" which will speed up the import progress 10 times fast.

How to select last child element in jQuery?

Hi all Please try this property

$( "p span" ).last().addClass( "highlight" );

Thanks

python: SyntaxError: EOL while scanning string literal

In my case, I forgot (' or ") at the end of string. E.g 'ABC' or "ABC"

How do I find all of the symlinks in a directory tree?

To see just the symlinks themselves, you can use

find -L /path/to/dir/ -xtype l 

while if you want to see also which files they target, just append an ls

find -L /path/to/dir/ -xtype l -exec ls -al {} \;

Disabling and enabling a html input button

Stick to php...

Why not only allow the button to appear once an above criteria is met.

<?
if (whatever == something) {
    $display = '<input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/>';
    return $display;
}
?>

GSON - Date format

As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.

Gson gson = new GsonBuilder()
   .registerTypeAdapter(java.sql.Date.class, ser).create();

This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.

Plot multiple boxplot in one graph

Since you don't mention a plot package , I propose here using Lattice version( I think there is more ggplot2 answers than lattice ones, at least since I am here in SO).

 ## reshaping the data( similar to the other answer)
 library(reshape2)
 dat.m <- melt(TestData,id.vars='Label')
 library(lattice)
 bwplot(value~Label |variable,    ## see the powerful conditional formula 
        data=dat.m,
        between=list(y=1),
        main="Bad or Good")

enter image description here

How to disable the back button in the browser using JavaScript

One cannot disable the browser back button functionality. The only thing that can be done is prevent them.

The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:

<script>
    function preventBack() {
        window.history.forward();
    }

    setTimeout("preventBack()", 0);
    window.onunload = function() {
        null
    };
</script>

Suppose there are two pages Page1.php and Page2.php and Page1.php redirects to Page2.php.

Hence to prevent user from visiting Page1.php using the back button you will need to place the above script in the head section of Page1.php.

For more information: Reference

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

One word answer: asynchronicity.

Forewords

This topic has been iterated at least a couple of thousands of times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:


The answer to the question at hand

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been canceled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, the asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

async code highlighted

In short, the callback functions are created synchronously but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs too inside the callback function would output the expected result, because the result is available at that point.

Implementing your own callback logic

Often you need to do more things with the result from an asynchronous function or do different things with the result depending on where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Code snippet of the above example:

_x000D_
_x000D_
// 1. Call helloCatAsync passing a callback function,_x000D_
//    which will be called receiving the result from the async operation_x000D_
console.log("1. function called...")_x000D_
helloCatAsync(function(result) {_x000D_
    // 5. Received the result from the async function,_x000D_
    //    now do whatever you want with it:_x000D_
    console.log("5. result is: ", result);_x000D_
});_x000D_
_x000D_
// 2. The "callback" parameter is a reference to the function which_x000D_
//    was passed as argument from the helloCatAsync call_x000D_
function helloCatAsync(callback) {_x000D_
    console.log("2. callback here is the function passed as argument above...")_x000D_
    // 3. Start async operation:_x000D_
    setTimeout(function() {_x000D_
    console.log("3. start async operation...")_x000D_
    console.log("4. finished async operation, calling the callback, passing the result...")_x000D_
        // 4. Finished async operation,_x000D_
        //    call the callback passing the result as argument_x000D_
        callback('Nya');_x000D_
    }, Math.random() * 2000);_x000D_
}
_x000D_
_x000D_
_x000D_

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Promises

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of the asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:


More reading material about JavaScript asynchronicity


Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputations can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

Viewing root access files/folders of android on windows

You can use Eclipse DDMS perspective to see connected devices and browse through files, you can also pull and push files to the device. You can also do a bunch of stuff using DDMS, this link explains a little bit more of DDMS uses.

EDIT:

If you just want to copy a database you can locate the database on eclipse DDMS file explorer, select it and then pull the database from the device to your computer.

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

The solution is already answered here above (long ago).

But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).

This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.

How do I put text on ProgressBar?

I have used this simple code, and it works!

for (int i = 0; i < N * N; i++)
     {
        Thread.Sleep(50);
        progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
        progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
        (float)10.25, FontStyle.Bold),
        Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
     }

It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#

I used this code, and it does work.

VB.NET - If string contains "value1" or "value2"

I've approached this in a different way. I've created a function which simply returns true or false.. Usage:

If FieldContains("A;B;C",MyFieldVariable,True|False) then

.. Do Something

End If

Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean

       If AllowNulls And Len(SearchField) = 0 Then Return True

        For Each strSearchFor As String In Searchfor.Split(";")
            If UCase(SearchField) = UCase(strSearchFor) Then
                Return True
            End If
        Next

        Return False

    End Function

SyntaxError: Cannot use import statement outside a module

Step 1

yarn add esm

or

npm i esm --save

Step 2

package.json

  "scripts": {
    "start": "node -r esm src/index.js",
  }

Step 3

nodemon --exec npm start

Line continue character in C#

You must use one of the following ways:

    string s = @"loooooooooooooooooooooooong loooooong
                  long long long";

string s = "loooooooooong loooong" +
           " long long" ;

Best way to iterate through a Perl array

  • In terms of speed: #1 and #4, but not by much in most instances.

    You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. ($_ is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)

    #5 might be similar.

  • In terms memory usage: They're all the same except for #5.

    for (@a) is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.

  • In terms of readability: #1.

  • In terms of flexibility: #1/#4 and #5.

    #2 does not support elements that are false. #2 and #3 are destructive.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How to split a delimited string in Ruby and convert it to an array?

"12345".each_char.map(&:to_i)

each_char does basically the same as split(''): It splits a string into an array of its characters.

hmmm, I just realize now that in the original question the string contains commas, so my answer is not really helpful ;-(..

invalid use of non-static member function

The simplest fix is to make the comparator function be static:

static int comparator (const Bar & first, const Bar & second);
^^^^^^

When invoking it in Count, its name will be Foo::comparator.

The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo.

Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo.

Enterprise app deployment doesn't work on iOS 7.1

ingconti is right.

  1. Upload your app.plist to dropbox.
  2. Get shared link of app.plist, like https://www.dropbox.com/s/qgknrfngaxazm38/app.plist
  3. replace www.dropbox.com with dl.dropboxusercontent.com in the link, like https://dl.dropboxusercontent.com/s/qgknrfngaxazm38/app.plist
  4. Remove any parameters on the dropbox shareable link such as "?dl=0t" (as per Carlos Aguirre Tradeco at Enterprise app deployment doesn't work on iOS 7.1 and my own experience).
  5. Create a download.html file with a link formatted as <a href="itms-services://?action=download-manifest&url=https://dl.dropboxusercontent.com/s/qgknrfngaxazm38/app.plist">INSTALL!!</a>
  6. Upload your download.html to dropbox
  7. Again, get a shared link of download.html, like https://www.dropbox.com/s/gnoctp7n9g0l3hx/download.html, and remove any parameters.
  8. Replace www.dropbox.com with dl.dropboxusercontent.com in the second link as well, like https://dl.dropboxusercontent.com/s/gnoctp7n9g0l3hx/download.html

Now, visit https://dl.dropboxusercontent.com/s/gnoctp7n9g0l3hx/download.html in your device, you can install the app like before.

WHAT A WONDERFUL WORLD!

How to get All input of POST in Laravel

You can get all post data into this function :-

$postData = $request->post();

and if you want specific filed then use it :-

$request->post('current-password');

How to concatenate two strings in SQL Server 2005

Try this:

DECLARE @COMBINED_STRINGS AS VARCHAR(50); -- Allocate just enough length for the two strings.

SET @COMBINED_STRINGS = 'rupesh''s' + 'malviya';
SELECT @COMBINED_STRINGS; -- Print your combined strings.

Or you can put your strings into variables. Such that:

DECLARE @COMBINED_STRINGS AS VARCHAR(50),
        @STRING1 AS VARCHAR(20),
        @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;

SELECT @COMBINED_STRINGS; 

Output:

rupesh'smalviya

Just add a space in your string as a separator.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

My way is importing the jquery library.

<script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>