Programs & Examples On #Inotifycollectionchanged

is a .NET interface for providing collection subscribers notification on changes, mostly used in WPF UI binding.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

You will have to be careful binding the UI to your custom collection -- the Default CollectionView class only supports single notification of items.

Check if DataRow exists by column name in c#?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

Something like:

DataColumnCollection Columns = dtItems.Columns;

if (Columns.Contains(ColNameToCheck))
{
  row["ColNameToCheck"] = "Checked";
}

No resource found that matches the given name '@style/Theme.AppCompat.Light'

Below are the steps you can try it out to resolve the issue: -

  1. Provide reference of AppCompat Library into your project.
  2. If option 1 doesn't solve the issue then you can try to change the style.xml file to below code.
 parent="android:Theme.Holo.Light"  

instead.

 parent="android:Theme.AppCompat.Light"  

But option 2 will require minimum sdk version 14.

Hope this will help !

Summved

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

SQL multiple column ordering

SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC

"Cannot update paths and switch to branch at the same time"

You can get this error in the context of, e.g. a Travis build that, by default, checks code out with git clone --depth=50 --branch=master. To the best of my knowledge, you can control --depth via .travis.yml but not the --branch. Since that results in only a single branch being tracked by the remote, you need to independently update the remote to track the desired remote's refs.

Before:

$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master

The fix:

$ git remote set-branches --add origin branch-1
$ git remote set-branches --add origin branch-2
$ git fetch

After:

$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/branch-1
remotes/origin/branch-2
remotes/origin/master

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

COPY copies a file/directory from your host to your image.

ADD copies a file/directory from your host to your image, but can also fetch remote URLs, extract TAR files, etc...

Use COPY for simply copying files and/or directories into the build context.

Use ADD for downloading remote resources, extracting TAR files, etc..

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

Pass data from Activity to Service using an Intent

Service: startservice can cause side affects,best way to use messenger and pass data.

private CallBackHandler mServiceHandler= new CallBackHandler(this);
private Messenger mServiceMessenger=null;
//flag with which the activity sends the data to service
private static final int DO_SOMETHING=1;

private static class CallBackHandler extends android.os.Handler {

private final WeakReference<Service> mService;

public CallBackHandler(Service service) {
    mService= new WeakReference<Service>(service);
}

public void handleMessage(Message msg) {
    //Log.d("CallBackHandler","Msg::"+msg);
    if(DO_SOMETHING==msg.arg1)
    mSoftKeyService.get().dosomthing()
}
}

Activity:Get Messenger from Intent fill it pass data and pass the message back to service

private Messenger mServiceMessenger;
@Override
protected void onCreate(Bundle savedInstanceState) {
mServiceMessenger = (Messenger)extras.getParcelable("myHandler");
}


private void sendDatatoService(String data){
Intent serviceIntent= new 
Intent(BaseActivity.this,Service.class);
Message msg = Message.obtain();
msg.obj =data;
msg.arg1=Service.DO_SOMETHING;
mServiceMessenger.send(msg);
}

WAMP Cannot access on local network 403 Forbidden

I got this answer from here. and its works for me

Require local

Change to

Require all granted
Order Deny,Allow
Allow from all

How to drop all tables from the database with manage.py CLI in Django?

This answer is for postgresql DB:

Run: echo 'drop owned by some_user' | ./manage.py dbshell

NOTE: some_user is the name of the user you use to access the database, see settings.py file:

default_database = {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'somedbname',
    'USER': 'some_user',
    'PASSWORD': 'somepass',
    'HOST': 'postgresql',
    'PORT': '',
}

How to get a list of column names

Use a recursive query. Given

create table t (a int, b int, c int);

Run:

with recursive
  a (cid, name) as (select cid, name from pragma_table_info('t')),
  b (cid, name) as (
    select cid, '|' || name || '|' from a where cid = 0
    union all
    select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
  )
select name
from b
order by cid desc
limit 1;

Alternatively, just use group_concat:

select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')

Both yield:

|a|b|c|

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

deleted the c#... here is the vb.net

<%=Html.ActionLink("Home", "Index", "Home", New With {.class = "tab"}, Nothing)%>

Change the default base url for axios

  1. Create .env.development, .env.production files if not exists and add there your API endpoint, for example: VUE_APP_API_ENDPOINT ='http://localtest.me:8000'
  2. In main.js file, add this line after imports: axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT

And that's it. Axios default base Url is replaced with build mode specific API endpoint. If you need specific baseURL for specific request, do it like this:

this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

How do I make a matrix from a list of vectors in R?

t(sapply(a, '[', 1:max(sapply(a, length))))

where 'a' is a list. Would work for unequal row size

Explain ggplot2 warning: "Removed k rows containing missing values"

The behavior you're seeing is due to how ggplot2 deals with data that are outside the axis ranges of the plot. You can change this behavior depending on whether you use scale_y_continuous (or, equivalently, ylim) or coord_cartesian to set axis ranges, as explained below.

library(ggplot2)

# All points are visible in the plot
ggplot(mtcars, aes(mpg, hp)) + 
  geom_point()

In the code below, one point with hp = 335 is outside the y-range of the plot. Also, because we used scale_y_continuous to set the y-axis range, this point is not included in any other statistics or summary measures calculated by ggplot, such as the linear regression line.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(0,300)) +  # Change this to limits=c(0,335) and the warning disappars
  geom_smooth(method="lm")

Warning messages:
1: Removed 1 rows containing missing values (stat_smooth). 
2: Removed 1 rows containing missing values (geom_point).

In the code below, the point with hp = 335 is still outside the y-range of the plot, but this point is nevertheless included in any statistics or summary measures that ggplot calculates, such as the linear regression line. This is because we used coord_cartesian to set the y-axis range, and this function does not exclude points that are outside the plot ranges when it does other calculations on the data.

If you compare this and the previous plot, you can see that the linear regression line in the second plot has a slightly steeper slope, because the point with hp=335 is included when calculating the regression line, even though it's not visible in the plot.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  coord_cartesian(ylim=c(0,300)) +
  geom_smooth(method="lm")

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

How can I download a specific Maven artifact in one command line?

To copy artifact in specified location use copy instead of get.

mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.2:copy \
  -DrepoUrl=someRepositoryUrl \
  -Dartifact="com.acme:foo:RELEASE:jar" -Dmdep.stripVersion -DoutputDirectory=/tmp/

An existing connection was forcibly closed by the remote host - WCF

I found that you can get this error if the returned object has getter only auto properties that are initialized in the constructor (with C# 6.0 syntax).

I believe this is due to WCF deserializing objects on the client side using a parameter-less constructor then setting the properties on the object. It needs to have a set available (it can be private) to fill the object, otherwise it'll fail.

How to use multiprocessing pool.map with multiple arguments?

Having learnt about itertools in J.F. Sebastian answer I decided to take it a step further and write a parmap package that takes care about parallelization, offering map and starmap functions on python-2.7 and python-3.2 (and later also) that can take any number of positional arguments.

Installation

pip install parmap

How to parallelize:

import parmap
# If you want to do:
y = [myfunction(x, argument1, argument2) for x in mylist]
# In parallel:
y = parmap.map(myfunction, mylist, argument1, argument2)

# If you want to do:
z = [myfunction(x, y, argument1, argument2) for (x,y) in mylist]
# In parallel:
z = parmap.starmap(myfunction, mylist, argument1, argument2)

# If you want to do:
listx = [1, 2, 3, 4, 5, 6]
listy = [2, 3, 4, 5, 6, 7]
param = 3.14
param2 = 42
listz = []
for (x, y) in zip(listx, listy):
        listz.append(myfunction(x, y, param1, param2))
# In parallel:
listz = parmap.starmap(myfunction, zip(listx, listy), param1, param2)

I have uploaded parmap to PyPI and to a github repository.

As an example, the question can be answered as follows:

import parmap

def harvester(case, text):
    X = case[0]
    text+ str(X)

if __name__ == "__main__":
    case = RAW_DATASET  # assuming this is an iterable
    parmap.map(harvester, case, "test", chunksize=1)

CGContextDrawImage draws image upside down when passed UIImage.CGImage

Swift 3.0 & 4.0

yourImage.draw(in: CGRect, blendMode: CGBlendMode, alpha: ImageOpacity)

No Alteration needed

How to Update a Component without refreshing full page - Angular

You can use a BehaviorSubject for communicating between different components throughout the app. You can define a data sharing service containing the BehaviorSubject to which you can subscribe and emit changes.

Define a data sharing service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataSharingService {
    public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}

Add the DataSharingService in your AppModule providers entry.

Next, import the DataSharingService in your <app-header> and in the component where you perform the sign-in operation. In <app-header> subscribe to the changes to isUserLoggedIn subject:

import { DataSharingService } from './data-sharing.service';

export class AppHeaderComponent { 
    // Define a variable to use for showing/hiding the Login button
    isUserLoggedIn: boolean;

    constructor(private dataSharingService: DataSharingService) {

        // Subscribe here, this will automatically update 
        // "isUserLoggedIn" whenever a change to the subject is made.
        this.dataSharingService.isUserLoggedIn.subscribe( value => {
            this.isUserLoggedIn = value;
        });
    }
}

In your <app-header> html template, you need to add the *ngIf condition e.g.:

<button *ngIf="!isUserLoggedIn">Login</button> 
<button *ngIf="isUserLoggedIn">Sign Out</button>

Finally, you just need to emit the event once the user has logged in e.g:

someMethodThatPerformsUserLogin() {
    // Some code 
    // .....
    // After the user has logged in, emit the behavior subject changes.
    this.dataSharingService.isUserLoggedIn.next(true);
}

How can I truncate a string to the first 20 words in PHP?

To Nearest Space

Truncates to nearest preceding space of target character. Demo

  • $str The string to be truncated
  • $chars The amount of characters to be stripped, can be overridden by $to_space
  • $to_space boolean for whether or not to truncate from space near $chars limit

Function

function truncateString($str, $chars, $to_space, $replacement="...") {
   if($chars > strlen($str)) return $str;

   $str = substr($str, 0, $chars);
   $space_pos = strrpos($str, " ");
   if($to_space && $space_pos >= 0) 
       $str = substr($str, 0, strrpos($str, " "));

   return($str . $replacement);
}

Sample

<?php

$str = "this is a string that is just some text for you to test with";

print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");

?>

Output

this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--

Reading RFID with Android phones

I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.

More devices are from Motorola & other vendors as well!

We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).

The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!

This is the sample app:

We get all the device paired to our Android/iOS phones :

get device list

connect

connected

Scan

Cleanest way to build an SQL string in Java

I second the recommendations for using an ORM like Hibernate. However, there are certainly situations where that doesn't work, so I'll take this opportunity to tout some stuff that i've helped to write: SqlBuilder is a java library for dynamically building sql statements using the "builder" style. it's fairly powerful and fairly flexible.

Javascript - validation, numbers only

// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:

$(document).ready(function () {
       $(".nosonly").keydown(function (event) {
           // Allow only backspace and delete
           if (event.keyCode == 46 || event.keyCode == 8) {
               // let it happen, don't do anything
           }
           else {
               // Ensure that it is a number and stop the keypress
               if (event.keyCode < 48 || event.keyCode > 57) {
              alert("Only Numbers Allowed"),event.preventDefault();
               }
           }
       });
   });

How to center the text in PHPExcel merged cell

<?php
    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Europe/London');

    /** Include PHPExcel */
    require_once '../Classes/PHPExcel.php';

    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValueByColumnAndRow(0, 1, "test");
    $sheet->mergeCells('A1:B1');
    $sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save("test.xlsx");
?>

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

What is the perfect counterpart in Python for "while not EOF"

While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --

try:
    line = raw_input()
    ... whatever needs to be done incase of no EOF ...
except EOFError:
    ... whatever needs to be done incase of EOF ...

Example:

$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
  File "<string>", line 1, in <module> 
EOFError: EOF when reading a line

Or press Ctrl-Z at a raw_input() prompt (Windows, Ctrl-Z Linux)

How to use if-else option in JSTL

This is good and efficient approach as per time complexity prospect. Once it will get a true condition , it will not check any other after this. In multiple If , it will check each and condition.

   <c:choose>
      <c:when test="${condtion1}">
        do something condtion1
      </c:when>
      <c:when test="${condtion2}">
        do something condtion2
      </c:when>
      ......
      ......
      ...... 
      .......

      <c:when test="${condtionN}">
        do something condtionn N
      </c:when>


      <c:otherwise>
        do this w
      </c:otherwise>
    </c:choose>

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

How do I set the background color of my main screen in Flutter?

and it's another approach to change the color of background:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(backgroundColor: Colors.pink,),);
  }
}

Does a `+` in a URL scheme/host/path represent a space?

Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.

The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.

But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:

(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const    
  HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
  I: Integer;
  c: AnsiChar;
begin
 // percent-encoding, see RFC-3986, p. 2.1
  Result := S;
  for I := Length(S) downto 1 do
  begin
    c := S[I];
    case c of
      'A' .. 'Z', 'a' .. 'z', // alpha
      '0' .. '9',             // digit
      '-', '.', '_', '~':;    // rest of unreserved characters as defined in the RFC-3986, p.2.3
      else
        begin
          Result[I] := '%';
          Insert('00', Result, I + 1);
          Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
          Result[I + 2] := HexCharArrA[Byte(C) and $F];
        end;
    end;
  end;
end;

function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
  Result := UrlEncodeRfcA(Utf8Encode(S));
end;

<script> tag vs <script type = 'text/javascript'> tag

<!-- HTML4 and (x)HTML -->
<script type="text/javascript"></script>


<!-- HTML5 -->
<script></script>

type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript. If this attribute is absent, the script is treated as JavaScript.

Ref: https://developer.mozilla.org/en/docs/Web/HTML/Element/script

Open source PDF library for C/C++ application?

I worked on a project that required a pdf report. After searching for online I found the PoDoFo library. Seemed very robust. I did not need all the features, so I created a wrapper to abstract away some of the complexity. Wasn't too difficult. You can find the library here:

http://podofo.sourceforge.net/

Enjoy!

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Google Chrome form autofill and its yellow background

Here's a Mootools solution doing the same as Alessandro's - replaces each affected input with a new one.

if (Browser.chrome) {
    $$('input:-webkit-autofill').each(function(item) {
        var text = item.value;
        var name = item.get('name');
        var newEl = new Element('input');
        newEl.set('name', name);
        newEl.value = text;
        newEl.replaces(item);
    });
}

Removing a non empty directory programmatically in C or C++

Many unix-like systems (Linux, the BSDs, and OS X, at the very least) have the fts functions for directory traversal.

To recursively delete a directory, perform a depth-first traversal (without following symlinks) and remove every visited file:

int recursive_delete(const char *dir)
{
    int ret = 0;
    FTS *ftsp = NULL;
    FTSENT *curr;

    // Cast needed (in C) because fts_open() takes a "char * const *", instead
    // of a "const char * const *", which is only allowed in C++. fts_open()
    // does not modify the argument.
    char *files[] = { (char *) dir, NULL };

    // FTS_NOCHDIR  - Avoid changing cwd, which could cause unexpected behavior
    //                in multithreaded programs
    // FTS_PHYSICAL - Don't follow symlinks. Prevents deletion of files outside
    //                of the specified directory
    // FTS_XDEV     - Don't cross filesystem boundaries
    ftsp = fts_open(files, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, NULL);
    if (!ftsp) {
        fprintf(stderr, "%s: fts_open failed: %s\n", dir, strerror(errno));
        ret = -1;
        goto finish;
    }

    while ((curr = fts_read(ftsp))) {
        switch (curr->fts_info) {
        case FTS_NS:
        case FTS_DNR:
        case FTS_ERR:
            fprintf(stderr, "%s: fts_read error: %s\n",
                    curr->fts_accpath, strerror(curr->fts_errno));
            break;

        case FTS_DC:
        case FTS_DOT:
        case FTS_NSOK:
            // Not reached unless FTS_LOGICAL, FTS_SEEDOT, or FTS_NOSTAT were
            // passed to fts_open()
            break;

        case FTS_D:
            // Do nothing. Need depth-first search, so directories are deleted
            // in FTS_DP
            break;

        case FTS_DP:
        case FTS_F:
        case FTS_SL:
        case FTS_SLNONE:
        case FTS_DEFAULT:
            if (remove(curr->fts_accpath) < 0) {
                fprintf(stderr, "%s: Failed to remove: %s\n",
                        curr->fts_path, strerror(curr->fts_errno));
                ret = -1;
            }
            break;
        }
    }

finish:
    if (ftsp) {
        fts_close(ftsp);
    }

    return ret;
}

Algorithm to randomly generate an aesthetically-pleasing color palette

In javascript:

function pastelColors(){
    var r = (Math.round(Math.random()* 127) + 127).toString(16);
    var g = (Math.round(Math.random()* 127) + 127).toString(16);
    var b = (Math.round(Math.random()* 127) + 127).toString(16);
    return '#' + r + g + b;
}

Saw the idea here: http://blog.functionalfun.net/2008/07/random-pastel-colour-generator.html

How to check if a service is running via batch file and start it, if it is not running?

That should do it:

FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)

How do you display a Toast from a background thread on Android?

You can use Looper to send Toast message. Go through this link for more details.

public void showToastInThread(final Context context,final String str){
    Looper.prepare();
    MessageQueue queue = Looper.myQueue();
    queue.addIdleHandler(new IdleHandler() {
         int mReqCount = 0;

         @Override
         public boolean queueIdle() {
             if (++mReqCount == 2) {
                  Looper.myLooper().quit();
                  return false;
             } else
                  return true;
         }
    });
    Toast.makeText(context, str,Toast.LENGTH_LONG).show();      
    Looper.loop();
}

and it is called in your thread. Context may be Activity.getContext() getting from the Activity you have to show the toast.

Change column type in pandas

Here is a function that takes as its arguments a DataFrame and a list of columns and coerces all data in the columns to numbers.

# df is the DataFrame, and column_list is a list of columns as strings (e.g ["col1","col2","col3"])
# dependencies: pandas

def coerce_df_columns_to_numeric(df, column_list):
    df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

So, for your example:

import pandas as pd

def coerce_df_columns_to_numeric(df, column_list):
    df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col1','col2','col3'])

coerce_df_columns_to_numeric(df, ['col2','col3'])

GitHub "fatal: remote origin already exists"

The concept of remote is simply the URL of your remote repository.

The origin is an alias pointing to that URL. So instead of writing the whole URL every single time we want to push something to our repository, we just use this alias and run:

git push -u origin master

Telling to git to push our code from our local master branch to the remote origin repository.

Whenever we clone a repository, git creates this alias for us by default. Also whenever we create a new repository, we just create it our self.

Whatever the case it is, we can always change this name to anything we like, running this:

git remote rename [current-name] [new-name]

Since it is stored on the client side of the git application (on our machine) changing it will not affect anything in our development process, neither at our remote repository. Remember, it is only a name pointing to an address.

The only thing that changes here by renaming the alias, is that we have to declare this new name every time we push something to our repository.

git push -u my-remote-alias master

Obviously a single name can not point to two different addresses. That's why you get this error message. There is already an alias named origin at your local machine. To see how many aliases you have and what are they, you can initiate this command:

git remote -v

This will show you all the aliases you have plus the corresponding URLs.

You can remove them as well if you like running this:

git remote rm my-remote-alias

So in brief:

  • find out what do you have already,
  • remove or rename them,
  • add your new aliases.

Happy coding.

selecting rows with id from another table

Try this (subquery):

SELECT * FROM terms WHERE id IN 
   (SELECT term_id FROM terms_relation WHERE taxonomy = "categ")

Or you can try this (JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

If you want to receive all fields from two tables:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

How to change int into int64?

This is called type conversion :

i := 23
var i64 int64
i64 = int64(i)

Format date and time in a Windows batch script

set hourstr = %time:~0,2%
if "%time:~0,1%"==" " (set hourstr=0%time:~1,1%)
set datetimestr=%date:~0,4%%date:~5,2%%date:~8,2%-%hourstr%%time:~3,2%%time:~6,2%

Converting string to byte array in C#

If you already have a byte array then you will need to know what type of encoding was used to make it into that byte array.

For example, if the byte array was created like this:

byte[] bytes = Encoding.ASCII.GetBytes(someString);

You will need to turn it back into a string like this:

string someString = Encoding.ASCII.GetString(bytes);

If you can find in the code you inherited, the encoding used to create the byte array then you should be set.

Java HashMap: How to get a key and value by index?

If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values() method

Map<String, List<String>> myMap;

for ( List<String> stringList : myMap.values() ) {
    for ( String myString : stringList ) {
        // process the string here
    }
}

The values() method is part of the Map interface and returns a Collection view of the values in the map.

How do I disable "missing docstring" warnings at a file-level in Pylint?

I came looking for an answer because, as cerin said, in Django projects it is cumbersome and redundant to add module docstrings to every one of the files that Django automatically generates when creating a new application.

So, as a workaround for the fact that Pylint doesn't let you specify a difference in docstring types, you can do this:

pylint */*.py --msg-template='{path}: {C}:{line:3d},{column:2d}: {msg}' | grep docstring | grep -v module

You have to update the msg-template, so that when you grep you will still know the file name. This returns all the other missing-docstring types excluding modules.

Then you can fix all of those errors, and afterwards just run:

pylint */*.py --disable=missing-docstring

CSS Printing: Avoiding cut-in-half DIVs between pages?

The possible values for page-break-after are: auto, always, avoid, left, right

I believe that you can’t use thie page-break-after property on absolutely positioned elements.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

Killing a process created with Python's subprocess.Popen()

Only use Popen kill method

process = subprocess.Popen(
    task.getExecutable(), 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE, 
    shell=True
)
process.kill()

How to position the div popup dialog to the center of browser screen?

You can use CSS3 'transform':

CSS:

.popup-bck{
  background-color: rgba(102, 102, 102, .5);
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}
.popup-content-box{
  background-color: white;
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 11;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

HTML:

<div class="popup-bck"></div>
<div class="popup-content-box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
</div>

*so you don't have to use margin-left: -width/2 px;

How do I add a bullet symbol in TextView?

Since android doesnt support <ol>, <ul> or <li> html elements, I had to do it like this

<string name="names"><![CDATA[<p><h2>List of Names:</h2></p><p>&#8226;name1<br />&#8226;name2<br /></p>]]></string>

if you want to maintain custom space then use </pre> tag

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How to access full source of old commit in BitBucket?

I know it's too late, but with API 2.0 you can do

from command line with:

curl https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>

or in php with:

$data = json_decode(file_get_contents("https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>", true));

then you have the history of your file (from the most recent commit to the oldest one):

{
"pagelen": 50,
"values": [
    {
      "links": {
        "self": {
          "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<hash>/<path_file>"
        },
        "meta": {
          "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD>/<path_file>?format=meta"
        },
        "history": {
          "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<HEAD>/<path_file>"
        }
      },
      "commit": {
        "hash": "<HEAD>",
        "type": "commit",
        "links": {
          "self": {
            "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/commit/<HEAD>"
          },
          "html": {
            "href": "https://bitbucket.org/<user>/<repo>/commits/<HEAD>"
          }
        }
      },
      "attributes": [],
      "path": "<path_file>",
      "type": "commit_file",
      "size": 31
    },
    {
      "links": {
        "self": {
          "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD~1>/<path_file>"
        },
        "meta": {
          "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD~1>/<path_file>?format=meta"
        },
        "history": {
          "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<HEAD~1>/<path_file>"
        }
      },
      "commit": {
        "hash": "<HEAD~1>",
        "type": "commit",
        "links": {
          "self": {
            "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/commit/<HEAD~1>"
          },
          "html": {
            "href": "https://bitbucket.org/<user>/<repo>/commits/<HEAD~1>"
          }
        }
      },
      "attributes": [],
      "path": "<path_file>",
      "type": "commit_file",
      "size": 20
    }
  ],
  "page": 1
}

where values > links > self provides the file at the moment in the history which you can retrieve it with curl <link> or file_get_contents(<link>).

Eventually, from the command line you can filter with:

 curl https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>?fields=values.links.self

in php, just make a foreach loop on the array $data.

Note: if <path_file> has a / you have to convert it in %2F.

See the doc here: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/filehistory/%7Bnode%7D/%7Bpath%7D

Split string based on regex

I suggest

l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)

Check this demo.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

Neither code is always better. They do different things, so they are good at different things.

InvariantCultureIgnoreCase uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.

OrdinalIgnoreCase compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é or ö. This is also faster because there are no extra rules to apply before comparing.

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

starting file download with JavaScript

A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.

If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.

How to get a responsive button in bootstrap 3

In some cases it's very useful to change font-size with relative font sizing units. For example:

.btn {font-size: 3vw;}

Demo: http://www.bootply.com/7VN5OCVhhF

1vw is 1% of the viewport width. More info: http://www.sitepoint.com/new-css3-relative-font-size/

Better way to set distance between flexbox items

I often use the + operator for such cases

_x000D_
_x000D_
#box {_x000D_
  display: flex;_x000D_
  width: 100px;_x000D_
}_x000D_
.item {_x000D_
  background: gray;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}_x000D_
.item + .item {_x000D_
    margin-left: 5px;_x000D_
}
_x000D_
<div id='box'>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check status of PostgreSQL server Mac OS X

As of PostgreSQL 9.3, you can use the command pg_isready to determine the connection status of a PostgreSQL server.

From the docs:

pg_isready returns 0 to the shell if the server is accepting connections normally, 1 if the server is rejecting connections (for example during startup), 2 if there was no response to the connection attempt, and 3 if no attempt was made (for example due to invalid parameters).

How to get the first five character of a String

Append five whitespace characters then cut off the first five and trim the result. The number of spaces you append should match the number you are cutting. Be sure to include the parenthesis before .Substring(0,X) or you'll append nothing.

string str = (yourStringVariable + "    ").Substring(0,5).Trim();

With this technique you won't have to worry about the ArgumentOutOfRangeException mentioned in other answers.

Print second last column/field in awk

You weren't far from the result! This does it:

awk '{NF--; print $NF}' file

This decrements the number of fields in one, so that $NF contains the former penultimate.

Test

Let's generate some numbers and print them on groups of 5:

$ seq 12 | xargs -n5
1 2 3 4 5
6 7 8 9 10
11 12

Let's print the penultimate on each line:

$ seq 12 | xargs -n5 | awk '{NF--; print $NF}'
4
9
11

Chrome Extension: Make it run every page load

This code should do it:

manifest.json

   {
      "name": "Alert 'hello world!' on page opening",
      "version": "1.0",
      "manifest_version": 2,
      "content_scripts": [
        {
          "matches": [
            "<all_urls>"
          ],
          "js": ["content.js"]
        }
      ]
    }

content.js

alert('Hello world!')

jQuery ajax upload file in asp.net mvc

If you posting form using ajax then you can not send image using $.ajax method, you have to use classic xmlHttpobject method for saving image, other alternative of it use submit type instead of button

What is meant by immutable?

An immutable object is the one you cannot modify after you create it. A typical example are string literals.

A D programming language, which becomes increasingly popular, has a notion of "immutability" through "invariant" keyword. Check this Dr.Dobb's article about it - http://dobbscodetalk.com/index.php?option=com_myblog&show=Invariant-Strings.html&Itemid=29 . It explains the problem perfectly.

Traverse a list in reverse order in Python

The other answers are good, but if you want to do as List comprehension style

collection = ['a','b','c']
[item for item in reversed( collection ) ]

How to determine the screen width in terms of dp or dip at runtime in Android?

I stumbled upon this question from Google, and later on I found an easy solution valid for API >= 13.

For future references:

Configuration configuration = yourActivity.getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.

See Configuration class reference

Edit: As noted by Nick Baicoianu, this returns the usable width/height of the screen (which should be the interesting ones in most uses). If you need the actual display dimensions stick to the top answer.

catch forEach last iteration

The 2018 ES6+ ANSWER IS:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

Populate nested array in mongoose

If you would like to populate another level deeper, here's what you need to do:

Airlines.findById(id)
      .populate({
        path: 'flights',
        populate:[
          {
            path: 'planeType',
            model: 'Plane'
          },
          {
          path: 'destination',
          model: 'Location',
          populate: { // deeper
            path: 'state',
            model: 'State',
            populate: { // even deeper
              path: 'region',
              model: 'Region'
            }
          }
        }]
      })

jquery change style of a div on click

If I understand correctly you want to change the CSS style of an element by clicking an item in a ul list. Am I right?

HTML:

<div class="results" style="background-color:Red;">
</div>

 <ul class="colors-list">
     <li>Red</li>
     <li>Blue</li>
     <li>#ffee99</li>
 </ul>

jquery

$('.colors-list li').click(function(e){
    var color = $(this).text();
    $('.results').css('background-color',color);
});

Note that jquery can use addClass, removeClass and toggleClass if you want to use classes rather than inline styling. This means that you can do something like that:

$('.results').addClass('selected');

And define the 'selected' styling in the CSS.

Working example: http://jsfiddle.net/uuJmP/

Add querystring parameters to link_to

If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:

# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>

 

If you use it in multiple places, clean the params in the controller:

# your_controller.rb
@params = params.slice(:sort, :per_page)

# view
<%= link_to 'Link', @params.merge(per_page: 20) %>

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)

{'a': 1, 'c': 7, 'b': 5, 'd': 5}

CSS position absolute full width problem

You need to add position:relative to #wrap element.

When you add this, all child elements will be positioned in this element, not browser window.

Regex remove all special characters except numbers?

to remove symbol use tag [ ]

step:1

[]

step 2:place what symbol u want to remove eg:@ like [@]

[@]

step 3:

var name = name.replace(/[@]/g, "");

thats it

_x000D_
_x000D_
var name="ggggggg@fffff"
var result = name.replace(/[@]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

Extra Tips

To remove space (give one space into square bracket like []=>[ ])

[@ ]

It Remove Everything (using except)

[^place u dont want to remove]

eg:i remove everyting except alphabet (small and caps)

[^a-zA-Z ]

_x000D_
_x000D_
var name="ggggg33333@#$%^&**I(((**gg@fffff"
var result = name.replace(/[^a-zA-Z]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

Laravel: Auth::user()->id trying to get a property of a non-object

you must check is user loggined ?

Auth::check() ? Auth::user()->id : null

How to convert DateTime to VarChar

CONVERT(VARCHAR, GETDATE(), 23)

Can I scroll a ScrollView programmatically in Android?

just page scroll:

ScrollView sv = (ScrollView) findViewById(your_scroll_view);
sv.pageScroll(View.FOCUS_DOWN);

How to test enum types?

I agree with aberrant80.

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

I would expand on it by adding that unit testings an Enum can be very useful. If you work in a large code base, build time starts to mount up and a unit test can be a faster way to verify functionality (tests only build their dependencies). Another really big advantage is that other developers cannot change the functionality of your code unintentionally (a huge problem with very large teams).

And with all Test Driven Development, tests around an Enums Methods reduce the number of bugs in your code base.

Simple Example

public enum Multiplier {
    DOUBLE(2.0),
    TRIPLE(3.0);

    private final double multiplier;

    Multiplier(double multiplier) {
        this.multiplier = multiplier;
    }

    Double applyMultiplier(Double value) {
        return multiplier * value;
    }

}

public class MultiplierTest {

    @Test
    public void should() {
        assertThat(Multiplier.DOUBLE.applyMultiplier(1.0), is(2.0));
        assertThat(Multiplier.TRIPLE.applyMultiplier(1.0), is(3.0));
    }
}

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Make sure that both projects are in the same .net version also check copy local property but this should be true as default

JavaScript check if value is only undefined, null or false

The best way to do it I think is:

if(val != true){
//do something
} 

This will be true if val is false, NaN, or undefined.

Eclipse hangs on loading workbench

Here's a less destructive method that worked for me:

I'm on Windows machine with a copy of Spring Tool Suite (an extension of Eclipse) which I'm running from a random directory. In my command line prompt, I had to navigate to the directory which contained my STS.exe and run: STS.exe -refresh.

After that, I could open my Eclipse the normal way (which was through a pinned taskbar icon).

Double value to round up in Java

Try this: org.apache.commons.math3.util.Precision.round(double x, int scale)

See: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html

Apache Commons Mathematics Library homepage is: http://commons.apache.org/proper/commons-math/index.html

The internal implemetation of this method is:

public static double round(double x, int scale) {
    return round(x, scale, BigDecimal.ROUND_HALF_UP);
}

public static double round(double x, int scale, int roundingMethod) {
    try {
        return (new BigDecimal
               (Double.toString(x))
               .setScale(scale, roundingMethod))
               .doubleValue();
    } catch (NumberFormatException ex) {
        if (Double.isInfinite(x)) {
            return x;
        } else {
            return Double.NaN;
        }
    }
}

Find index of a value in an array

Just posted my implementation of IndexWhere() extension method (with unit tests):

http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

Example usage:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

Get total of Pandas column

You should use sum:

Total = df['MyColumn'].sum()
print (Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

Compiling an application for use in highly radioactive environments

Someone mentioned using slower chips to prevent ions from flipping bits as easily. In a similar fashion perhaps use a specialized cpu/ram that actually uses multiple bits to store a single bit. Thus providing a hardware fault tolerance because it would be very unlikely that all of the bits would get flipped. So 1 = 1111 but would need to get hit 4 times to actually flipped. (4 might be a bad number since if 2 bits get flipped its already ambiguous). So if you go with 8, you get 8 times less ram and some fraction slower access time but a much more reliable data representation. You could probably do this both on the software level with a specialized compiler(allocate x amount more space for everything) or language implementation (write wrappers for data structures that allocate things this way). Or specialized hardware that has the same logical structure but does this in the firmware.

How to check for null/empty/whitespace values with a single test?

Use below query and it works

SELECT column_name FROM table_name where isnull(column_name,'') <> ''

Group by with union mysql select query

This may be what your after:

SELECT Count(Owner_ID), Name
FROM (
    SELECT M.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Motorbike As M
    WHERE T.Type = 'Motorbike'
    AND O.Owner_ID = M.Owner_ID
    AND T.Type_ID = M.Motorbike_ID

    UNION ALL

    SELECT C.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Car As C
    WHERE T.Type = 'Car'
    AND O.Owner_ID = C.Owner_ID
    AND T.Type_ID = C.Car_ID
)
GROUP BY Owner_ID

Mac SQLite editor

Sqliteman is my current preference: It uses QT, so it's cross-platform. Since I develop on Windows, Linux and OS X, it helps to have the same tools available on each.

I also tried SQLite Admin (Windows, so irrelevant to the question anyway) for a while, but it seems unmaintained these days, and has the most annoying hotkeys of any application I've ever used - Ctrl-S clears the current query, with no hope of undo.

python max function using 'key' and lambda expression

According to the documentation:

max(iterable[, key])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).

What this is saying is that in your case, you are providing a list, in this case players. Then the max function will iterate over all the items in the list and compare them to each other to get a "maximum".

As you can imagine, with a complex object like a player determining its value for comparison is tricky, so you are given the key argument to determine how the max function will decide the value of each player. In this case, you are using a lambda function to say "for each p in players get p.totalscore and use that as his value for comparison".

Check if a string contains another string

You can also use the special word like:

Public Sub Search()
  If "My Big String with, in the middle" Like "*,*" Then
    Debug.Print ("Found ','")
  End If
End Sub

In a bootstrap responsive page how to center a div

I think the simplest way to accomplish the layout with bootstrap is like this:

<section>
<div class="container">
    <div class="row">
        <div align="center">
            <div style="max-width: 200px; background-color: blueviolet;">
                <div>
                    <h1 style="color: white;">Content goes here</h1>
                </div>
            </div>
        </div>
    </div>
</div>

all I did was to add layers of divs that allowed me to center the div, but since I am not using percentages, you need to specify the max-width of the div to be center.

You can use this same method to center more than one column, you just need to add more div layers:

<div class="container">
    <div class="row">
        <div align="center">
            <div style="max-width: 400px; background-color: blueviolet;">
                <div class="col-md-12 col-sm-12 col-xs-12" style="background-color: blueviolet;">
                    <div class="col-md-8 col-sm-8 col-xs-12" style="background-color: darkcyan;">
                        <h1 style="color: white;">Some content</h1>
                    </div>
                    <div class="col-md-4 col-sm-4 col-xs-12" style="background-color: blue;">
                        <p style="color: white;">More content</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Note: that I added a div with column 12 for md, sm and xs, if you don't do this the first div with background color (in this case "blueviolet") will collapse, you will be able to see the child divs, but not the background color.

android start activity from service

UPDATE ANDROID 10 AND HIGHER

Start an activity from service (foreground or background) is no longer allowed.

There are still some restrictions that can be seen in the documentation

https://developer.android.com/guide/components/activities/background-starts

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Use YAML with variables

After some search, I've found a cleaner solution wich use the % operator.

In your YAML file :

key : 'This is the foobar var : %{foobar}'

In your ruby code :

require 'yaml'

file = YAML.load_file('your_file.yml')

foobar = 'Hello World !'
content = file['key']
modified_content = content % { :foobar => foobar }

puts modified_content

And the output is :

This is the foobar var : Hello World !

As @jschorr said in the comment, you can also add multiple variable to the value in the Yaml file :

Yaml :

key : 'The foo var is %{foo} and the bar var is %{bar} !'

Ruby :

# ...
foo = 'FOO'
bar = 'BAR'
# ...
modified_content = content % { :foo => foo, :bar => bar }

Output :

The foo var is FOO and the bar var is BAR !

How do I list all cron jobs for all users?

Since it is a matter of looping through a file (/etc/passwd) and performing an action, I am missing the proper approach on How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:

while IFS=":" read -r user _
do
   echo "crontab for user ${user}:"
   crontab -u "$user" -l
done < /etc/passwd

This reads /etc/passwd line by line using : as field delimiter. By saying read -r user _, we make $user hold the first field and _ the rest (it is just a junk variable to ignore fields).

This way, we can then call crontab -u using the variable $user, which we quote for safety (what if it contains spaces? It is unlikely in such file, but you can never know).

Checking on a thread / remove from list

mythreads = threading.enumerate()

Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html

How to disable gradle 'offline mode' in android studio?

On Windows:-

Go to File -> Settings.

And open the 'Build,Execution,Deployment'. Then open the

Build Tools -> Gradle

Then uncheck -> Offline work on the right.

Click the OK button.

Then Rebuild the Project.

On Mac OS:-

go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image

[For Mac go 1

enter image description here

What does the "$" sign mean in jQuery or JavaScript?

Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:

"test".match( /t(e)st/ );
alert( RegExp.$1 );

will alert "e"

But also here it's not "magic" but simply part of the properties name

Check if all values in list are greater than a certain number

You could do the following:

def Lists():

    my_list1 = [30,34,56]
    my_list2 = [29,500,43]

    for element in my_list1:
        print(element >= 30)

    for element in my_list2:
        print(element >= 30)

Lists()

This will return the values that are greater than 30 as True, and the values that are smaller as false.

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

Reload the current page:
F5
or
CTRL + R


Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R

Precision String Format Specifier In Swift

extension Double {
  func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
     let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
     return Double(formattedString)!
     }
 }

 1.3333.formatWithDecimalPlaces(2)

How to use if statements in underscore.js templates?

Responding to blackdivine above (about how to stripe one's results), you may have already found your answer (if so, shame on you for not sharing!), but the easiest way of doing so is by using the modulus operator. say, for example, you're working in a for loop:

<% for(i=0, l=myLongArray.length; i<l; ++i) { %>
...
<% } %>

Within that loop, simply check the value of your index (i, in my case):

<% if(i%2) { %>class="odd"<% } else { %>class="even" <% }%>

Doing this will check the remainder of my index divided by two (toggling between 1 and 0 for each index row).

How to set a DateTime variable in SQL Server 2008?

Try using Select instead of Print

DECLARE @Test AS DATETIME 

SET @Test = '2011-02-15'

Select @Test

Authentication plugin 'caching_sha2_password' cannot be loaded

Just downloaded the latest mysqlworkbench which is compatible with the latest encryption:

https://downloads.mysql.com/archives/workbench/

Note: On Mac big Sur, the latest two versions: 8.0.22 and 8.0.23 are buggy and do not work.

Use 8.0.21 until these are fixed

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

How do I uninstall a Windows service if the files do not exist anymore?

We discovered that even if you run sc_delete, there can be an entry remaining in the registry for your service, so that reinstalling the service results in a corrupted set of registry entries (they don't match). What we did was to regedit and remove this leftover entry by hand.

Note: ShipmunkService is still showing up after sc_delete!

Then you can reinstall, and your service will run correctly. Best of luck to you all, and may the force be with you.

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

Using TortoiseSVN via the command line

My fix for getting SVN commands was to copy .exe and .dll files from the TortoiseSVN directory and pasting them into system32 folder.

You could also perform the command from the TortoiseSVN directory and add the path of the working directory to each command. For example:

C:\Program Files\TortoiseSVN\bin> svn st -v C:\checkout

Adding the bin to the path should make it work without duplicating the files, but it didn't work for me.

How to use Select2 with JSON via Ajax request?

for select2 v4.0.0 slightly different

$(".itemSearch").select2({
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    ajax: {
        url: URL,
        dataType: "json",
        type: "GET",
        data: function (params) {

            var queryParameters = {
                term: params.term
            }
            return queryParameters;
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    }
});

find: missing argument to -exec

You need to do some escaping I think.

find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i {} \-sameq {}.mp3 \&\& rm {}\;

Android Studio - Device is connected but 'offline'

Change your USB Preferences to File Transfer if you use your smartphone to debug.

There are several option :

File Transfer /* Choose this one */

USB Tethering

MIDI

PTP

No Data Transfer

Could not install packages due to an EnvironmentError: [Errno 13]

I got the same error when I was trying to install a package (flask-classful).
I made the mistake of installing anaconda as root. I changed the ownership of the installed anaconda folder and I could install the package successfully.

Use the command chown with option -R to recursively change ownership of the installed anaconda folder like so:

chown -R owner:group /path/to/anaconda

Here owner is your username and group is the group name.

phpMyAdmin says no privilege to create database, despite logged in as root user

It appears to be a transient issue and fixed itself afterwards. Thanks for everyone's attention.

How to import an Excel file into SQL Server?

You can also use OPENROWSET to import excel file in sql server.

SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                        'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
                        'SELECT * FROM [Data$]')

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

As additional to @Karthick Kumar answer from bootstrap docs

show is triggered at the start of an event

shown is triggered on the completion of an action

... so it should be:

$('.modal')
    .on('show.bs.modal', function (){
            $('body').css('overflow', 'hidden');
        })
    .on('hide.bs.modal', function (){
            // Also if you are using multiple modals (cascade) - additional check
            if ($('.modal.in').length == 1) {
                $('body').css('overflow', 'auto');
            }
        });

How to get response body using HttpURLConnection, when code other than 2xx is returned?

This is an easy way to get a successful response from the server like PHP echo otherwise an error message.

BufferedReader br = null;
if (conn.getResponseCode() == 200) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
}

Unable to load script from assets index.android.bundle on windows

don't forget turn on internet in emulator device, I resovled this error, it work perfect :V I get this error because i turn off internet to test NetInfo :D

How do I open a new fragment from another fragment?

This is more described code of @Narendra's code,

First you need an instance of the 2nd fragment. Then you should have objects of FragmentManager and FragmentTransaction. The complete code is as below,

Fragment2 fragment2=new Fragment2();
FragmentManager fragmentManager=getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_main,fragment2,"tag");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Hope this will work. In case you use androidx, you need getSupportFragmentManager() instead of getFragmentManager().

Which type of folder structure should be used with Angular 2?

I suggest the following structure, which might violate some existing conventions.

I was striving to reduce name redundancy in the path, and trying to keep naming short in general.

So there is no/app/components/home/home.component.ts|html|css.

Instead it looks like this:

|-- app
    |-- users
        |-- list.ts|html|css
        |-- form.ts|html|css
    |-- cars
        |-- list.ts|html|css
        |-- form.ts|html|css
        |-- configurator.ts|html|css
    |-- app.component.ts|html|css
    |-- app.module.ts
    |-- user.service.ts
    |-- car.service.ts
|-- index.html
|-- main.ts
|-- style.css

Avoid duplicates in INSERT INTO SELECT query in SQL Server

From SQL Server you can set a Unique key index on the table for (Columns that needs to be unique)

From sql server right click on the table design select Indexes/Keys

Select column(s) that will be not duplicate , then type Unique Key

How can I disable ReSharper in Visual Studio and enable it again?

You can add a menu item to toggle ReSharper if you don't want to use the command window or a shortcut key. Sadly the ReSharper_ToggleSuspended command can't be directly added to a menu (there's an open issue on that), but it's easy enough to work around:

Create a macro like this:

Sub ToggleResharper()

    DTE.ExecuteCommand("ReSharper_ToggleSuspended")

End Sub

Then add a menu item to run that macro:

  1. Tools | Customize...
  2. Choose the Commands tab
  3. Choose the menu you want to put the item on
  4. Click Add Command...
  5. In the list on the left, choose "Macros"
  6. In the resulting list on the right, choose the macro
  7. Click OK
  8. Highlight your new command in the list and click Modify Selection... to set the menu item text etc.

How to move an element down a litte bit in html

Try it like this:

.row-2 ul li {
    margin-top: 15px;
}

Batch script loop

The answer really depends on how familiar you are with batch, if you are not so experienced, I would recommend incrementing a loop variable:

@echo off
set /a loop=1
:repeat
echo Hello World!
set /a loop=%loop%+1
if %loop%==<no. of times to repeat> (
goto escapedfromrepeat
)
goto repeat
:escapedfromrepeat
echo You have come out of the loop
pause

But if you are more experienced with batch, I would recommend the more practical for /l %loop in (1, 1, 10) do echo %loop is the better choice.

             (start at 1, go up in 1's, end at 10)
for /l %[your choice] (start, step, end) do [command of your choice]

How can I check for an empty/undefined/null string in JavaScript?

Starting with:

return (!value || value == undefined || value == "" || value.length == 0);

Looking at the last condition, if value == "", its length must be 0. Therefore drop it:

return (!value || value == undefined || value == "");

But wait! In JavaScript, an empty string is false. Therefore, drop value == "":

return (!value || value == undefined);

And !undefined is true, so that check isn't needed. So we have:

return (!value);

And we don't need parentheses:

return !value

Error in installation a R package

In my case, the installation of nlme package is in trouble:

mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme' 
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme': 
Permission denied

Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:

sudo R
install.packages('nlme')
q()

Get bytes from std::string in C++

If you just need read-only access, then c_str() will do it:

char const *c = myString.c_str();

If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:

std::vector<char> bytes(myString.begin(), myString.end());
bytes.push_back('\0');
char *c = &bytes[0];

MySQL: Curdate() vs Now()

Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-

NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.

NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;

Programmatically scroll to a specific position in an Android ListView

-If you just want the list to scroll up\dawn to a specific position:

myListView.smoothScrollToPosition(i);

-if you want to get the position of a specific item in myListView:

myListView.getItemAtPosition(i);

-also this myListView.getVerticalScrollbarPosition(i);can helps you.

Good Luck :)

What's the difference between struct and class in .NET?

From Microsoft's Choosing Between Class and Struct ...

As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.

? CONSIDER a struct instead of a class:

  • If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

X AVOID a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable. (cannot be changed)
  • It will not have to be boxed frequently.

How to prevent page scrolling when scrolling a DIV element?

You can do this without JavaScript. You can set the style on both divs to position: fixed and overflow-y: auto. You may need to make one of them higher than the other by setting its z-index (if they overlap).

Here's a basic example on CodePen.

Efficient way to rotate a list in python

I'm "old school" I define efficiency in lowest latency, processor time and memory usage, our nemesis are the bloated libraries. So there is exactly one right way:

    def rotatel(nums):
        back = nums.pop(0)
        nums.append(back)
        return nums

What is HTML5 ARIA?

WAI-ARIA is a spec defining support for accessible web apps. It defines bunch of markup extensions (mostly as attributes on HTML5 elements), which can be used by the web app developer to provide additional information about the semantics of the various elements to assistive technologies like screen readers. Of course, for ARIA to work, the HTTP user agent that interprets the markup needs to support ARIA, but the spec is created in such a way, as to allow down-level user agents to ignore the ARIA-specific markup safely without affecting the web app's functionality.

Here's an example from the ARIA spec:

<ul role="menubar">

  <!-- Rule 2A: "File" label via aria-labelledby -->
  <li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel"><span id="fileLabel">File</span>
    <ul role="menu">

      <!-- Rule 2C: "New" label via Namefrom:contents -->
      <li role="menuitem" aria-haspopup="false">New</li>
      <li role="menuitem" aria-haspopup="false">Open…</li>
      ...
    </ul>
  </li>
  ...
</ul>

Note the role attribute on the outer <ul> element. This attribute does not affect in any way how the markup is rendered on the screen by the browser; however, browsers that support ARIA will add OS-specific accessibility information to the rendered UI element, so that the screen reader can interpret it as a menu and read it aloud with enough context for the end-user to understand (for example, an explicit "menu" audio hint) and is able to interact with it (for example, voice navigation).

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I got this error when I tried to access a bucket that didn't exist.

I mistakenly switched a path variable with the bucket name variable and so the bucket name had the file path value. So maybe double-check, if the bucket name that you set on your request is correct.

Can a CSS class inherit one or more other classes?

You can achieve what you want if you preprocess your .css files through php. ...

$something='color:red;'
$else='display:inline;';
echo '.something {'. $something .'}';
echo '.else {'. $something .'}';
echo '.somethingelse {'. $something  .$else '}';

...

How to create dispatch queue in Swift 3

I did this and this is especially important if you want to refresh your UI to show new data without user noticing like in UITableView or UIPickerView.

    DispatchQueue.main.async
 {
   /*Write your thread code here*/
 }

Why is semicolon allowed in this python snippet?

Python uses the ; as a separator, not a terminator. You can also use them at the end of a line, which makes them look like a statement terminator, but this is legal only because blank statements are legal in Python -- a line that contains a semicolon at the end is two statements, the second one blank.

Changing password with Oracle SQL Developer

One note for people who might not have the set password for sysdba or sys and regularly use a third party client. Here's some info about logging into command line sqlplus without a password that helped me. I am using fedora 21 by the way.

locate sqlplus

In my case, sqlplus is located here:

/u01/app/oracle/product/11.2.0/xe/config/scripts/sqlplus.sh

Now run

cd /u01/app/oracle/product/11.2.0/xe/config/scripts
./sqlplus.sh / as sysdba

Now you need to connect to database with your old credentials. You can find Oracle provided template in your output:

Use "connect username/password@XE" to connect to the database.

In my case I have user "oracle" with password "oracle" so my input looks like

connect oracle/oracle@XE

Done. Now type your new password twice. Then if you don't want your password to expire anymore you could run

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

TypeError: 'bool' object is not callable

You do cls.isFilled = True. That overwrites the method called isFilled and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.

The solution is use a different name for the variable than you do for the method.

How to change an image on click using CSS alone?

Try this (but once clicked, it is not reversible):

HTML:

<a id="test"><img src="normal-image.png"/></a>

CSS:

a#test {
    border: 0;
}
a#test:visited img, a#test:active img {
    background-image: url(clicked-image.png);
}

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

How to force file download with PHP

Display your file first and set its value into url.

index.php

<a href="download.php?download='.$row['file'].'" title="Download File">

download.php

<?php
/*db connectors*/
include('dbconfig.php');

/*function to set your files*/
function output_file($file, $name, $mime_type='')
{
    if(!is_readable($file)) die('File not found or inaccessible!');
    $size = filesize($file);
    $name = rawurldecode($name);
    $known_mime_types=array(
        "htm" => "text/html",
        "exe" => "application/octet-stream",
        "zip" => "application/zip",
        "doc" => "application/msword",
        "jpg" => "image/jpg",
        "php" => "text/plain",
        "xls" => "application/vnd.ms-excel",
        "ppt" => "application/vnd.ms-powerpoint",
        "gif" => "image/gif",
        "pdf" => "application/pdf",
        "txt" => "text/plain",
        "html"=> "text/html",
        "png" => "image/png",
        "jpeg"=> "image/jpg"
    );

    if($mime_type==''){
        $file_extension = strtolower(substr(strrchr($file,"."),1));
        if(array_key_exists($file_extension, $known_mime_types)){
            $mime_type=$known_mime_types[$file_extension];
        } else {
            $mime_type="application/force-download";
        };
    };
    @ob_end_clean();
    if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
    header('Content-Type: ' . $mime_type);
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary");
    header('Accept-Ranges: bytes');

    if(isset($_SERVER['HTTP_RANGE']))
    {
        list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
        list($range) = explode(",",$range,2);
        list($range, $range_end) = explode("-", $range);
        $range=intval($range);
        if(!$range_end) {
            $range_end=$size-1;
        } else {
            $range_end=intval($range_end);
        }

        $new_length = $range_end-$range+1;
        header("HTTP/1.1 206 Partial Content");
        header("Content-Length: $new_length");
        header("Content-Range: bytes $range-$range_end/$size");
    } else {
        $new_length=$size;
        header("Content-Length: ".$size);
    }

    $chunksize = 1*(1024*1024);
    $bytes_send = 0;
    if ($file = fopen($file, 'r'))
    {
        if(isset($_SERVER['HTTP_RANGE']))
        fseek($file, $range);

        while(!feof($file) &&
            (!connection_aborted()) &&
            ($bytes_send<$new_length)
        )
        {
            $buffer = fread($file, $chunksize);
            echo($buffer);
            flush();
            $bytes_send += strlen($buffer);
        }
        fclose($file);
    } else
        die('Error - can not open file.');
    die();
}
set_time_limit(0);

/*set your folder*/
$file_path='uploads/'."your file";

/*output must be folder/yourfile*/

output_file($file_path, ''."your file".'', $row['type']);

/*back to index.php while downloading*/
header('Location:index.php');
?>

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

1· Do I need these DLL's?

It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.

  1. Where can I get them?

most dlls can be found at https://www.dll-files.com

I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll

For me leshims.dll can be placed at C:\Windows\System32\. Context: windows 7 64bit.

ASP.NET MVC Global Variables

Technically any static variable or Property on a class, anywhere in your project, will be a Global variable e.g.

public static class MyGlobalVariables
{
    public static string MyGlobalString { get; set; }
}

But as @SLaks says, they can 'potentially' be bad practice and dangerous, if not handled correctly. For instance, in that above example, you would have multiple requests (threads) trying to access the same Property, which could be an issue if it was a complex type or a collection, you would have to implement some form of locking.

Installing Java on OS X 10.9 (Mavericks)

From the OP:

I finally reinstalled it from Java for OS X 2013-005. It solved this issue.

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

If you use MAMP, make sure it's started. :)

I just ran into this problem, and after starting MAMP the error went away. Not my finest moment.

Why does the C preprocessor interpret the word "linux" as the constant "1"?

This appears to be an (undocumented) "GNU extension": [correction: I finally found a mention in the docs. See below.]

The following command uses the -dM option to print all preprocessor defines; since the input "file" is empty, it shows exactly the predefined macros. It was run with gcc-4.7.3 on a standard ubuntu install. You can see that the preprocessor is standard-aware. In total, there 243 macros with -std=gnu99 and 240 with -std=c99; I filtered the output for relevance.

$ cpp --std=c89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1

$ cpp --std=gnu89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

$ cpp --std=c99 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1

$ cpp --std=gnu99 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

The "gnu standard" versions also #define unix. (Using c11 and gnu11 produces the same results.)

I suppose they had their reasons, but it seems to me to make the default installation of gcc (which compiles C code with -std=gnu89 unless otherwise specified) non-conformant, and -- as in this question -- surprising. Polluting the global namespace with macros whose names don't begin with an underscore is not permitted in a conformant implementation. (6.8.10p2: "Any other predefined macro names shall begin with a leading underscore followed by an uppercase letter or a second underscore," but, as mentioned in Appendix J.5 (portability issues), such names are often predefined.)

When I originally wrote this answer, I wasn't able to find any documentation in gcc about this issue, but I did finally discover it, not in C implementation-defined behaviour nor in C extensions but in the cpp manual section 3.7.3, where it notes that:

We are slowly phasing out all predefined macros which are outside the reserved namespace. You should never use them in new programs…

Generate unique random numbers between 1 and 100

if you need more unique you must generate a array(1..100).

var arr=[];
function generateRandoms(){
for(var i=1;i<=100;i++) arr.push(i);
}
function extractUniqueRandom()
{
   if (arr.length==0) generateRandoms();
   var randIndex=Math.floor(arr.length*Math.random());
   var result=arr[randIndex];
   arr.splice(randIndex,1);
   return result;

}
function extractUniqueRandomArray(n)
{
   var resultArr=[];
   for(var i=0;i<n;i++) resultArr.push(extractUniqueRandom());
   return resultArr;
}

above code is faster:
extractUniqueRandomArray(50)=> [2, 79, 38, 59, 63, 42, 52, 22, 78, 50, 39, 77, 1, 88, 40, 23, 48, 84, 91, 49, 4, 54, 93, 36, 100, 82, 62, 41, 89, 12, 24, 31, 86, 92, 64, 75, 70, 61, 67, 98, 76, 80, 56, 90, 83, 44, 43, 47, 7, 53]

How to fix a locale setting warning from Perl

ssh overwrites LC locale variables by default. See /etc/ssh/sshd_config:

AcceptEnv LANG LC_*

So maybe you need to set these variables in your local shell.

Set a button group's width to 100% and make buttons equal width?

There's no need for extra css the .btn-group-justified class does this.

You have to add this to the parent element and then wrap each btn element in a div with .btn-group like this

    <div class="form-group">

            <div class="btn-group btn-group-justified">
                <div class="btn-group">
                    <button type="submit" id="like" class="btn btn-lg btn-success ">Like</button>
                </div>
                <div class="btn-group">
                    <button type="submit" id="nope" class="btn btn-lg btn-danger ">Nope</button>
                </div>
            </div>

        </div>

Error "initializer element is not constant" when trying to initialize variable with const

Just for illustration by compare and contrast The code is from http://www.geeksforgeeks.org/g-fact-80/ /The code fails in gcc and passes in g++/

#include<stdio.h>
int initializer(void)
{
    return 50;
}

int main()
{
    int j;
    for (j=0;j<10;j++)
    {
        static int i = initializer();
        /*The variable i is only initialized to one*/
        printf(" value of i = %d ", i);
        i++;
    }
    return 0;
}

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

About the removal of componentWillReceiveProps: you should be able to handle its uses with a combination of getDerivedStateFromProps and componentDidUpdate, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps updates the state similarly to an object passed to setState.

In case you really need the old value of a prop, you can always cache it in your state with something like this:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

Anything that doesn't affect the state can be put in componentDidUpdate, and there's even a getSnapshotBeforeUpdate for very low-level stuff.

UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



How to zoom in/out an UIImage object when user pinches screen?

As others described, the easiest solution is to put your UIImageView into a UIScrollView. I did this in the Interface Builder .xib file.

In viewDidLoad, set the following variables. Set your controller to be a UIScrollViewDelegate.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView.minimumZoomScale = 0.5;
    self.scrollView.maximumZoomScale = 6.0;
    self.scrollView.contentSize = self.imageView.frame.size;
    self.scrollView.delegate = self;
}

You are required to implement the following method to return the imageView you want to zoom.

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

In versions prior to iOS9, you may also need to add this empty delegate method:

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
}

The Apple Documentation does a good job of describing how to do this:

How can I check if a directory exists?

You may also use access in combination with opendir to determine if the directory exists, and, if the name exists, but is not a directory. For example:

/* test that dir exists (1 success, -1 does not exist, -2 not dir) */
int
xis_dir (const char *d)
{
    DIR *dirptr;

    if (access ( d, F_OK ) != -1 ) {
        // file exists
        if ((dirptr = opendir (d)) != NULL) {
            closedir (dirptr); /* d exists and is a directory */
        } else {
            return -2; /* d exists but is not a directory */
        }
    } else {
        return -1;     /* d does not exist */
    }

    return 1;
}

Fatal error: Class 'SoapClient' not found

I solved this issue on PHP 7.0.22-0ubuntu0.16.04.1 nginx

sudo apt-get install php7.0-soap

sudo systemctl restart php7.0-fpm
sudo systemctl restart nginx

SQL Server : export query as a .txt file

You can use bcp utility.

To copy the result set from a Transact-SQL statement to a data file, use the queryout option. The following example copies the result of a query into the Contacts.txt data file. The example assumes that you are using Windows Authentication and have a trusted connection to the server instance on which you are running the bcp command. At the Windows command prompt, enter:

bcp "<your query here>" queryout Contacts.txt -c -T

You can use BCP by directly calling as operating sytstem command in SQL Agent job.

How do I test a website using XAMPP?

Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/www"
    ServerName example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs"
    ServerName htdocs.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

delete image from folder PHP

First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.

              if (file_exists($filePath)) 
               {
                 unlink($filePath);
                  echo "File Successfully Delete."; 
              }
              else
              {
               echo "File does not exists"; 
              }

Rails server says port already used, how to kill that process?

Using this command you can kill the server:

ps aux|grep rails 

JQuery Ajax - How to Detect Network Connection error when making Ajax call

Have you tried this?

$(document).ajaxError(function(){ alert('error'); }

That should handle all AjaxErrors. I´ve found it here. There you find also a possibility to write these errors to your firebug console.

How to use the onClick event for Hyperlink using C# code?

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

How to get datetime in JavaScript?

Date().toLocaleString() returns this: 7/31/2018, 12:58:03 PM

Pretty close - just drop the comma and the seconds:

new Date().toLocaleString().replace(",","").replace(/:.. /," ");

Results: 7/31/2018 12:58 PM

Cell spacing in UICollectionView

I stumbled upon a similar problem as OP. Unfortunately the accepted answer did not work for me since the content of the collectionView would not be centered properly. Therefore I came up with a different solution which only requires that all items in the collectionView are of the same width, which seems to be the case in the question:

#define cellSize 90

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    float width = collectionView.frame.size.width;
    float spacing = [self collectionView:collectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
    int numberOfCells = (width + spacing) / (cellSize + spacing);
    int inset = (width + spacing - numberOfCells * (cellSize + spacing) ) / 2;

    return UIEdgeInsetsMake(0, inset, 0, inset);
}

That code will ensure that the value returned by ...minimumInteritemSpacing... will be the exact spacing between every collectionViewCell and furthermore guarantee that the cells all together will be centered in the collectionView

Associating enums with strings in C#

I would make it into a class an avoid an enum altogether. And then with the usage of a typehandler you could create the object when you grab it from the db.

IE:

public class Group
{
    public string Value{ get; set; }
    public Group( string value ){ Value = value; } 
    public static Group TheGroup() { return new Group("OEM"); }
    public static Group OtherGroup() { return new Group("CMB"); }

}

UIScrollView Scrollable Content Size Ambiguity

Swift 4+ approach:

1) Set UIScrollView top, bottom, left and right margins to 0

2) Inside the UIScrollView add a UIView and set top, bottom, leading, trailing margins to 0 ( equal to UIScrollView margins ).

3) The most important part is to set width and height, where height constraint should have a low priority.

private func setupConstraints() {

    // Constraints for scrollView
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    // Constraints for containerView
    containerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
    containerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
    containerView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
    containerView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
    containerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true

    let heightConstraint = containerView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
    heightConstraint.priority = UILayoutPriority(rawValue: 250)
    heightConstraint.isActive = true
}

How to change button color with tkinter

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

You can also revert to the original color.

Customizing Bootstrap CSS template

The best thing to do is.

1. fork twitter-bootstrap from github and clone locally.

they are changing really quickly the library/framework (they diverge internally. Some prefer library, i'd say that it's a framework, because change your layout from the time you load it on your page). Well... forking/cloning will let you fetch the new upcoming versions easily.

2. Do not modify the bootstrap.css file

It's gonna complicate your life when you need to upgrade bootstrap (and you will need to do it).

3. Create your own css file and overwrite whenever you want original bootstrap stuff

if they set a topbar with, let's say, color: black; but you wan it white, create a new very specific selector for this topbar and use this rule on the specific topbar. For a table for example, it would be <table class="zebra-striped mycustomclass">. If you declare your css file after bootstrap.css, this will overwrite whatever you want to.

Convert string to a variable name

There is another simple solution found there: http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/

To convert a string to a variable:

x <- 42
eval(parse(text = "x"))
[1] 42

And the opposite:

x <- 42
deparse(substitute(x))
[1] "x"

Does JSON syntax allow duplicate keys in an object?

Posting and answer because there is a lot of outdated ideas and confusion about the standards. As of December 2017, there are two competing standards:

RFC 8259 - https://tools.ietf.org/html/rfc8259

ECMA-404 - http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf

json.org suggests ECMA-404 is the standard, but this site does not appear to be an authority. While I think it's fair to consider ECMA the authority, what's important here is, the only difference between the standards (regarding unique keys) is that RFC 8259 says the keys should be unique, and the ECMA-404 says they are not required to be unique.

RFC-8259:

"The names within an object SHOULD be unique."

The word "should" in all caps like that, has a meaning within the RFC world, that is specifically defined in another standard (BCP 14, RFC 2119 - https://tools.ietf.org/html/rfc2119) as,

  1. SHOULD This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

ECMA-404:

"The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs."

So, no matter how you slice it, it's syntactically valid JSON.

The reason given for the unique key recommendation in RFC 8259 is,

An object whose names are all unique is interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.

In other words, from the RFC 8259 viewpoint, it's valid but your parser may barf and there's no promise as to which, if any, value will be paired with that key. From the ECMA-404 viewpoint (which I'd personally take as the authority), it's valid, period. To me this means that any parser that refuses to parse it is broken. It should at least parse according to both of these standards. But how it gets turned into your native object of choice is, in any case, unique keys or not, completely dependent on the environment and the situation, and none of that is in the standard to begin with.

How to add to an existing hash in Ruby

hash = { a: 'a', b: 'b' }
 => {:a=>"a", :b=>"b"}
hash.merge({ c: 'c', d: 'd' })
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 

Returns the merged value.

hash
 => {:a=>"a", :b=>"b"} 

But doesn't modify the caller object

hash = hash.merge({ c: 'c', d: 'd' })
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 
hash
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 

Reassignment does the trick.

how to add a day to a date using jquery datepicker

The datepicker('setDate') sets the date in the datepicket not in the input.

You should add the date and set it in the input.

var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);

Determine file creation date in Java

As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.

On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;

public class TestFA {
  static void getAttributes(String pathStr) throws IOException {
    Path p = Paths.get(pathStr);
    BasicFileAttributes view
       = Files.getFileAttributeView(p, BasicFileAttributeView.class)
              .readAttributes();
    System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
  }
  public static void main(String[] args) throws IOException {
    for (String s : args) {
        getAttributes(s);
    }
  }
}

How to display a list of images in a ListView in Android?

File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >  

<ImageView android:id="@+id/R.id.list_item_image"
  android:layout_width="100dip"
  android:layout_height="wrap_content" />  
</LinearLayout>

Assign an initial value to radio button as checked

You can just use:

<input type="radio" checked />

Using just the attribute checked without stating a value is the same as checked="checked".

Create Directory When Writing To File In Node.js

first taking the full path including directory and extracting the directory

//Just for the sake of example
cwd=process.cwd()
filendir=path.resolve(cwd,'_site/assets/text','node.txt')

// Extracting directory name
mkdir=path.dirname(filendir)

Now make the directory, add option recursive:true as stated by @David Weldon

fs.mkdirSync(mkdir,{recursive:true})

Then make the file

data='Some random text'
fs.writeFileSync(filendir,data)

"Android library projects cannot be launched"?

With Me I had the library ticked under Eclipse>Project Properties>Android what I just did was uncheck the ticked library.

how to get the cookies from a php curl into a variable

someone here may find it useful. hhb_curl_exec2 works pretty much like curl_exec, but arg3 is an array which will be populated with the returned http headers (numeric index), and arg4 is an array which will be populated with the returned cookies ($cookies["expires"]=>"Fri, 06-May-2016 05:58:51 GMT"), and arg5 will be populated with... info about the raw request made by curl.

the downside is that it requires CURLOPT_RETURNTRANSFER to be on, else it error out, and that it will overwrite CURLOPT_STDERR and CURLOPT_VERBOSE, if you were already using them for something else.. (i might fix this later)

example of how to use it:

<?php
header("content-type: text/plain;charset=utf8");
$ch=curl_init();
$headers=array();
$cookies=array();
$debuginfo="";
$body="";
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$body=hhb_curl_exec2($ch,'https://www.youtube.com/',$headers,$cookies,$debuginfo);
var_dump('$cookies:',$cookies,'$headers:',$headers,'$debuginfo:',$debuginfo,'$body:',$body);

and the function itself..

function hhb_curl_exec2($ch, $url, &$returnHeaders = array(), &$returnCookies = array(), &$verboseDebugInfo = "")
{
    $returnHeaders    = array();
    $returnCookies    = array();
    $verboseDebugInfo = "";
    if (!is_resource($ch) || get_resource_type($ch) !== 'curl') {
        throw new InvalidArgumentException('$ch must be a curl handle!');
    }
    if (!is_string($url)) {
        throw new InvalidArgumentException('$url must be a string!');
    }
    $verbosefileh = tmpfile();
    $verbosefile  = stream_get_meta_data($verbosefileh);
    $verbosefile  = $verbosefile['uri'];
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_STDERR, $verbosefileh);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $html             = hhb_curl_exec($ch, $url);
    $verboseDebugInfo = file_get_contents($verbosefile);
    curl_setopt($ch, CURLOPT_STDERR, NULL);
    fclose($verbosefileh);
    unset($verbosefile, $verbosefileh);
    $headers       = array();
    $crlf          = "\x0d\x0a";
    $thepos        = strpos($html, $crlf . $crlf, 0);
    $headersString = substr($html, 0, $thepos);
    $headerArr     = explode($crlf, $headersString);
    $returnHeaders = $headerArr;
    unset($headersString, $headerArr);
    $htmlBody = substr($html, $thepos + 4); //should work on utf8/ascii headers... utf32? not so sure..
    unset($html);
    //I REALLY HOPE THERE EXIST A BETTER WAY TO GET COOKIES.. good grief this looks ugly..
    //at least it's tested and seems to work perfectly...
    $grabCookieName = function($str)
    {
        $ret = "";
        $i   = 0;
        for ($i = 0; $i < strlen($str); ++$i) {
            if ($str[$i] === ' ') {
                continue;
            }
            if ($str[$i] === '=') {
                break;
            }
            $ret .= $str[$i];
        }
        return urldecode($ret);
    };
    foreach ($returnHeaders as $header) {
        //Set-Cookie: crlfcoookielol=crlf+is%0D%0A+and+newline+is+%0D%0A+and+semicolon+is%3B+and+not+sure+what+else
        /*Set-Cookie:ci_spill=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22305d3d67b8016ca9661c3b032d4319df%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%2285.164.158.128%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A109%3A%22Mozilla%2F5.0+%28Windows+NT+6.1%3B+WOW64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F43.0.2357.132+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1436874639%3B%7Dcab1dd09f4eca466660e8a767856d013; expires=Tue, 14-Jul-2015 13:50:39 GMT; path=/
        Set-Cookie: sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT;
        //Cookie names cannot contain any of the following '=,; \t\r\n\013\014'
        //
        */
        if (stripos($header, "Set-Cookie:") !== 0) {
            continue;
            /**/
        }
        $header = trim(substr($header, strlen("Set-Cookie:")));
        while (strlen($header) > 0) {
            $cookiename                 = $grabCookieName($header);
            $returnCookies[$cookiename] = '';
            $header                     = substr($header, strlen($cookiename) + 1); //also remove the = 
            if (strlen($header) < 1) {
                break;
            }
            ;
            $thepos = strpos($header, ';');
            if ($thepos === false) { //last cookie in this Set-Cookie.
                $returnCookies[$cookiename] = urldecode($header);
                break;
            }
            $returnCookies[$cookiename] = urldecode(substr($header, 0, $thepos));
            $header                     = trim(substr($header, $thepos + 1)); //also remove the ;
        }
    }
    unset($header, $cookiename, $thepos);
    return $htmlBody;
}

function hhb_curl_exec($ch, $url)
{
    static $hhb_curl_domainCache = "";
    //$hhb_curl_domainCache=&$this->hhb_curl_domainCache;
    //$ch=&$this->curlh;
    if (!is_resource($ch) || get_resource_type($ch) !== 'curl') {
        throw new InvalidArgumentException('$ch must be a curl handle!');
    }
    if (!is_string($url)) {
        throw new InvalidArgumentException('$url must be a string!');
    }

    $tmpvar = "";
    if (parse_url($url, PHP_URL_HOST) === null) {
        if (substr($url, 0, 1) !== '/') {
            $url = $hhb_curl_domainCache . '/' . $url;
        } else {
            $url = $hhb_curl_domainCache . $url;
        }
    }
    ;

    curl_setopt($ch, CURLOPT_URL, $url);
    $html = curl_exec($ch);
    if (curl_errno($ch)) {
        throw new Exception('Curl error (curl_errno=' . curl_errno($ch) . ') on url ' . var_export($url, true) . ': ' . curl_error($ch));
        // echo 'Curl error: ' . curl_error($ch);
    }
    if ($html === '' && 203 != ($tmpvar = curl_getinfo($ch, CURLINFO_HTTP_CODE)) /*203 is "success, but no output"..*/ ) {
        throw new Exception('Curl returned nothing for ' . var_export($url, true) . ' but HTTP_RESPONSE_CODE was ' . var_export($tmpvar, true));
    }
    ;
    //remember that curl (usually) auto-follows the "Location: " http redirects..
    $hhb_curl_domainCache = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL), PHP_URL_HOST);
    return $html;
}

Convert date to another timezone in JavaScript

You can try this also for convert date timezone to India:

var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);

Notepad++ change text color?

You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.

Sample for your reference here.

Multi-line bash commands in makefile

Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo depend on itself, but of course, make is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.

GNU make knows how to run gcc to produce an executable out of a set of .c and .h files, so maybe all you really need amounts to

foo: $(wildcard *.h) $(wildcard *.c)

Stack smashing detected

Minimal reproduction example with disassembly analysis

main.c

void myfunc(char *const src, int len) {
    int i;
    for (i = 0; i < len; ++i) {
        src[i] = 42;
    }
}

int main(void) {
    char arr[] = {'a', 'b', 'c', 'd'};
    int len = sizeof(arr);
    myfunc(arr, len + 1);
    return 0;
}

GitHub upstream.

Compile and run:

gcc -fstack-protector-all -g -O0 -std=c99 main.c
ulimit -c unlimited && rm -f core
./a.out

fails as desired:

*** stack smashing detected ***: terminated
Aborted (core dumped)

Tested on Ubuntu 20.04, GCC 10.2.0.

On Ubuntu 16.04, GCC 6.4.0, I could reproduce with -fstack-protector instead of -fstack-protector-all, but it stopped blowing up when I tested on GCC 10.2.0 as per Geng Jiawen's comment. man gcc clarifies that as suggested by the option name, the -all version adds checks more aggressively, and therefore presumably incurs a larger performance loss:

-fstack-protector

Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call "alloca", and functions with buffers larger than or equal to 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits. Only variables that are actually allocated on the stack are considered, optimized away variables or variables allocated in registers don't count.

-fstack-protector-all

Like -fstack-protector except that all functions are protected.

Disassembly

Now we look at the disassembly:

objdump -D a.out

which contains:

int main (void){
  400579:       55                      push   %rbp
  40057a:       48 89 e5                mov    %rsp,%rbp

  # Allocate 0x10 of stack space.
  40057d:       48 83 ec 10             sub    $0x10,%rsp

  # Put the 8 byte canary from %fs:0x28 to -0x8(%rbp),
  # which is right at the bottom of the stack.
  400581:       64 48 8b 04 25 28 00    mov    %fs:0x28,%rax
  400588:       00 00 
  40058a:       48 89 45 f8             mov    %rax,-0x8(%rbp)

  40058e:       31 c0                   xor    %eax,%eax
    char arr[] = {'a', 'b', 'c', 'd'};
  400590:       c6 45 f4 61             movb   $0x61,-0xc(%rbp)
  400594:       c6 45 f5 62             movb   $0x62,-0xb(%rbp)
  400598:       c6 45 f6 63             movb   $0x63,-0xa(%rbp)
  40059c:       c6 45 f7 64             movb   $0x64,-0x9(%rbp)
    int len = sizeof(arr);
  4005a0:       c7 45 f0 04 00 00 00    movl   $0x4,-0x10(%rbp)
    myfunc(arr, len + 1);
  4005a7:       8b 45 f0                mov    -0x10(%rbp),%eax
  4005aa:       8d 50 01                lea    0x1(%rax),%edx
  4005ad:       48 8d 45 f4             lea    -0xc(%rbp),%rax
  4005b1:       89 d6                   mov    %edx,%esi
  4005b3:       48 89 c7                mov    %rax,%rdi
  4005b6:       e8 8b ff ff ff          callq  400546 <myfunc>
    return 0;
  4005bb:       b8 00 00 00 00          mov    $0x0,%eax
}
  # Check that the canary at -0x8(%rbp) hasn't changed after calling myfunc.
  # If it has, jump to the failure point __stack_chk_fail.
  4005c0:       48 8b 4d f8             mov    -0x8(%rbp),%rcx
  4005c4:       64 48 33 0c 25 28 00    xor    %fs:0x28,%rcx
  4005cb:       00 00 
  4005cd:       74 05                   je     4005d4 <main+0x5b>
  4005cf:       e8 4c fe ff ff          callq  400420 <__stack_chk_fail@plt>

  # Otherwise, exit normally.
  4005d4:       c9                      leaveq 
  4005d5:       c3                      retq   
  4005d6:       66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
  4005dd:       00 00 00 

Notice the handy comments automatically added by objdump's artificial intelligence module.

If you run this program multiple times through GDB, you will see that:

  • the canary gets a different random value every time
  • the last loop of myfunc is exactly what modifies the address of the canary

The canary randomized by setting it with %fs:0x28, which contains a random value as explained at:

Debug attempts

From now on, we modify the code:

    myfunc(arr, len + 1);

to be instead:

    myfunc(arr, len);
    myfunc(arr, len + 1); /* line 12 */
    myfunc(arr, len);

to be more interesting.

We will then try to see if we can pinpoint the culprit + 1 call with a method more automated than just reading and understanding the entire source code.

gcc -fsanitize=address to enable Google's Address Sanitizer (ASan)

If you recompile with this flag and run the program, it outputs:

#0 0x4008bf in myfunc /home/ciro/test/main.c:4
#1 0x40099b in main /home/ciro/test/main.c:12
#2 0x7fcd2e13d82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
#3 0x400798 in _start (/home/ciro/test/a.out+0x40079

followed by some more colored output.

This clearly pinpoints the problematic line 12.

The source code for this is at: https://github.com/google/sanitizers but as we saw from the example it is already upstreamed into GCC.

ASan can also detect other memory problems such as memory leaks: How to find memory leak in a C++ code/project?

Valgrind SGCheck

As mentioned by others, Valgrind is not good at solving this kind of problem.

It does have an experimental tool called SGCheck:

SGCheck is a tool for finding overruns of stack and global arrays. It works by using a heuristic approach derived from an observation about the likely forms of stack and global array accesses.

So I was not very surprised when it did not find the error:

valgrind --tool=exp-sgcheck ./a.out

The error message should look like this apparently: Valgrind missing error

GDB

An important observation is that if you run the program through GDB, or examine the core file after the fact:

gdb -nh -q a.out core

then, as we saw on the assembly, GDB should point you to the end of the function that did the canary check:

(gdb) bt
#0  0x00007f0f66e20428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1  0x00007f0f66e2202a in __GI_abort () at abort.c:89
#2  0x00007f0f66e627ea in __libc_message (do_abort=do_abort@entry=1, fmt=fmt@entry=0x7f0f66f7a49f "*** %s ***: %s terminated\n") at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007f0f66f0415c in __GI___fortify_fail (msg=<optimized out>, msg@entry=0x7f0f66f7a481 "stack smashing detected") at fortify_fail.c:37
#4  0x00007f0f66f04100 in __stack_chk_fail () at stack_chk_fail.c:28
#5  0x00000000004005f6 in main () at main.c:15
(gdb) f 5
#5  0x00000000004005f6 in main () at main.c:15
15      }
(gdb)

And therefore the problem is likely in one of the calls that this function made.

Next we try to pinpoint the exact failing call by first single stepping up just after the canary is set:

  400581:       64 48 8b 04 25 28 00    mov    %fs:0x28,%rax
  400588:       00 00 
  40058a:       48 89 45 f8             mov    %rax,-0x8(%rbp)

and watching the address:

(gdb) p $rbp - 0x8
$1 = (void *) 0x7fffffffcf18
(gdb) watch 0x7fffffffcf18
Hardware watchpoint 2: *0x7fffffffcf18
(gdb) c
Continuing.

Hardware watchpoint 2: *0x7fffffffcf18

Old value = 1800814336
New value = 1800814378
myfunc (src=0x7fffffffcf14 "*****?Vk\266", <incomplete sequence \355\216>, len=5) at main.c:3
3           for (i = 0; i < len; ++i) {
(gdb) p len
$2 = 5
(gdb) p i
$3 = 4
(gdb) bt
#0  myfunc (src=0x7fffffffcf14 "*****?Vk\266", <incomplete sequence \355\216>, len=5) at main.c:3
#1  0x00000000004005cc in main () at main.c:12

Now, this does leaves us at the right offending instruction: len = 5 and i = 4, and in this particular case, did point us to the culprit line 12.

However, the backtrace is corrupted, and contains some trash. A correct backtrace would look like:

#0  myfunc (src=0x7fffffffcf14 "abcd", len=4) at main.c:3
#1  0x00000000004005b8 in main () at main.c:11

so maybe this could corrupt the stack and prevent you from seeing the trace.

Also, this method requires knowing what is the last call of the canary checking function otherwise you will have false positives, which will not always be feasible, unless you use reverse debugging.

Json.net serialize/deserialize derived types?

Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.

The long way is to write custom JsonConverters to handle (de)serialization by manually checking and setting the type property.

A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:

[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
    public virtual string Sound { get; }
    public string Color { get; set; }
}

public class Dog : Animal
{
    public override string Sound { get; } = "Bark";
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public override string Sound { get; } = "Meow";
    public bool Declawed { get; set; }
}

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

Difference between @click and v-on:click Vuejs

There is no difference between the two, one is just a shorthand for the second.

The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.

<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>

Source: official documentation.

Javascript Drag and drop for touch devices

I had the same solution as gregpress answer, but my draggable items used a class instead of an id. It seems to work.

var $target = $(event.target);  
if( $target.hasClass('draggable') ) {  
    event.preventDefault();  
}

Convert date to day name e.g. Mon, Tue, Wed

You can not use strtotime as your time format is not within the supported date and time formats of PHP.

Therefor, you have to create a valid date format first making use of createFromFormat function.

//creating a valid date format
$newDate = DateTime::createFromFormat('YmdHi', $longdate);

//formating the date as we want
$finalDate = $newDate->format('D');