Programs & Examples On #Countdownevent

In the .Net framework a CountdownEvent is an object that represents a thread synchronization primitive that is signaled when its count reaches zero. It can be used to synchronize returning threads.

How can I post an array of string to ASP.NET MVC Controller without a form?

As I discussed here ,

if you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.

public string GetData() {
  // InputStream contains the JSON object you've sent
  String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();

  // Deserialize it to a dictionary
  var dic =
    Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < String,
    dynamic >> (jsonString);

  string result = "";

  result += dic["firstname"] + dic["lastname"];

  // You can even cast your object to their original type because of 'dynamic' keyword
  result += ", Age: " + (int) dic["age"];

  if ((bool) dic["married"])
    result += ", Married";

  return result;
}

The real benefit of this solution is that you don't require to define a new class for each combination of arguments and beside that, you can cast your objects to their original types easily.

You can use a helper method like this to facilitate your job:

public static Dictionary < string, dynamic > GetDic(HttpRequestBase request) {
  String jsonString = new StreamReader(request.InputStream).ReadToEnd();
  return Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, dynamic >> (jsonString);
}

Removing multiple files from a Git repo that have already been deleted from disk

The most flexible solution I have found to date is to

git cola

And select all deleted files I want to stage.

(Note I usually do everything commandline in git, but git handles removed files a bit awkward).

Submit form after calling e.preventDefault()

The problem is that, even if you see the error, your return false affects the callback of the .each() method ... so, even if there is an error, you reach the line

$('form').unbind('submit').submit();

and the form is submitted.

You should create a variable, validated, for example, and set it to true. Then, in the callback, instead of return false, set validated = false.

Finally...

if (validated) $('form').unbind('submit').submit();

This way, only if there are no errors will the form be submitted.

How do I get Fiddler to stop ignoring traffic to localhost?

To get Fiddler to capture traffic when you are debugging on local host, after you hit F5 to begin degugging change the address so that localhost has a "." after it.

For instance, you start debugging and the you have the following URL in the Address bar:

http://localhost:49573/Default.aspx

Change it to:

http://localhost.:49573/Default.aspx

Hit enter and Fidder will start picking up your traffic.

Is it possible to display inline images from html in an Android TextView?

KOTLIN

There is also the possibility to use sufficientlysecure.htmltextview.HtmlTextView

Use like below in gradle files:

Project gradle file:

repositories {
    jcenter()
}

App gradle file:

dependencies {
implementation 'org.sufficientlysecure:html-textview:3.9'
}

Inside xml file replace your textView with:

<org.sufficientlysecure.htmltextview.HtmlTextView
      android:id="@+id/allNewsBlockTextView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="2dp"
      android:textColor="#000"
      android:textSize="18sp"
      app:htmlToString="@{detailsViewModel.selectedText}" />

Last line above is if you use Binding adapters where the code will be like:

@BindingAdapter("htmlToString")
fun bindTextViewHtml(textView: HtmlTextView, htmlValue: String) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setHtml(
        htmlValue,
        HtmlHttpImageGetter(textView, "n", true)
    );
    } else {
        textView.setHtml(
        htmlValue,
        HtmlHttpImageGetter(textView, "n", true)
        );
    }
}

More info from github page and a big thank you to the authors!!!!!

UICollectionView Set number of columns

Swift 3.0. Works for both horizontal and vertical scroll directions and variable spacing

Specify number of columns

let numberOfColumns: CGFloat = 3

Configure flowLayout to render specified numberOfColumns

if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
    let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
    let cellWidth = (collectionView.frame.width - max(0, numberOfColumns - 1)*horizontalSpacing)/numberOfColumns
    flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
}

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

Why does z-index not work?

If you set position to other value than static but your element's z-index still doesn't seem to work, it may be that some parent element has z-index set.

The stacking contexts have hierarchy, and each stacking context is considered in the stacking order of the parent's stacking context.

So with following html

_x000D_
_x000D_
div { border: 2px solid #000; width: 100px; height: 30px; margin: 10px; position: relative; background-color: #FFF; }_x000D_
#el3 { background-color: #F0F; width: 100px; height: 60px; top: -50px; }
_x000D_
<div id="el1" style="z-index: 5"></div>_x000D_
<div id="el2" style="z-index: 3">_x000D_
  <div id="el3" style="z-index: 8"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

no matter how big the z-index of el3 will be set, it will always be under el1 because it's parent has lower stacking context. You can imagine stacking order as levels where stacking order of el3 is actually 3.8 which is lower than 5.

If you want to check stacking contexts of parent elements, you can use this:

var el = document.getElementById("#yourElement"); // or use $0 in chrome;
do {
    var styles = window.getComputedStyle(el);
    console.log(styles.zIndex, el);
} while(el.parentElement && (el = el.parentElement));

There is a great article about stacking contexts on MDN

How do I do a not equal in Django queryset filtering?

Using exclude and filter

results = Model.objects.filter(x=5).exclude(a=true)

Replace Default Null Values Returned From Left Outer Join

In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).

 SELECT iar.Description, 
      IFNULL(iai.Quantity,0) as Quantity, 
      IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
      iar.Compliance 
    FROM InventoryAdjustmentReason iar
    LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

Try this function

getQuantileGroupNum <- function(vec, group_num, decreasing=FALSE) {
  if(decreasing) {
    abs(cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T) - group_num - 1)
  } else {
    cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T)
  }
}
> t1 <- runif(7)
> t1
[1] 0.4336094 0.2842928 0.5578876 0.2678694 0.6495285 0.3706474 0.5976223
> getQuantileGroupNum(t1, 4)
[1] 2 1 3 1 4 2 4
> getQuantileGroupNum(t1, 4, decreasing=T)
[1] 3 4 2 4 1 3 1

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

Using subprocess to run Python script on Windows

For example, to execute following with command prompt or BATCH file we can use this:

C:\Python27\python.exe "C:\Program files(x86)\dev_appserver.py" --host 0.0.0.0 --post 8080 "C:\blabla\"

Same thing to do with Python, we can do this:

subprocess.Popen(['C:/Python27/python.exe', 'C:\\Program files(x86)\\dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:\\blabla'], shell=True)

or

subprocess.Popen(['C:/Python27/python.exe', 'C:/Program files(x86)/dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:/blabla'], shell=True)

How to save a list to a file and read it as a list type?

What I did not like with many answers is that it makes way too many system calls by writing to the file line per line. Imho it is best to join list with '\n' (line return) and then write it only once to the file:

mylist = ["abc", "def", "ghi"]
myfile = "file.txt"
with open(myfile, 'w') as f:
    f.write("\n".join(mylist))

and then to open it and get your list again:

with open(myfile, 'r') as f:
    mystring = f.read()
my_list = mystring.split("\n")

How to study design patterns?

The best way is to begin coding with them. Design patterns are a great concept that are hard to apply from just reading about them. Take some sample implementations that you find online and build up around them.

A great resource is the Data & Object Factory page. They go over the patterns, and give you both conceptual and real world examples. Their reference material is great, too.

Tkinter: How to use threads to preventing main event loop from "freezing"

I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:

import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk

class UI:
   def __init__(self):
      self.root = tk.Tk()
      self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
      self.button = tk.Button(text="Do Task", command=self.do_task).pack()

   def do_task(self):
      rx.empty().subscribe(
         on_completed=self.long_running_task, 
         scheduler=self.pool_scheduler
      )

   def long_running_task(self):
      # your long running task here... eg:
      time.sleep(3)
      # if you want a callback on the main thread:
      self.root.after(5, self.on_task_complete)

   def on_task_complete(self):
       pass # runs on main thread

if __name__ == "__main__":
    ui = UI()
    ui.root.mainloop()

Another way to use this construct which might be cleaner (depending on preference):

tk.Button(text="Do Task", command=self.button_clicked).pack()

...

def button_clicked(self):

   def do_task(_):
      time.sleep(3) # runs on background thread
             
   def on_task_done():
      pass # runs on main thread

   rx.just(1).subscribe(
      on_next=do_task, 
      on_completed=lambda: self.root.after(5, on_task_done), 
      scheduler=self.pool_scheduler
   )

How do you create different variable names while in a loop?

for x in range(9):
    exec("string" + str(x) + " = 'hello'")

This should work.

uncaught syntaxerror unexpected token U JSON

Well, to all who actually can't find the error anywhere in your code, neither "undefined as it says in local storage nor null"..simply just comment out your code and write another one that actually removes the item in local storage ..after that ,u can comment or delet the current code and reset again the previous one by simply uncommenting it out (if u dint delet t ...if u did u can write it again:))

LocalStorage.setItem('Previous' , "removeprevious");  


LocalStorage.removeItem('Previous');   
 Console.log(LocalStorage.getItem('Previous'));

Console will show null and that it ..reset your code again if t doesn't work, dude!you got errors.

sorry for my English!

How to make inline plots in Jupyter Notebook larger?

A quick fix to "plot overlap" is to use plt.tight_layout():

Example (in my case)

for i,var in enumerate(categorical_variables):
    plt.title(var)
    plt.xticks(rotation=45)
    df[var].hist()
    plt.subplot(len(categorical_variables)/2, 2, i+1)

plt.tight_layout()

Get Android Device Name

I solved this by getting the Bluetooth name, but not from the BluetoothAdapter (that needs Bluetooth permission).

Here's the code:

Settings.Secure.getString(getContentResolver(), "bluetooth_name");

No extra permissions needed.

New og:image size for Facebook share?

UPDATE: The image size Must be larger than (600 x 315px)

The image size can be any size because Faceboook re-size the image width & height.

The default height is 208px & width is 398px for a post permalink:

www.facebook.com/{username}/posts/{post_id}

But for a timeline view:

www.facebook.com/{username}

width is 377px & height is 197px

I hope this will help you!

Using underscores in Java variables and method names

It's a blend of coding styles. One school of thought is to preface private members with an underscore to distinguish them.

setBar( int bar)
{
   _bar = bar;
}

instead of

setBar( int bar)
{
   this.bar = bar;
}

Others will use underscores to indicate a temp local variable that will go out of scope at the end of the method call. (I find this pretty useless - a good method shouldn't be that long, and the declaration is RIGHT THERE! so I know it goes out of scope) Edit: God forbid a programmer from this school and a programmer from the memberData school collaborate! It would be hell.

Sometimes, generated code will preface variables with _ or __. The idea being that no human would ever do this, so it's safe.

Get output parameter value in ADO.NET

The other response shows this, but essentially you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.

Using your code sample:

// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
   // Create parameter with Direction as Output (and correct name and type)
   SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
   { 
      Direction = ParameterDirection.Output 
   };

   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.Add(outputIdParam);

   conn.Open();
   cmd.ExecuteNonQuery();

   // Some various ways to grab the output depending on how you would like to
   // handle a null value returned from the query (shown in comment for each).

   // Note: You can use either the SqlParameter variable declared
   // above or access it through the Parameters collection by name:
   //   outputIdParam.Value == cmd.Parameters["@ID"].Value

   // Throws FormatException
   int idFromString = int.Parse(outputIdParam.Value.ToString());

   // Throws InvalidCastException
   int idFromCast = (int)outputIdParam.Value; 

   // idAsNullableInt remains null
   int? idAsNullableInt = outputIdParam.Value as int?; 

   // idOrDefaultValue is 0 (or any other value specified to the ?? operator)
   int idOrDefaultValue = outputIdParam.Value as int? ?? default(int); 

   conn.Close();
}

Be careful when getting the Parameters[].Value, since the type needs to be cast from object to what you're declaring it as. And the SqlDbType used when you create the SqlParameter needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString() (either explictly or implicitly via a Console.Write() or String.Format() call).

EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.

Tab separated values in awk

You need to set the OFS variable (output field separator) to be a tab:

echo "$line" | 
awk -v var="$mycol_new" -F $'\t' 'BEGIN {OFS = FS} {$3 = var; print}'

(make sure you quote the $line variable in the echo statement)

Hide header in stack navigator React navigation

For me navigationOptions didn't work. The following worked for me.

<Stack.Screen name="Login" component={Login}
      options={{
               headerShown: false
              }}
     />

How to select from subquery using Laravel Query Builder?

The solution of @JarekTkaczyk it is exactly what I was looking for. The only thing I miss is how to do it when you are using DB::table() queries. In this case, this is how I do it:

$other = DB::table( DB::raw("({$sub->toSql()}) as sub") )->select(
    'something', 
    DB::raw('sum( qty ) as qty'), 
    'foo', 
    'bar'
);
$other->mergeBindings( $sub );
$other->groupBy('something');
$other->groupBy('foo');
$other->groupBy('bar');
print $other->toSql();
$other->get();

Special atention how to make the mergeBindings without using the getQuery() method

Filtering Sharepoint Lists on a "Now" or "Today"

In the View, modify the current view or create a new view and make a filter change, select the radio button "Show items only when the following is true", in the below columns type "Created" and in the next dropdown select "is less than" and fill the next column [Today]-7.

The keyword [Today] denotes the current day for the calculation and this view will show as per your requirement

Counting inversions in an array

Here is one possible solution with variation of binary tree. It adds a field called rightSubTreeSize to each tree node. Keep on inserting number into binary tree in the order they appear in the array. If number goes lhs of node the inversion count for that element would be (1 + rightSubTreeSize). Since all those elements are greater than current element and they would have appeared earlier in the array. If element goes to rhs of a node, just increase its rightSubTreeSize. Following is the code.

Node { 
    int data;
    Node* left, *right;
    int rightSubTreeSize;

    Node(int data) { 
        rightSubTreeSize = 0;
    }   
};

Node* root = null;
int totCnt = 0;
for(i = 0; i < n; ++i) { 
    Node* p = new Node(a[i]);
    if(root == null) { 
        root = p;
        continue;
    } 

    Node* q = root;
    int curCnt = 0;
    while(q) { 
        if(p->data <= q->data) { 
            curCnt += 1 + q->rightSubTreeSize;
            if(q->left) { 
                q = q->left;
            } else { 
                q->left = p;
                break;
            }
        } else { 
            q->rightSubTreeSize++;
            if(q->right) { 
                q = q->right;
            } else { 
                q->right = p;
                break;
            }
        }
    }

    totCnt += curCnt;
  }
  return totCnt;

Good Hash Function for Strings

If it's a security thing, you could use Java crypto:

import java.security.MessageDigest;

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(stringToHash.getBytes());
String stringHash = new String(messageDigest.digest());

Static constant string (class member)

To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.

This is the restriction. Hence, in this case you need to define variable outside the class. refer answwer from @AndreyT

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

The error is due to maven official repository being not accessible. This repo (https://repo.maven.apache.org/maven2/) is not accessible so follow these steps:

  1. Firstly delete your /home/user/.m2 folder
  2. create .m2 folder at user home and repository folder within .m2
  3. copy the default settings.xml to .m2 folder
  4. Change mirrors as follows in the settings.xml as shown in below snap mirror_settings

_x000D_
_x000D_
<mirrors>_x000D_
  <mirror>_x000D_
    <id>UK</id>_x000D_
    <name>UK Central</name>_x000D_
    <url>http://uk.maven.org/maven2</url>_x000D_
    <mirrorOf>central</mirrorOf>_x000D_
  </mirror>_x000D_
</mirrors>
_x000D_
_x000D_
_x000D_

  1. Execute the mvn clean commands now .....

HTML radio buttons allowing multiple selections

Try this way of formation, it is rather fancy ...

Have a look at this jsfiddle

Button-Radio

The idea is to choose a the radio as a button instead of the normal circle image.

What is the difference between varchar and varchar2 in Oracle?

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.

  2. If we declare datatype as VARCHAR then it will occupy space for NULL values. In the case of VARCHAR2 datatype, it will not occupy any space for NULL values. e.g.,

    name varchar(10)

will reserve 6 bytes of memory even if the name is 'Ravi__', whereas

name varchar2(10) 

will reserve space according to the length of the input string. e.g., 4 bytes of memory for 'Ravi__'.

Here, _ represents NULL.

NOTE: varchar will reserve space for null values and varchar2 will not reserve any space for null values.

Replacing from match to end-of-line

This should do what you want:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five
>    four two  five five six
>    six  one  two seven four" | sed 's/two.*/BLAH/'
   one  BLAH
   four BLAH
   six  one  BLAH

The $ is unnecessary because the .* will finish at the end of the line anyways, and the g at the end is unnecessary because your first match will be the first two to the end of the line.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

The X-Frame-Options header is a security feature enforced at the browser level.

If you have control over your user base (IT dept for corp app), you could try something like a greasemonkey script (if you can a) deploy greasemonkey across everyone and b) deploy your script in a shared way)...

Alternatively, you can proxy their result. Create an endpoint on your server, and have that endpoint open a connection to the target endpoint, and simply funnel traffic backwards.

How many spaces will Java String.trim() remove?

All of them.

Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

~ Quoted from Java 1.5.0 docs

(But why didn't you just try it and see for yourself?)

Open an image using URI in Android's default gallery image viewer

A much cleaner, safer answer to this problem (you really shouldn't hard code Strings):

public void openInGallery(String imageId) {
  Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(imageId).build();
  Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  startActivity(intent);
}

All you have to do is append the image id to the end of the path for the EXTERNAL_CONTENT_URI. Then launch an Intent with the View action, and the Uri.

The image id comes from querying the content resolver.

Java for loop syntax: "for (T obj : objects)"

public class ForEachLoopExample {

    public static void main(String[] args) {

        System.out.println("For Each Loop Example: ");

        int[] intArray = { 1,2,3,4,5 };

        //Here iteration starts from index 0 to last index
        for(int i : intArray)
            System.out.println(i);
    }

}

Add a auto increment primary key to existing table in oracle

Snagged from Oracle OTN forums

Use alter table to add column, for example:

alter table tableName add(columnName NUMBER);

Then create a sequence:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

and, the use update to insert values in column like this

UPDATE tableName SET columnName = seq_test_id.NEXTVAL

Difference Between Cohesion and Coupling

The term cohesion is indeed a little counter intuitive for what it means in software design.

Cohesion common meaning is that something that sticks together well, is united, which are characterized by strong bond like molecular attraction. However in software design, it means striving for a class that ideally does only one thing, so multiple sub-modules are not even involved.

Perhaps we can think of it this way. A part has the most cohesion when it is the only part (does only one thing and can't be broken down further). This is what is desired in software design. Cohesion simply is another name for "single responsibility" or "separation of concerns".

The term coupling on the hand is quite intuitive which means when a module doesn't depend on too many other modules and those that it connects with can be easily replaced for example obeying liskov substitution principle .

Setting an int to Infinity in C++

You can also use INT_MAX:

http://www.cplusplus.com/reference/climits/

it's equivalent to using numeric_limits.

./xx.py: line 1: import: command not found

I've experienced the same problem and now I just found my solution to this issue.

#!/usr/bin/python

import sys
import os

os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))

This is the code[1] for my case. When I tried this script I received error message like :

import: command not found

I found people talks about the shebang. As you see there is the shebang in my python code above. I tried these and those trials but didn't find a good solution.

I finally tried to type the shebang my self.

#!/usr/bin/python

and removed the copied one.

And my problem solved!!!

I copied the code from the internet[1].

And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.

I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)

Journeyer

PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.

[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy

How to use hex color values

Swift 5: You can create colors in Xcode as explained in the following two images:

enter image description here

You should name the color because you reference the color by the name. As shown in image 2:

enter image description here

Best way to format multiple 'or' conditions in an if statement (Java)

No you cannot do that in Java. you can however write a method as follows:

boolean isContains(int i, int ... numbers) {
    // code to check if i is one of the numbers
    for (int n : numbers) {
        if (i == n) return true;
    }
    return false;
}

ComboBox: Adding Text and Value to an Item (no Binding Source)

You can use Dictionary Object instead of creating a custom class for adding text and value in a Combobox.

Add keys and values in a Dictionary Object:

Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");

Bind the source Dictionary object to Combobox:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

Retrieve Key and value:

string key = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Value;

Full Source : Combobox Text nd Value

How to compare strings in sql ignoring case?

before comparing the two or more strings first execute the following commands

alter session set NLS_COMP=LINGUISTIC;
alter session set NLS_SORT=BINARY_CI;

after those two statements executed then you may compare the strings and there will be case insensitive.for example you had two strings s1='Apple' and s2='apple', if yow want to compare the two strings before executing the above statements then those two strings will be treated as two different strings but when you compare the strings after the execution of the two alter statements then those two strings s1 and s2 will be treated as the same string

reasons for using those two statements

We need to set NLS_COMP=LINGUISTIC and NLS_SORT=BINARY_CI in order to use 10gR2 case insensitivity. Since these are session modifiable, it is not as simple as setting them in the initialization parameters. We can set them in the initialization parameters but they then only affect the server and not the client side.

SQL Inner-join with 3 tables?

This is correct query for join 3 table with same id**

select a.empname,a.empsalary,b.workstatus,b.bonus,c.dateofbirth from employee a, Report b,birth c where a.empid=b.empid and a.empid=c.empid and b.empid='103';

employee first table. report second table. birth third table

Preserve line breaks in angularjs

Based on @pilau s answer - but with an improvement that even the accepted answer does not have.

<div class="angular-with-newlines" ng-repeat="item in items">
   {{item.description}}
</div>

/* in the css file or in a style block */
.angular-with-newlines {
    white-space: pre-line;
}

This will use newlines and whitespace as given, but also break content at the content boundaries. More information about the white-space property can be found here:

https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

If you want to break on newlines, but also not collapse multiple spaces or white space preceeding the text (to render code or something), you can use:

white-space: pre-wrap;

Nice comparison of the different rendering modes: http://meyerweb.com/eric/css/tests/white-space.html

What happened to console.log in IE8?

It works in IE8. Open IE8's Developer Tools by hitting F12.

>>console.log('test')
LOG: test

What is the difference between Set and List?

List :

  1. List is ordered grouping elements
  2. List provides positional access in the elements of the collections.
  3. We can store duplicate elements in the list.
  4. List implements ArrayList, LinkedList, Vector and Stack.
  5. List can store multiple null elements.

Set :

  1. Unorderd grouping elements.
  2. Set doesn’t provides positional access in the elements of the collections.
  3. We can’t store duplicate elements in the set.
  4. Set implement HashSet and LinkedHashSet interfaces.
  5. Set can store only one null elements.

Git push error: "origin does not appear to be a git repository"

I had this problem cause i had already origin remote defined locally. So just change "origin" into another name:

git remote add originNew https://github.com/UAwebM...

git push -u originNew

or u can remove your local origin. to check your remote name type:

git remote

to remove remote - log in your clone repository and type:

git remote remove origin(depending on your remote's name)

Difference between checkout and export in SVN

svn export simply extracts all the files from a revision and does not allow revision control on it. It also does not litter each directory with .svn directories.

svn checkout allows you to use version control in the directory made, e.g. your standard commands such as svn update and svn commit.

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

How do you display code snippets in MS Word preserving format and syntax highlighting?

You can also use SciTE to paste code if you don't want to install heavy IDEs and then download plugins for all the code you're making. Simply choose your language from the language menu, type your code, high-light code, select Edit->Copy as RTF, paste into Word with formatting (default paste).

SciTE supports the following languages but probably has support for others: Abaqus*, Ada, ANS.1 MIB definition files*, APDL, Assembler (NASM, MASM), Asymptote*, AutoIt*, Avenue*, Batch files (MS-DOS), Baan*, Bash*, BlitzBasic*, Bullant*, C/C++/C#, Clarion, cmake*, conf (Apache), CSound, CSS*, D, diff files*, E-Script*, Eiffel*, Erlang*, Flagship (Clipper / XBase), Flash (ActionScript), Fortran*, Forth*, GAP*, Gettext, Haskell, HTML*, HTML with embedded JavaScript, VBScript, PHP and ASP*, Gui4Cli*, IDL - both MSIDL and XPIDL*, INI, properties* and similar, InnoSetup*, Java*, JavaScript*, LISP*, LOT*, Lout*, Lua*, Make, Matlab*, Metapost*, MMIXAL, MSSQL, nnCron, NSIS*, Objective Caml*, Opal, Octave*, Pascal/Delphi*, Perl, most of it except for some ambiguous cases*, PL/M*, Progress*, PostScript*, POV-Ray*, PowerBasic*, PowerShell*, PureBasic*, Python*, R*, Rebol*, Ruby*, Scheme*, scriptol*, Specman E*, Spice, Smalltalk, SQL and PLSQL, TADS3*, TeX and LaTeX, Tcl/Tk*, VB and VBScript*, Verilog*, VHDL*, XML*, YAML*.

HttpClient.GetAsync(...) never returns when using await/async

I'm going to put this in here more for completeness than direct relevance to the OP. I spent nearly a day debugging an HttpClient request, wondering why I was never getting back a response.

Finally found that I had forgotten to await the async call further down the call stack.

Feels about as good as missing a semicolon.

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Switch statement with returns -- code correctness

I would remove them. In my book, dead code like that should be considered errors because it makes you do a double-take and ask yourself "How would I ever execute that line?"

Writing JSON object to a JSON file with fs.writeFileSync

You need to stringify the object.

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));

Turning off hibernate logging console output

I managed to stop by adding those 2 lines

log4j.logger.org.hibernate.orm.deprecation=error

log4j.logger.org.hibernate=error

Bellow is what my log4j.properties looks like, i just leave some commented lines explaining the log level

# Root logger option
#Level/rules TRACE < DEBUG < INFO < WARN < ERROR < FATAL.
#FATAL: shows messages at a FATAL level only
#ERROR: Shows messages classified as ERROR and FATAL
#WARNING: Shows messages classified as WARNING, ERROR, and FATAL
#INFO: Shows messages classified as INFO, WARNING, ERROR, and FATAL
#DEBUG: Shows messages classified as DEBUG, INFO, WARNING, ERROR, and FATAL
#TRACE : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL
#ALL : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL
#OFF : No log messages display


log4j.rootLogger=INFO, file, console

log4j.logger.main=DEBUG
log4j.logger.org.hibernate.orm.deprecation=error
log4j.logger.org.hibernate=error

#######################################
# Direct log messages to a log file
log4j.appender.file.Threshold=ALL
log4j.appender.file.file=logs/MyProgram.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} - %m%n

# set file size limit
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=50


#############################################
# Direct log messages to System Out
log4j.appender.console.Threshold=INFO
log4j.appender.console.Target=System.out
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss} %-5p %c{1} - %m%n

Close Bootstrap Modal

Another way of doing this is that first you remove the class modal-open, which closes the modal. Then you remove the class modal-backdrop that removes the grayish cover of the modal.

Following code can be used:

$('body').removeClass('modal-open')
$('.modal-backdrop').remove()  

Alternative to mysql_real_escape_string without connecting to DB

From further research, I've found:

http://dev.mysql.com/doc/refman/5.1/en/news-5-1-11.html

Security Fix:

An SQL-injection security hole has been found in multi-byte encoding processing. The bug was in the server, incorrectly parsing the string escaped with the mysql_real_escape_string() C API function.

This vulnerability was discovered and reported by Josh Berkus and Tom Lane as part of the inter-project security collaboration of the OSDB consortium. For more information about SQL injection, please see the following text.

Discussion. An SQL injection security hole has been found in multi-byte encoding processing. An SQL injection security hole can include a situation whereby when a user supplied data to be inserted into a database, the user might inject SQL statements into the data that the server will execute. With regards to this vulnerability, when character set-unaware escaping is used (for example, addslashes() in PHP), it is possible to bypass the escaping in some multi-byte character sets (for example, SJIS, BIG5 and GBK). As a result, a function such as addslashes() is not able to prevent SQL-injection attacks. It is impossible to fix this on the server side. The best solution is for applications to use character set-aware escaping offered by a function such mysql_real_escape_string().

However, a bug was detected in how the MySQL server parses the output of mysql_real_escape_string(). As a result, even when the character set-aware function mysql_real_escape_string() was used, SQL injection was possible. This bug has been fixed.

Workarounds. If you are unable to upgrade MySQL to a version that includes the fix for the bug in mysql_real_escape_string() parsing, but run MySQL 5.0.1 or higher, you can use the NO_BACKSLASH_ESCAPES SQL mode as a workaround. (This mode was introduced in MySQL 5.0.1.) NO_BACKSLASH_ESCAPES enables an SQL standard compatibility mode, where backslash is not considered a special character. The result will be that queries will fail.

To set this mode for the current connection, enter the following SQL statement:

SET sql_mode='NO_BACKSLASH_ESCAPES';

You can also set the mode globally for all clients:

SET GLOBAL sql_mode='NO_BACKSLASH_ESCAPES';

This SQL mode also can be enabled automatically when the server starts by using the command-line option --sql-mode=NO_BACKSLASH_ESCAPES or by setting sql-mode=NO_BACKSLASH_ESCAPES in the server option file (for example, my.cnf or my.ini, depending on your system). (Bug#8378, CVE-2006-2753)

See also Bug#8303.

jQuery post() with serialize and extra data

Try $.param

$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));

converting Java bitmap to byte array

Ted Hopp is correct, from the API Documentation :

public void copyPixelsToBuffer (Buffer dst)

"... After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer. "

and

public ByteBuffer get (byte[] dst, int dstOffset, int byteCount)

"Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read."

how to open Jupyter notebook in chrome on windows

See response on this thread that has worked for me:

https://stackoverflow.com/a/62275293/11141700

NOTE - Additional STEP 3 that has made the difference for me compared to similar approaches suggested here

In short:

Step 1 - Generate config for Jupyter Notebook:

jupyter notebook --generate-config

Step 2 - Edit the config file using "nano" or other editor

The config fileshould be under your home directory under ".jupyter" folder:

~/.jupyter/jupyter_notebook_config.py

Step 3 - Disable launching browser by redirecting file

First comment out the line, then change True to False:

c.NotebookApp.use_redirect_file = False

Step 4 - add a line to your .bashrc file to set the BROWSER path

export BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'

For me it was Chrome under my Windows Program File. Otherwise any linux installation under WSL doesn't have a native browser to launch, so need to set it to the Windows executable.

Step 5 - restart .bashrc

source .bashrc

Concatenate two NumPy arrays vertically

a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))

works just as well as

np.array([[1,2,3], [4,5,6]])

Regardless of whether it is a list of lists or a list of 1d arrays, np.array tries to create a 2d array.

But it's also a good idea to understand how np.concatenate and its family of stack functions work. In this context concatenate needs a list of 2d arrays (or any anything that np.array will turn into a 2d array) as inputs.

np.vstack first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.

np.stack is a new function that joins the arrays on a new dimension. Default behaves just like np.array.

Look at the code for these functions. If written in Python you can learn quite a bit. For vstack:

return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)

How to program a fractal?

The mandelbrot set is generated by repeatedly evaluating a function until it overflows (some defined limit), then checking how long it took you to overflow.

Pseudocode:

MAX_COUNT = 64 // if we haven't escaped to infinity after 64 iterations, 
               // then we're inside the mandelbrot set!!!

foreach (x-pixel)
  foreach (y-pixel)
    calculate x,y as mathematical coordinates from your pixel coordinates
    value = (x, y)
    count = 0
    while value.absolutevalue < 1 billion and count < MAX_COUNT
        value = value * value + (x, y)
        count = count + 1

    // the following should really be one statement, but I split it for clarity
    if count == MAX_COUNT 
        pixel_at (x-pixel, y-pixel) = BLACK
    else 
        pixel_at (x-pixel, y-pixel) = colors[count] // some color map. 

Notes:

value is a complex number. a complex number (a+bi) is squared to give (aa-b*b+2*abi). You'll have to use a complex type, or include that calculation in your loop.

XPath:: Get following Sibling

You should be looking for the second tr that has the td that equals ' Color Digest ', then you need to look at either the following sibling of the first td in the tr, or the second td.

Try the following:

//tr[td='Color Digest'][2]/td/following-sibling::td[1]

or

//tr[td='Color Digest'][2]/td[2]

http://www.xpathtester.com/saved/76bb0bca-1896-43b7-8312-54f924a98a89

Fastest JSON reader/writer for C++

http://lloyd.github.com/yajl/

http://www.digip.org/jansson/

Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)

Unable to connect to any of the specified mysql hosts. C# MySQL

I am running mysql on a computer on a local network. MySQL Workbench could connect to that server, but not my c# code. I solved my issue by disconnecting from a vpn client that was running.

How can I capture the result of var_dump to a string?

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>

jQuery get text as number

myInteger = parseInt(myString);

It's a standard javascript function.

Python, HTTPS GET with basic authentication

requests.get(url, auth=requests.auth.HTTPBasicAuth(username=token, password=''))

If with token, password should be ''.

It works for me.

Rails Object to hash

If you are looking for only attributes, then you can get them by:

@post.attributes

Note that this calls ActiveModel::AttributeSet.to_hash every time you invoke it, so if you need to access the hash multiple times you should cache it in a local variable:

attribs = @post.attributes

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

What is the default value for Guid?

You can use Guid.Empty. It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000

you can also use these instead

var g = new Guid();
var g = default(Guid);

beware not to use Guid.NewGuid() because it will generate a new Guid.

use one of the options above which you and your team think it is more readable and stick to it. Do not mix different options across the code. I think the Guid.Empty is the best one since new Guid() might make us think it is generating a new guid and some may not know what is the value of default(Guid).

Searching in a ArrayList with custom objects for certain strings

try this

ArrayList<Datapoint > searchList = new ArrayList<Datapoint >();
String search = "a";
int searchListLength = searchList.size();
for (int i = 0; i < searchListLength; i++) {
if (searchList.get(i).getName().contains(search)) {
//Do whatever you want here
}
}

Base64 decode snippet in C++

There are several snippets here. However, this one is compact, efficient, and C++11 friendly:

static std::string base64_encode(const std::string &in) {

    std::string out;

    int val = 0, valb = -6;
    for (uchar c : in) {
        val = (val << 8) + c;
        valb += 8;
        while (valb >= 0) {
            out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val>>valb)&0x3F]);
            valb -= 6;
        }
    }
    if (valb>-6) out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val<<8)>>(valb+8))&0x3F]);
    while (out.size()%4) out.push_back('=');
    return out;
}

static std::string base64_decode(const std::string &in) {

    std::string out;

    std::vector<int> T(256,-1);
    for (int i=0; i<64; i++) T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;

    int val=0, valb=-8;
    for (uchar c : in) {
        if (T[c] == -1) break;
        val = (val << 6) + T[c];
        valb += 6;
        if (valb >= 0) {
            out.push_back(char((val>>valb)&0xFF));
            valb -= 8;
        }
    }
    return out;
}

How to set the action for a UIBarButtonItem in Swift

Swift 5 & iOS 13+ Programmatic Example

  1. You must mark your function with @objc, see below example!
  2. No parenthesis following after the function name! Just use #selector(name).
  3. private or public doesn't matter; you can use private.

Code Example

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    let menuButtonImage = UIImage(systemName: "flame")
    let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
    navigationItem.rightBarButtonItem = menuButton
}

@objc public func didTapMenuButton() {
    print("Hello World")
}

Selecting the last value of a column

Actually I found a simpler solution here:

http://www.google.com/support/forum/p/Google+Docs/thread?tid=20f1741a2e663bca&hl=en

It looks like this:

=FILTER( A10:A100 , ROW(A10:A100) =MAX( FILTER( ArrayFormula(ROW(A10:A100)) , NOT(ISBLANK(A10:A100)))))

Access a URL and read Data with R

Often data on webpages is in the form of an XML table. You can read an XML table into R using the package XML.

In this package, the function

readHTMLTable(<url>)

will look through a page for XML tables and return a list of data frames (one for each table found).

In Java, how do I check if a string contains a substring (ignoring case)?

How about matches()?

String string = "Madam, I am Adam";

// Starts with
boolean  b = string.startsWith("Mad");  // true

// Ends with
b = string.endsWith("dam");             // true

// Anywhere
b = string.indexOf("I am") >= 0;        // true

// To ignore case, regular expressions must be used

// Starts with
b = string.matches("(?i)mad.*");

// Ends with
b = string.matches("(?i).*adam");

// Anywhere
b = string.matches("(?i).*i am.*");

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I faced a similar situation, so i replaced all the external jar files(poi-bin-3.17-20170915) and make sure you add other jar files present in lib and ooxml-lib folders.

Hope this helps!!!:)

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

Creating static library worked for me, compiling using g++ -static. It bundles the dependent libraries along with the build.

Dealing with multiple Python versions and PIP?

Another possible way could be using conda and pip. Some time you probably want to use just one of those, but if you really need to set up a particular version of python I combine both.

  1. I create a starting conda enviroment with the python I want. As in here https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html. Alternatively you could set up the whole enviroment just using conda.

    conda create -n myenv python=3.6.4

  2. Then activate your enviroment with the python you like. This command could change depending on the OS.

    source activae myenv

  3. Now you have your python active then you could continue using conda but if you need/want to use pip:

    python -m pip -r requirements.txt

Here you have a possible way.

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

I faced this error before

when I tried to update specific field in my model in entity framwork

Letter letter = new Letter {ID = letterId, ExportNumber = letterExportNumber,EntityState = EntityState.Modified};
LetterService.ChangeExportNumberfor(letter);
//----------


public int ChangeExportNumber(Letter letter)
    {
        int result = 0;
        using (var db = ((LettersGeneratorEntities) GetContext()))
        {
            db.Letters.Attach(letter);
            db.Entry(letter).Property(x => x.ExportNumber).IsModified = true;
            result += db.SaveChanges();
        }
        return result;
    }

and according the above answers

I found the Validation message The SignerName field is required.

which pointing to field in my model

and when I checked my database schema I found

enter image description here

so off coure ValidationException has its right to raise

and according to this field I want it to be nullable, (I dont know how I messed it)

so I changed that field to allow Null, and by this my code will not give me this error again

so This error maybe will happened if you invalidate Your Data integrity of your database

How to Test Facebook Connect Locally

Facebook has added test versions feature.

First, add a test version of your application: Create Test App

Create Test App

Then, change the Site URL to "http://localhost" under Website, and press Save Changes

enter image description here

That's all, but be careful: App ID and App Secret keys are different for the application and its test versions!

Sockets: Discover port availability using Java

This is the implementation coming from the Apache camel project:

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 */
public static boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.

Hope this helps.

GROUP_CONCAT comma separator - MySQL

Query to achieve your requirment

SELECT id,GROUP_CONCAT(text SEPARATOR ' ') AS text FROM table_name group by id;

Looking for simple Java in-memory cache

If you're needing something simple, would this fit the bill?

Map<K, V> myCache = Collections.synchronizedMap(new WeakHashMap<K, V>());

It wont save to disk, but you said you wanted simple...

Links:

(As Adam commented, synchronising a map has a performance hit. Not saying the idea doesn't have hairs on it, but would suffice as a quick and dirty solution.)

How to automatically close cmd window after batch file execution?

This worked for me. I just wanted to close the command window automatically after exiting the game. I just double click on the .bat file on my desktop. No shortcuts.

taskkill /f /IM explorer.exe
C:\"GOG Games"\Starcraft\Starcraft.exe
start explorer.exe
exit /B

Visual Studio : short cut Key : Duplicate Line

if you have a macos version, cmd+shift+D can make the job for you

How can I avoid running ActiveRecord callbacks?

When I need full control over the callback, I create another attribute that is used as a switch. Simple and effective:

Model:

class MyModel < ActiveRecord::Base
  before_save :do_stuff, unless: :skip_do_stuff_callback
  attr_accessor :skip_do_stuff_callback

  def do_stuff
    puts 'do stuff callback'
  end
end

Test:

m = MyModel.new()

# Fire callbacks
m.save

# Without firing callbacks
m.skip_do_stuff_callback = true
m.save

# Fire callbacks again
m.skip_do_stuff_callback = false
m.save

How do I prompt a user for confirmation in bash script?

use case/esac.

read -p "Continue (y/n)?" choice
case "$choice" in 
  y|Y ) echo "yes";;
  n|N ) echo "no";;
  * ) echo "invalid";;
esac

advantage:

  1. neater
  2. can use "OR" condition easier
  3. can use character range, eg [yY][eE][sS] to accept word "yes", where any of its characters may be in lowercase or in uppercase.

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

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

Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.

Install:

$ npm install cors
const cors = require('cors');
app.use(cors());

You have to put this code in your node server.

Regular expression replace in C#

Add the following 2 lines

var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);

If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"

How to embed fonts in CSS?

One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.

Read it and you will end with something like:

/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('?'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

How to reduce the image file size using PIL

If you hava a fact png (1MB for 400x400 etc.):

__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")

Proper way to exit iPhone application?

It may be appropriate to exit an app if it is a long lived app that also executes in the background, for example to get location updates (using the location updates background capability for that).

For example, let's say the user logs out of your location based app, and pushes the app to the background using the home button. In this case your app may keep running, but it could make sense to completely exit it. It would be good for the user (releases memory and other resources that don't need to be used), and good for app stability (i.e. making sure the app is periodically restarted when possible is a safety net against memory leaks and other low memory issues).

This could (though probably shouldn't, see below :-) be achieved with something like:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if (/* logged out */) {
        exit(0);
    } else {
       // normal handling.
    }
}

Since the app would then exit out of the background it will not look wrong to the user, and will not resemble a crash, providing the user interface is restored the next time they run the app. In other words, to the user it would not look any different to a system initiated termination of the app when the app is in the background.

Still, it would be preferable to use a more standard approach to let the system know that the app can be terminated. For example in this case, by making sure the GPS is not in use by stopping requesting location updates, including turning off show current location on a map view if present. That way the system will take care of terminating the app a few minutes (i.e. [[UIApplication sharedApplication] backgroundTimeRemaining]) after the app enters the background. This would get all the same benefits without having to use code to terminate the app.

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if (/* logged out */) {
       // stop requesting location updates if not already done so
       // tidy up as app will soon be terminated (run a background task using beginBackgroundTaskWithExpirationHandler if needed).
    } else {
       // normal handling.
    }
}

And of course, using exit(0) would never be appropriate for the average production app that runs in the foreground, as per other answers that reference http://developer.apple.com/iphone/library/qa/qa2008/qa1561.html

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

Just customize the footer section

.footer 
{
   position: fixed;
   bottom: 0;
   width: 100%;
   padding: 1rem;
   text-align: center;
}
 <div class="footer">
   Footer is always bootom
 </div>

Getting the last element of a list

You can also use the code below, if you do not want to get IndexError when the list is empty.

next(reversed(some_list), None)

How to get the mobile number of current sim card in real device?

Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

How to make a query with group_concat in sql server

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , STUFF((
          SELECT ',' + T.maskdetail
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH('')), 1, 1, '') as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by  A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname

How do I change the font size of a UILabel in Swift?

swift 4:

label.font = UIFont("your font name", size: 15)

also if you want to set the label font in all views in your project try this in appDelegate>didFinishLaunch: UILabel.appearance().font = UIFont("your font name", size: 15)

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

Hide element by class in pure Javascript

document.getElementsByClassName returns an HTMLCollection(an array-like object) of all elements matching the class name. The style property is defined for Element not for HTMLCollection. You should access the first element using the bracket(subscript) notation.

document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';

Updated jsFiddle

To change the style rules of all elements matching the class, using the Selectors API:

[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
  el.style.visibility = 'hidden';
});

If for...of is available:

for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';

How to grep recursively, but only in files with certain extensions?

Since this is a matter of finding files, let's use find!

Using GNU find you can use the -regex option to find those files in the tree of directories whose extension is either .h or .cpp:

find -type f -regex ".*\.\(h\|cpp\)"
#            ^^^^^^^^^^^^^^^^^^^^^^^

Then, it is just a matter of executing grep on each of its results:

find -type f -regex ".*\.\(h\|cpp\)" -exec grep "your pattern" {} +

If you don't have this distribution of find you have to use an approach like Amir Afghani's, using -o to concatenate options (the name is either ending with .h or with .cpp):

find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +
#            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

And if you really want to use grep, follow the syntax indicated to --include:

grep "your pattern" -r --include=*.{cpp,h}
#                      ^^^^^^^^^^^^^^^^^^^

AttributeError: can't set attribute in python

namedtuples are immutable, just like standard tuples. You have two choices:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.

The former would look like:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

Is there a command line command for verifying what version of .NET is installed

This is working for me:

@echo off
SETLOCAL ENABLEEXTENSIONS

echo Verify .Net Framework Version

for /f "delims=" %%I in ('dir /B /A:D %windir%\Microsoft.NET\Framework') do (
    for /f "usebackq tokens=1,3 delims= " %%A in (`reg query "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\%%I" 2^>nul ^| findstr Install`) do (
        if %%A==Install (
            if %%B==0x1 (
                echo %%I
            )
        )
    )
)

echo Do you see version v4.5.2 or greater in the list?

pause

ENDLOCAL 

The 2^>nul redirects errors to vapor.

How to store a command in a variable in a shell script?

Its is not necessary to store commands in variables even as you need to use it later. just execute it as per normal. If you store in variable, you would need some kind of eval statement or invoke some unnecessary shell process to "execute your variable".

What does $1 mean in Perl?

The variables $1 .. $9 are also read only variables so you can't implicitly assign a value to them:

$1 = 'foo'; print $1;

That will return an error: Modification of a read-only value attempted at script line 1.

You also can't use numbers for the beginning of variable names:

$1foo = 'foo'; print $1foo;

The above will also return an error.

What does .pack() do?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

For Expose.class Error i.e

java.util.zip.ZipException: duplicate entry: com/google/gson/annotations/Expose.class

use the below code

configurations {
    all*.exclude  module: 'gson'
}

How to select top n rows from a datatable/dataview in ASP.NET

I just used Midhat's answer but appended CopyToDataTable() on the end.

The code below is an extension to the answer that I used to quickly enable some paging.

int pageNum = 1;
int pageSize = 25;

DataTable dtPage = dt.Rows.Cast<System.Data.DataRow>().Skip((pageNum - 1) * pageSize).Take(pageSize).CopyToDataTable();

Is there any WinSCP equivalent for linux?

To run WinSCP under Linux (Ubuntu 12.04), follow these steps:

  1. Run sudo apt-get install wine (run this one time only, to get 'wine' in your system, if you haven't it)
  2. Download latest WinSCP portable package https://winscp.net/eng/download.php
  3. Make a folder and put the content of zip file in this folder
  4. Open a terminal
  5. Type wine WinSCP.exe

Done! WinSCP will run like in Windows environment!

Best regards.

Keylistener in Javascript

Did you check the small Mousetrap library?

Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

How to send POST request in JSON using HTTPClient in Android?

Too much code for this task, checkout this library https://github.com/kodart/Httpzoid Is uses GSON internally and provides API that works with objects. All JSON details are hidden.

Http http = HttpFactory.create(context);
http.get("http://example.com/users")
    .handler(new ResponseHandler<User[]>() {
        @Override
        public void success(User[] users, HttpResponse response) {
        }
    }).execute();

java.net.SocketTimeoutException: Read timed out under Tomcat

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

Output first 100 characters in a string

From python tutorial:

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

So it is safe to use x[:100].

Body set to overflow-y:hidden but page is still scrollable in Chrome

I finally found a way to fix the issue so I'm answering here.

I set the overflow-y on the #content instead, and wrapped my steps in another div. It works.

Here is the final code:

<body>
  <div id="content">
    <div id="steps">
       <div class="step">this is the 1st step</div>
       <div class="step">this is the 2nd step</div>
       <div class="step">this is the 3rd step</div>
     </div>
   </div>
</body>

#content {
  position:absolute;
  width:100%;
  overflow-y:hidden;
  top:0;
  bottom:0;
}
.step {
  position:relative;
  height:500px;
  margin-bottom:500px;
}

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

Select Tomcat server in Targeted Runtime

Project->Properties->Targeted Runtimes (Select your Tomcat Server)

How can I install a local gem?

If you create your gems with bundler:

# do this in the proper directory
bundle gem foobar

You can install them with rake after they are written:

# cd into your gem directory
rake install

Chances are, that your downloaded gem will know rake install, too.

Implementing SearchView in action bar


For Searchview use these code

  1. For XML

    <android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView">
    
    </android.support.v7.widget.SearchView>
    

  2. In your Fragment or Activity

    package com.example.user.salaryin;
    
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
    import com.example.user.salaryin.Network.ApiClient;
    import com.example.user.salaryin.POJO.ProductDetailPojo;
    import com.example.user.salaryin.Service.ServiceAPI;
    import java.util.ArrayList;
    import java.util.List;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    
    
    public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
    
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<ProductDetailPojo> arrayList;
    BusinessModuleAdapter adapter;
    private ProgressDialog pDialog;
    GridLayoutManager gridLayoutManager;
    SearchView searchView;
    
    public OneFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.one_fragment,container,false);
    
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
    
    
        searchView=(SearchView)rootView.findViewById(R.id.searchView);
        searchView.setQueryHint("Search BY Brand");
        searchView.setOnQueryTextListener(this);
    
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(layoutManager);
        gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        getImageData();
    
    
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.one_fragment, container, false);
        return rootView;
    }
    
    
    private void getImageData() {
        pDialog.show();
        ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
        Call<List<ProductDetailPojo>> call = service.getBusinessImage();
    
        call.enqueue(new Callback<List<ProductDetailPojo>>() {
            @Override
            public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
                if (response.isSuccessful()) {
                    arrayList = (ArrayList<ProductDetailPojo>) response.body();
                    adapter = new BusinessModuleAdapter(arrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    pDialog.dismiss();
                } else if (response.code() == 401) {
                    pDialog.dismiss();
                    Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
    
            }
        });
    }
    
       /* @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint("Search Product");
        searchView.setOnQueryTextListener(this);
    }*/
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ProductDetailPojo> newList = new ArrayList<>();
        for (ProductDetailPojo productDetailPojo : arrayList) {
            String name = productDetailPojo.getDetails().toLowerCase();
    
            if (name.contains(newText) )
                newList.add(productDetailPojo);
            }
        adapter.setFilter(newList);
        return true;
       }
    }
    
  3. In adapter class

     public void setFilter(List<ProductDetailPojo> newList){
        arrayList=new ArrayList<>();
        arrayList.addAll(newList);
        notifyDataSetChanged();
    }
    

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

Can I set an opacity only to the background image of a div?

None of the solutions worked for me. If everything else fails, get the picture to Photoshop and apply some effect. 5 minutes versus so much time on this...

php.ini & SMTP= - how do you pass username & password

PHP mail() command does not support authentication. Your options:

  1. PHPMailer- Tutorial
  2. PEAR - Tutorial
  3. Custom functions - See various solutions in the notes section: http://php.net/manual/en/ref.mail.php

Where am I? - Get country

Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();

Since it is the sim code it also should not change when traveling to other countries.

Validate Dynamically Added Input fields

Reset form validation after adding new fields.

function resetFormValidator(formId) {
    $(formId).removeData('validator');
    $(formId).removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(formId);
}

How to set the value for Radio Buttons When edit?

This is easier to read for me:

<input type="radio" name="rWF" id="rWF" value=1  <?php if ($WF == '1') {echo ' checked ';} ?> />Water Fall</label>
<input type="radio" name="rWF" id="rWF" value=0 <?php if ($WF == '0') {echo ' checked ';} ?> />nope</label>

Twitter Bootstrap date picker

I was also facing the same problem for twitter-bootstrap.

As eternicode/bootstrap-datepicker is incompatible with jQuery UI.

But twitter-bootstrap is working fine for vitalets/bootstrap-datepicker even with jQuery UI.

Deleting array elements in JavaScript - delete vs splice

Others have already properly compared delete with splice.

Another interesting comparison is delete versus undefined: a deleted array item uses less memory than one that is just set to undefined;

For example, this code will not finish:

let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
    ary.push(y);
    ary[y] = undefined;
    y += 1;
}
console(ary.length);

It produces this error:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

So, as you can see undefined actually takes up heap memory.

However, if you also delete the ary-item (instead of just setting it to undefined), the code will slowly finish:

let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
    ary.push(x);
    ary[x] = undefined;
    delete ary[x];
    x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);

These are extreme examples, but they make a point about delete that I haven't seen anyone mention anywhere.

What exactly is a Maven Snapshot and why do we need it?

simply snapshot means it is the version which is not stable one.

when version includes snapshot like 1.0.0 -SNAPSHOT means it is not stable version and look for remote repository to resolve dependencies

XMLHttpRequest status 0 (responseText is empty)

If the server responds to an OPTIONS method and to GET and POST (whichever of them you're using) with a header like:

Access-Control-Allow-Origin: *

It might work OK. Seems to in FireFox 3.5 and rekonq 0.4.0. Apparently, with that header and the initial response to OPTIONS, the server is saying to the browser, "Go ahead and let this cross-domain request go through."

Adding and reading from a Config file

  1. Add an Application Configuration File item to your project (Right -Click Project > Add item). This will create a file called app.config in your project.

  2. Edit the file by adding entries like <add key="keyname" value="someValue" /> within the <appSettings> tag.

  3. Add a reference to the System.Configuration dll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"].

Cannot lower case button text in android studio

there are 3 ways to do it.

1.Add the following line on style.xml to change entire application

<item name="android:textAllCaps">false</item>

2.Use

android:textAllCaps="false"

in your layout-v21

mButton.setTransformationMethod(null);
  1. add this line under the element(button or edit text) in xml

android:textAllCaps="false"

regards

How do I programmatically set the value of a select box element using JavaScript?


function foo(value)
{
    var e = document.getElementById('leaveCode');
    if(e) e.value = value;
}

Responsive table handling in Twitter Bootstrap

Bootstrap 3 now has Responsive tables out of the box. Hooray! :)

You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive

Add a <div class="table-responsive"> surrounding your table and you should be good to go:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

To make it work on all layouts you can do this:

.table-responsive
{
    overflow-x: auto;
}

Using bootstrap with bower

Also remember that with a command like:

bower search twitter

You get a result with a list of any package related to twitter. This way you are up to date of everything regarding Twitter and Bower like for instance knowing if there is brand new bower component.

Updating a dataframe column in spark

importing col, when from pyspark.sql.functions and updating fifth column to integer(0,1,2) based on the string(string a, string b, string c) into a new DataFrame.

from pyspark.sql.functions import col, when 

data_frame_temp = data_frame.withColumn("col_5",when(col("col_5") == "string a", 0).when(col("col_5") == "string b", 1).otherwise(2))

How to take MySQL database backup using MySQL Workbench?

  1. On ‘HOME’ page -- > select 'Manage Import / Export' under 'Server Administration'

  2. A box comes up... choose which server holds the data you want to back up.

  3. On the 'Export to Disk' tab, then select which databases you want to export.

  4. If you want all the tables, select option ‘Export to self-contained file’, otherwise choose the other option for a selective restore

  5. If you need advanced options, see other post, otherwise then click ‘Start Export’

failed to open stream: No such file or directory in

It's because you have included a leading / in your file path. The / makes it start at the top of your filesystem. Note: filesystem path, not Web site path (you're not accessing it over HTTP). You can use a relative path with include_once (one that doesn't start with a leading /).

You can change it to this:

include_once 'headerSite.php';

That will look first in the same directory as the file that's including it (i.e. C:\xampp\htdocs\PoliticalForum\ in your example.

C# Inserting Data from a form into an access Database

and doesnt give any clues

Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:

catch (OleDbException  ex)
{
    MessageBox.Show(ex.Source);
    conn.Close();
}

All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.

Don't ignore the exception, it contains information about what went wrong and why.

There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.

In your debugger, place a breakpoint inside the catch block and examine the details of the exception. You'll find it contains a lot of information.

drag drop files into standard html file input

_x000D_
_x000D_
//----------App.js---------------------//_x000D_
$(document).ready(function() {_x000D_
    var holder = document.getElementById('holder');_x000D_
    holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
    holder.ondrop = function (e) {_x000D_
      this.className = 'hidden';_x000D_
      e.preventDefault();_x000D_
      var file = e.dataTransfer.files[0];_x000D_
      var reader = new FileReader();_x000D_
      reader.onload = function (event) {_x000D_
          document.getElementById('image_droped').className='visible'_x000D_
          $('#image_droped').attr('src', event.target.result);_x000D_
      }_x000D_
      reader.readAsDataURL(file);_x000D_
    };_x000D_
});
_x000D_
.holder_default {_x000D_
    width:500px; _x000D_
    height:150px; _x000D_
    border: 3px dashed #ccc;_x000D_
}_x000D_
_x000D_
#holder.hover { _x000D_
    width:400px; _x000D_
    height:150px; _x000D_
    border: 3px dashed #0c0 !important; _x000D_
}_x000D_
_x000D_
.hidden {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.visible {_x000D_
    visibility: visible;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html>_x000D_
    <head>_x000D_
        <title> HTML 5 </title>_x000D_
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>_x000D_
    </head>_x000D_
    <body>_x000D_
      <form method="post" action="http://example.com/">_x000D_
        <div id="holder" style="" id="holder" class="holder_default">_x000D_
          <img src="" id="image_droped" width="200" style="border: 3px dashed #7A97FC;" class=" hidden"/>_x000D_
        </div>_x000D_
      </form>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What does Html.HiddenFor do?

Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.

So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.

To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting

Finding modified date of a file/folder

To get the modified date on a single file try:

$lastModifiedDate = (Get-Item "C:\foo.tmp").LastWriteTime

To compare with another:

$dateA= $lastModifiedDate 
$dateB= (Get-Item "C:\other.tmp").LastWriteTime

if ($dateA -ge $dateB) {
  Write-Host("C:\foo.tmp was modified at the same time or after C:\other.tmp")
} else {
  Write-Host("C:\foo.tmp was modified before C:\other.tmp")
}

How to add an image to the emulator gallery in android studio?

I went through the Android Device Monitor

  1. Click on device
  2. Select Android Device Monitor's File Explorer tab
  3. Select Pictures folder (path: data -> media -> 0 -> Pictures)
  4. Click "Push folders on to device" icon
  5. Select pic from computer and ok.

Check for special characters (/*-+_@&$#%) in a string?

Try this way.

public static bool hasSpecialChar(string input)
    {
        string specialChar = @"\|!#$%&/()=?»«@£§€{}.-;'<>_,";
        foreach (var item in specialChar)
        {
            if (input.Contains(item)) return true;
        }

        return false;
    }

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

In my case:

PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.synchronous            = NO;

Was trying to do this with dispatch_group

Is it better to use path() or url() in urls.py for django 2.0?

Regular expressions don't seem to work with the path() function with the following arguments: path(r'^$', views.index, name="index").

It should be like this: path('', views.index, name="index").

The 1st argument must be blank to enter a regular expression.

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

It could also be possible that you have created the "Products" in your login schema and you were trying to execute the same in a different schema (probably dbo)

Steps to resolve this issue

1)open the management studio 2) Locate the object in the explorer and identify the schema under which your object is? ( it is the text before your object name ). In the image below its the "dbo" and my object name is action status

highlighted part is schema name

if you see it like "yourcompanydoamin\yourloginid" then you should you can modify the permission on that specific schema and not any other schema.

you may refer to "Ownership and User-Schema Separation in SQL Server"

How can I rename a project folder from within Visual Studio?

Well, I did it my way

  • Close Visual Studio 2012
  • Rename your subdirectory to the preferred name under .sln
  • Delete the *.suo file
  • Open the solution again, and fix any properties of Project(s) loaded to meet the new subdirectory name

Segmentation fault on large array sizes

In C or C++ local objects are usually allocated on the stack. You are allocating a large array on the stack, more than the stack can handle, so you are getting a stackoverflow.

Don't allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap. Global variables are fine, if you don't use the from any other compilation unit. To make sure this doesn't happen by accident, add a static storage specifier, otherwise just use the heap.

This will allocate in the BSS segment, which is a part of the heap:

static int c[1000000];
int main()
{
   cout << "done\n";
   return 0;
}

This will allocate in the DATA segment, which is a part of the heap too:

int c[1000000] = {};
int main()
{
   cout << "done\n";
   return 0;
}

This will allocate at some unspecified location in the heap:

int main()
{
   int* c = new int[1000000];
   cout << "done\n";
   return 0;
}

Dropping connected users in Oracle database

Here's how I "automate" Dropping connected users in Oracle database:

# A shell script to Drop a Database Schema, forcing off any Connected Sessions (for example, before an Import) 
# Warning! With great power comes great responsibility.
# It is often advisable to take an Export before Dropping a Schema

if [ "$1" = "" ] 
then
    echo "Which Schema?"
    read schema
else
    echo "Are you sure? (y/n)"
    read reply
    [ ! $reply = y ] && return 1
    schema=$1
fi

sqlplus / as sysdba <<EOF
set echo on
alter user $schema account lock;
-- Exterminate all sessions!
begin     
  for x in ( select sid, serial# from v\$session where username=upper('$schema') )
  loop  
   execute immediate ( 'alter system kill session '''|| x.Sid || ',' || x.Serial# || ''' immediate' );  
  end loop;  
  dbms_lock.sleep( seconds => 2 ); -- Prevent ORA-01940: cannot drop a user that is currently connected
end;
/
drop user $schema cascade;
quit
EOF

Screen width in React Native

Simply declare this code to get device width

let deviceWidth = Dimensions.get('window').width

Maybe it's obviously but, Dimensions is an react-native import

import { Dimensions } from 'react-native'

Dimensions will not work without that

Dynamic Height Issue for UITableView Cells (Swift)

For objective c this is one of my nice solution. it's worked for me.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.text = [_nameArray objectAtIndex:indexPath.row];
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

We need to apply these 2 changes.

1)cell.textLabel.numberOfLines = 0;
  cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;

2)return UITableViewAutomaticDimension;

Difference between _self, _top, and _parent in the anchor tag target attribute

Section 6.16 Frame target names in the HTML 4.01 spec defines the meanings, but it is partly outdated. It refers to “windows”, whereas HTML5 drafts more realistically speak about “browsing contexts”, since modern browsers often use tabs instead of windows in this context.

Briefly, _self is the default (current browsing context, i.e. current window or tab), so it is useful only to override a <base target=...> setting. The value _parent refers to the frameset that is the parent of the current frame, whereas _top “breaks out of all frames” and opens the linked document in the entire browser window.

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

Find multiple files and rename them in Linux

Scipt above can be written in one line:

find /tmp -name "*.txt" -exec bash -c 'mv $0 $(echo "$0" | sed -r \"s|.txt|.cpp|g\")' '{}' \;

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

I tried this and it worked:

C:\cd MySQL installed path\MySQL -uyourusername -pyourpassword

php exec command (or similar) to not wait for result

"exec nohup setsid your_command"

the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).

How to install and run Typescript locally in npm?

To install TypeScript local in project as a development dependency you can use --save-dev key

npm install --save-dev typescript

It's also writes the typescript into your package.json

You also need to have a tsconfig.json file. For example

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    ".npm"
  ]
}

For more information about the tsconfig you can see here http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

How to manually install a pypi module without pip/easy_install?

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

Adding line break in C# Code behind page

C# doesn't have an explicit line break character. You statements end with a semicolon so you can span your statements over many lines. These are both the same:

public string GenerateString()
{
    return "abc" + "def";
}

public string GenerateString()
{
    return
        "abc" +
        "def";
}

PHP code to convert a MySQL query to CSV

Check out this question / answer. It's more concise than @Geoff's, and also uses the builtin fputcsv function.

$result = $db_con->query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
    $headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, $headers);
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

What does map(&:name) mean in Ruby?

Two things are happening here, and it's important to understand both.

As described in other answers, the Symbol#to_proc method is being called.

But the reason to_proc is being called on the symbol is because it's being passed to map as a block argument. Placing & in front of an argument in a method call causes it to be passed this way. This is true for any Ruby method, not just map with symbols.

def some_method(*args, &block)
  puts "args: #{args.inspect}"
  puts "block: #{block.inspect}"
end

some_method(:whatever)
# args: [:whatever]
# block: nil

some_method(&:whatever)
# args: []
# block: #<Proc:0x007fd23d010da8>

some_method(&"whatever")
# TypeError: wrong argument type String (expected Proc)
# (String doesn't respond to #to_proc)

The Symbol gets converted to a Proc because it's passed in as a block. We can show this by trying to pass a proc to .map without the ampersand:

arr = %w(apple banana)
reverse_upcase = proc { |i| i.reverse.upcase }
reverse_upcase.is_a?(Proc)
=> true

arr.map(reverse_upcase)
# ArgumentError: wrong number of arguments (1 for 0)
# (map expects 0 positional arguments and one block argument)

arr.map(&reverse_upcase)
=> ["ELPPA", "ANANAB"]

Even though it doesn't need to be converted, the method won't know how to use it because it expects a block argument. Passing it with & gives .map the block it expects.

How can I get the last character in a string?

Javascript strings have a length property that will tell you the length of the string.

Then all you have to do is use the substr() function to get the last character:

var myString = "Test3";
var lastChar = myString.substr(myString.length -1);

edit: yes, or use the array notation as the other posts before me have done.

Lots of String functions explained here

How to create a checkbox with a clickable label?

You could also use CSS pseudo elements to pick and display your labels from all your checkbox's value attributes (respectively).
Edit: This will only work with webkit and blink based browsers (Chrome(ium), Safari, Opera....) and thus most mobile browsers. No Firefox or IE support here.
This may only be useful when embedding webkit/blink onto your apps.

<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
    content: attr(value);
    margin: -3px 15px;
    vertical-align: top;
    white-space:nowrap;
    display: inline-block;
}
</style>

All pseudo element labels will be clickable.

Demo:http://codepen.io/mrmoje/pen/oteLl, + The gist of it

Default nginx client_max_body_size

The default value for client_max_body_size directive is 1 MiB.

It can be set in http, server and location context — as in the most cases, this directive in a nested block takes precedence over the same directive in the ancestors blocks.

Excerpt from the ngx_http_core_module documentation:

Syntax:   client_max_body_size size;
Default:  client_max_body_size 1m;
Context:  http, server, location

Sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.

Don't forget to reload configuration by nginx -s reload or service nginx reload commands prepending with sudo (if any).

How to call a parent method from child class in javascript?

ES6 style allows you to use new features, such as super keyword. super keyword it's all about parent class context, when you are using ES6 classes syntax. As a very simple example, checkout:

class Foo {
    static classMethod() {
        return 'hello';
    }
}

class Bar extends Foo {
    static classMethod() {
        return super.classMethod() + ', too';
    }
}
Bar.classMethod(); // 'hello, too'

Also, you can use super to call parent constructor:

class Foo {}

class Bar extends Foo {
    constructor(num) {
        let tmp = num * 2; // OK
        this.num = num; // ReferenceError
        super();
        this.num = num; // OK
    }
}

And of course you can use it to access parent class properties super.prop. So, use ES6 and be happy.

How to iterate over arguments in a Bash script

Note that Robert's answer is correct, and it works in sh as well. You can (portably) simplify it even further:

for i in "$@"

is equivalent to:

for i

I.e., you don't need anything!

Testing ($ is command prompt):

$ set a b "spaces here" d
$ for i; do echo "$i"; done
a
b
spaces here
d
$ for i in "$@"; do echo "$i"; done
a
b
spaces here
d

I first read about this in Unix Programming Environment by Kernighan and Pike.

In bash, help for documents this:

for NAME [in WORDS ... ;] do COMMANDS; done

If 'in WORDS ...;' is not present, then 'in "$@"' is assumed.

How to set the allowed url length for a nginx request (error code: 414, uri too large)

From: http://nginx.org/r/large_client_header_buffers

Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

Create a copy of a table within the same database DB2

You have to surround the select part with parenthesis.

CREATE TABLE SCHEMA.NEW_TB AS (
    SELECT *
    FROM SCHEMA.OLD_TB
) WITH NO DATA

Should work. Pay attention to all the things @Gilbert said would not be copied.

I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.

How do I know which version of Javascript I'm using?

Rather than finding which version you are using you can rephrase your question to "which version of ECMA script does my browser's JavaScript/JSscript engine conform to".

For IE :

alert(@_jscript_version);      //IE

Refer Squeegy's answer for non-IE versions :)

How to get data from Magento System Configuration

$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');

sectionName, groupName and fieldName are present in etc/system.xml file of your module.

The above code will automatically fetch config value of currently viewed store.

If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig function as below:

$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);

How can I remove the gloss on a select element in Safari on Mac?

Sorry to pile on to an old item. I found partial answers to my questions here but had to do some work so I wanted to share my results for the next person.

I ended up using the same approach as the other contributors, but with a few tweaks to fix the following

  1. Long text was covering the arrows in the other solutions
  2. The image being used was a somewhat old and ugly up/down combo arrow.

The below will give you a working solution with the above issues fixed. Note: I used a white arrow for my use case, you may need to change the color of the arrow for yours.

here's a preview:

select with white arrow

select{    
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgaWQ9IkxheWVyXzEiICAgZGF0YS1uYW1lPSJMYXllciAxIiAgIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIiAgIHZlcnNpb249IjEuMSIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxIHIxMzcyNSIgICBzb2RpcG9kaTpkb2NuYW1lPSJkb3dubG9hZC5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE0MjAyIj4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgIDwvY2M6V29yaz4gICAgPC9yZGY6UkRGPiAgPC9tZXRhZGF0YT4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9IjEwMjciICAgICBpZD0ibmFtZWR2aWV3NDIwMCIgICAgIHNob3dncmlkPSJmYWxzZSIgICAgIGlua3NjYXBlOnpvb209Ijg0LjMiICAgICBpbmtzY2FwZTpjeD0iMi40NzQ5OTk5IiAgICAgaW5rc2NhcGU6Y3k9IjUiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyNyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjEiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJMYXllcl8xIiAvPiAgPGRlZnMgICAgIGlkPSJkZWZzNDE5MCI+ICAgIDxzdHlsZSAgICAgICBpZD0ic3R5bGU0MTkyIj4uY2xzLTJ7ZmlsbDojNDQ0O308L3N0eWxlPiAgPC9kZWZzPiAgPHRpdGxlICAgICBpZD0idGl0bGU0MTk0Ij5hcnJvd3M8L3RpdGxlPiAgPHBvbHlnb24gICAgIGNsYXNzPSJjbHMtMiIgICAgIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIiAgICAgaWQ9InBvbHlnb240MTk4IiAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MSIgLz48L3N2Zz4=) no-repeat 101% 50%;
  padding-right:20px;
}

Half circle with CSS (border, outline only)

I had a similar issue not long time ago and this was how I solved it

_x000D_
_x000D_
.rotated-half-circle {_x000D_
  /* Create the circle */_x000D_
  width: 40px;_x000D_
  height: 40px;_x000D_
  border: 10px solid black;_x000D_
  border-radius: 50%;_x000D_
  /* Halve the circle */_x000D_
  border-bottom-color: transparent;_x000D_
  border-left-color: transparent;_x000D_
  /* Rotate the circle */_x000D_
  transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
_x000D_
_x000D_

Return current date plus 7 days

strtotime will automatically use the current unix timestamp to base your string annotation off of.

Just do:

$date = strtotime("+7 day");
echo date('M d, Y', $date);

Added Info For Future Visitors: If you need to pass a timestamp to the function, the below will work.

This will calculate 7 days from yesterday:

$timestamp = time()-86400;

$date = strtotime("+7 day", $timestamp);
echo date('M d, Y', $date);

Use curly braces to initialize a Set in Python

From Python 3 documentation (the same holds for python 2.7):

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

in python 2.7:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

Be aware that {} is also used for map/dict:

>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'> 

One can also use comprehensive syntax to initialize sets:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])

Why does the jquery change event not trigger when I set the value of a select using val()?

If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:

window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);

Mismatch Detected for 'RuntimeLibrary'

I had this problem along with mismatch in ITERATOR_DEBUG_LEVEL. As a sunday-evening problem after all seemed ok and good to go, I was put out for some time. Working in de VS2017 IDE (Solution Explorer) I had recently added/copied a sourcefile reference to my project (ctrl-drag) from another project. Looking into properties->C/C++/Preprocessor - at source file level, not project level - I noticed that in a Release configuration _DEBUG was specified instead of NDEBUG for this source file. Which was all the change needed to get rid of the problem.

Is there a Public FTP server to test upload and download?

Tele2 provides ftp://speedtest.tele2.net , you can log in as anonymous and upload anything to test your upload speed. For download testing they provide fixed size files, you can choose which fits best to your test.

You can connect with username of anonymous and any password (e.g. anonymous ). You can upload files to upload folder. You can't create new folder here. Your file is deleted immediately after successful upload.

Found here: http://speedtest.tele2.net/

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:

  • People in favor of cssSelector say that it is more readable and faster (especially when running against Internet Explorer).
  • While those in favor of XPath tout it's ability to transverse the page (while cssSelector cannot).
  • Traversing the DOM in older browsers like IE8 does not work with cssSelector but is fine with XPath.
  • XPath can walk up the DOM (e.g. from child to parent), whereas cssSelector can only traverse down the DOM (e.g. from parent to child)
  • However not being able to traverse the DOM with cssSelector in older browsers isn't necessarily a bad thing as it is more of an indicator that your page has poor design and could benefit from some helpful markup.
  • Ben Burton mentions you should use cssSelector because that's how applications are built. This makes the tests easier to write, talk about, and have others help maintain.
  • Adam Goucher says to adopt a more hybrid approach -- focusing first on IDs, then cssSelector, and leveraging XPath only when you need it (e.g. walking up the DOM) and that XPath will always be more powerful for advanced locators.

Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.

Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.


Test SetUp

To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark was used.


Test Code

require_relative 'base'
require 'benchmark'

class LargeDOM < Base

  LOCATORS = {
    nested_sibling_traversal: {
      css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
      xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
    },
    nested_sibling_traversal_by_class: {
      css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
      xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
    },
    table_header_id_and_class: {
      css: "table#large-table thead .column-50",
      xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
    },
    table_header_id_class_and_direct_desc: {
      css: "table#large-table > thead .column-50",
      xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
    },
    table_header_traversing: {
      css: "table#large-table thead tr th:nth-of-type(50)",
      xpath: "//table[@id='large-table']//thead//tr//th[50]"
    },
    table_header_traversing_and_direct_desc: {
      css: "table#large-table > thead > tr > th:nth-of-type(50)",
      xpath: "//table[@id='large-table']/thead/tr/th[50]"
    },
    table_cell_id_and_class: {
      css: "table#large-table tbody .column-50",
      xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
    },
    table_cell_id_class_and_direct_desc: {
      css: "table#large-table > tbody .column-50",
      xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
    },
    table_cell_traversing: {
      css: "table#large-table tbody tr td:nth-of-type(50)",
      xpath: "//table[@id='large-table']//tbody//tr//td[50]"
    },
    table_cell_traversing_and_direct_desc: {
      css: "table#large-table > tbody > tr > td:nth-of-type(50)",
      xpath: "//table[@id='large-table']/tbody/tr/td[50]"
    }
  }

  attr_reader :driver

  def initialize(driver)
    @driver = driver
    visit '/large'
    is_displayed?(id: 'siblings')
    super
  end

  # The benchmarking approach was borrowed from
  # http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
  def benchmark
    Benchmark.bmbm(27) do |bm|
      LOCATORS.each do |example, data|
    data.each do |strategy, locator|
      bm.report(example.to_s + " using " + strategy.to_s) do
        begin
          ENV['iterations'].to_i.times do |count|
         find(strategy => locator)
          end
        rescue Selenium::WebDriver::Error::NoSuchElementError => error
          puts "( 0.0 )"
        end
      end
    end
      end
    end
  end

end

Results

NOTE: The output is in seconds, and the results are for the total run time of 100 executions.

In Table Form:

css_xpath_under_microscopev2

In Chart Form:

  • Chrome:

chart-chrome

  • Firefox:

chart-firefox

  • Internet Explorer 8:

chart-ie8

  • Internet Explorer 9:

chart-ie9

  • Internet Explorer 10:

chart-ie10

  • Opera:

chart-opera


Analyzing the Results

  • Chrome and Firefox are clearly tuned for faster cssSelector performance.
  • Internet Explorer 8 is a grab bag of cssSelector that won't work, an out of control XPath traversal that takes ~65 seconds, and a 38 second table traversal with no cssSelector result to compare it against.
  • In IE 9 and 10, XPath is faster overall. In Safari, it's a toss up, except for a couple of slower traversal runs with XPath. And across almost all browsers, the nested sibling traversal and table cell traversal done with XPath are an expensive operation.
  • These shouldn't be that surprising since the locators are brittle and inefficient and we need to avoid them.

Summary

  • Overall there are two circumstances where XPath is markedly slower than cssSelector. But they are easily avoidable.
  • The performance difference is slightly in favor of for non-IE browsers and slightly in favor of for IE browsers.

Trivia

You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.

Stripping everything but alphanumeric chars from a string in Python

As a spin off from some other answers here, I offer a really simple and flexible way to define a set of characters that you want to limit a string's content to. In this case, I'm allowing alphanumerics PLUS dash and underscore. Just add or remove characters from my PERMITTED_CHARS as suits your use case.

PERMITTED_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-" 
someString = "".join(c for c in someString if c in PERMITTED_CHARS)

Open File in Another Directory (Python)

import os
import os.path
import shutil

You find your current directory:

d = os.getcwd() #Gets the current working directory

Then you change one directory up:

os.chdir("..") #Go up one directory from working directory

Then you can get a tupple/list of all the directories, for one directory up:

o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple

Then you can search the tuple for the directory you want and open the file in that directory:

for item in o:
    if os.path.exists(item + '\\testfile.txt'):
    file = item + '\\testfile.txt'

Then you can do stuf with the full file path 'file'

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How to set commands output as a variable in a batch file

These answers were all so close to the answer that I needed. This is an attempt to expand on them.

In a Batch file

If you're running from within a .bat file and you want a single line that allows you to export a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json to a variable named AWS_ACCESS_KEY then you want this:

FOR /F "tokens=* USEBACKQ" %%g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%%g")

On the Command Line

If you're at the C:\ prompt you want a single line that allows you to run a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json to a variable named AWS_ACCESS_KEY then you want this:

FOR /F "tokens=* USEBACKQ" %g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%g")

Explanation

The only difference between the two answers above is that on the command line, you use a single % in your variable. In a batch file, you have to double up on the percentage signs (%%).

Since the command includes colons, quotes, and parentheses, you need to include the USEBACKQ line in the options so that you can use backquotes to specify the command to run and then all kinds of funny characters inside of it.

How to resize datagridview control when form resizes

Set the property of your DataGridView:

Anchor: Top,Left
AutoSizeColumn: Fill
Dock: Fill

What's the common practice for enums in Python?

class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3

what does "error : a nonstatic member reference must be relative to a specific object" mean?

CPMSifDlg::EncodeAndSend() method is declared as non-static and thus it must be called using an object of CPMSifDlg. e.g.

CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);

If EncodeAndSend doesn't use/relate any specifics of an object (i.e. this) but general for the class CPMSifDlg then declare it as static:

class CPMSifDlg {
...
  static int EncodeAndSend(...);
  ^^^^^^
};

How to get HttpRequestMessage data

From this answer:

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
    string jsonContent = content.ReadAsStringAsync().Result;
}

Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.

How to check for an empty struct?

Just a quick addition, because I tackled the same issue today:

With Go 1.13 it is possible to use the new isZero() method:

if reflect.ValueOf(session).IsZero() {
     // do stuff...
}

I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual().

cleanup php session files

Debian/Ubuntu handles this with a cronjob defined in /etc/cron.d/php5

# /etc/cron.d/php5: crontab fragment for php5
#  This purges session files older than X, where X is defined in seconds
#  as the largest value of session.gc_maxlifetime from all your php.ini
#  files, or 24 minutes if not defined.  See /usr/lib/php5/maxlifetime

# Look for and purge old sessions every 30 minutes
09,39 *     * * *     root   [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm

The maxlifetime script simply returns the number of minutes a session should be kept alive by checking php.ini, it looks like this

#!/bin/sh -e

max=1440

for ini in /etc/php5/*/php.ini; do
        cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\([0-9]\+\).*$/\1/p' $ini 2>/dev/null || true);
        [ -z "$cur" ] && cur=0
        [ "$cur" -gt "$max" ] && max=$cur
done

echo $(($max/60))

exit 0

Finding common rows (intersection) in two Pandas dataframes

My understanding is that this question is better answered over in this post.

But briefly, the answer to the OP with this method is simply:

s1 = pd.merge(df1, df2, how='inner', on=['user_id'])

Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.

How do you append to a file?

If multiple processes are writing to the file, you must use append mode or the data will be scrambled. Append mode will make the operating system put every write, at the end of the file irrespective of where the writer thinks his position in the file is. This is a common issue for multi-process services like nginx or apache where multiple instances of the same process, are writing to the same log file. Consider what happens if you try to seek, then write:

Example does not work well with multiple processes: 

f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");

writer1: seek to end of file.           position 1000 (for example)
writer2: seek to end of file.           position 1000
writer2: write data at position 1000    end of file is now 1000 + length of data.
writer1: write data at position 1000    writer1's data overwrites writer2's data.

By using append mode, the operating system will place any write at the end of the file.

f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");

Append most does not mean, "open file, go to end of the file once after opening it". It means, "open file, every write I do will be at the end of the file".

WARNING: For this to work you must write all your record in one shot, in one write call. If you split the data between multiple writes, other writers can and will get their writes in between yours and mangle your data.