SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

You can also try to reset visual studio setting

  1. Open Visual Studio Command Prompt

  2. Enter command Devenv /ResetSettings

It will remove already saved TFS account and ask for credentials

Check if starting characters of a string are alphabetical in T-SQL

You don't need to use regex, LIKE is sufficient:

WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'

Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

How to remove all MySQL tables from the command-line without DROP database permissions?

Try this.

This works even for tables with constraints (foreign key relationships). Alternatively you can just drop the database and recreate, but you may not have the necessary permissions to do that.

mysqldump -u[USERNAME] -p[PASSWORD] \
  --add-drop-table --no-data [DATABASE] | \
  grep -e '^DROP \| FOREIGN_KEY_CHECKS' | \
  mysql -u[USERNAME] -p[PASSWORD] [DATABASE]

In order to overcome foreign key check effects, add show table at the end of the generated script and run many times until the show table command results in an empty set.

maven error: package org.junit does not exist

if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

see JUNIT conflict

Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

If you want to remove the support for any architecture, for example, ARMv7-s in your case, use menu Project -> Build Settings -> remove the architecture from "valid architectures".

You can use this as a temporary solution until the library has been updated. You have to remove the architecture from your main project, not from the library.

Alternatively, you can set the flag for your debug configuration's "Build Active Architecture Only" to Yes. Leave the release configuration's "Build Active Architecture Only" to No, just so you'll get a reminder before releasing that you ought to upgrade any third-party libraries you're using.

What does it mean when Statement.executeUpdate() returns -1?

As the statement executed is not actually DML (eg UPDATE, INSERT or EXECUTE), but a piece of T-SQL which contains DML, I suspect it is not treated as an update-query.

Section 13.1.2.3 of the JDBC 4.1 specification states something (rather hard to interpret btw):

When the method execute returns true, the method getResultSet is called to retrieve the ResultSet object. When execute returns false, the method getUpdateCount returns an int. If this number is greater than or equal to zero, it indicates the update count returned by the statement. If it is -1, it indicates that there are no more results.

Given this information, I guess that executeUpdate() internally does an execute(), and then - as execute() will return false - it will return the value of getUpdateCount(), which in this case - in accordance with the JDBC spec - will return -1.

This is further corroborated by the fact 1) that the Javadoc for Statement.executeUpdate() says:

Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

And 2) that the Javadoc for Statement.getUpdateCount() specifies:

the current result as an update count; -1 if the current result is a ResultSet object or there are no more results

Just to clarify: given the Javadoc for executeUpdate() the behavior is probably wrong, but it can be explained.

Also as I commented elsewhere, the -1 might just indicate: maybe something was changed, but we simply don't know, or we can't give an accurate number of changes (eg because in this example it is a piece of T-SQL that is executed).

Converting Epoch time into the datetime

First a bit of info in epoch from man gmtime

The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar  time.   When  inter-
       preted  as  an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
       Time (UTC).

to understand how epoch should be.

>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)

just ensure the arg you are passing to time.gmtime() is integer.

How To Check If A Key in **kwargs Exists?

You can discover those things easily by yourself:

def hello(*args, **kwargs):
    print kwargs
    print type(kwargs)
    print dir(kwargs)

hello(what="world")

Vim: How to insert in visual block mode?

  1. press ctrl and v // start select
  2. press shift and i // then type in any text
  3. press esc esc // press esc twice

CURL to access a page that requires a login from a different page

Also you might want to log in via browser and get the command with all headers including cookies:

Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".

screenshot

How do I close an open port from the terminal on the Mac?

very simple find port 5900:

sudo lsof -i :5900

then considering 59553 as PID

sudo kill 59553

iOS 6 apps - how to deal with iPhone 5 screen size?

I think you can use [UIScreen mainScreen].bounds.size.height and calculate step for your objects. when you calculate step you can set coordinates for two resolutions.

Or you can get height like above and if(iphone5) then... else if(iphone4) then... else if(ipad). Something like this.

If you use storyboards then you have to create new for new iPhone i think.

Convert double to BigDecimal and set BigDecimal Precision

BigDecimal b = new BigDecimal(c).setScale(2,BigDecimal.ROUND_HALF_UP);

How to develop or migrate apps for iPhone 5 screen resolution?

Use the Auto Layout feature for views. It will adjust automatically to all resolutions.

Create two xibs for a controller having controller name with suffix either ~iphone or ~ipad. At compile time, Xcode will take the right xib based on the device.

Use size classes, if you want to create a single xib for both iPhone and iPad, if the view is simple enough to port to iPhone and iPad.

excel delete row if column contains value from to-remove-list

I've found a more reliable method (at least on Excel 2016 for Mac) is:

Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:

= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")

Then just sort the list by column C to find what you have to delete.

How to add RSA key to authorized_keys file?

>ssh user@serverip -p portnumber 
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys

Targeting .NET Framework 4.5 via Visual Studio 2010

I have been struggling with VS2010/DNFW 4.5 integration and have finally got this working. Starting in VS 2008, a cache of assemblies was introduced that is used by Visual Studio called the "Referenced Assemblies". This file cache for VS 2010 is located at \Reference Assemblies\Microsoft\Framework.NetFramework\v4.0. Visual Studio loads framework assemblies from this location instead of from the framework installation directory. When Microsoft says that VS 2010 does not support DNFW 4.5 what they mean is that this directory does not get updated when DNFW 4.5 is installed. Once you have replace the files in this location with the updated DNFW 4.5 files, you will find that VS 2010 will happily function with DNFW 4.5.

Representing EOF in C code?

The answer is NO, but...

You may confused because of the behavior of fgets()

From http://www.cplusplus.com/reference/cstdio/fgets/ :

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

grep for special characters in Unix

Tell grep to treat your input as fixed string using -F option.

grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

Option -n is required to get the line number,

grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

How to center align the ActionBar title in Android?

A Kotlin-only solution that does not require to have changes in the XML Layouts:

//Function to call in onResume() of your activity
private fun centerToolbarText() {
    val mTitleTextView = AppCompatTextView(this)
    mTitleTextView.text = title
    mTitleTextView.setSingleLine()//Remove it if you want to allow multiple lines in the toolbar
    mTitleTextView.textSize = 25f
    val layoutParams = android.support.v7.app.ActionBar.LayoutParams(
        ActionBar.LayoutParams.WRAP_CONTENT,
        ActionBar.LayoutParams.WRAP_CONTENT
    )
    layoutParams.gravity = Gravity.CENTER
    supportActionBar?.setCustomView(mTitleTextView,layoutParams)
    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
}

Reference member variables as class members

C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.

When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.

DataTable: How to get item value with row name and column name? (VB)

Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
     searchedValue = rows(0).Item("ColumnName2") 
End If

With FirstOrDefault:

Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
     searchedValue = row.Item("ColumnName2") 
End If

In C#:

var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
     searchedValue = row["ColumnName2"];

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How to send a "multipart/form-data" with requests in python?

Here is the simple code snippet to upload a single file with additional parameters using requests:

url = 'https://<file_upload_url>'
fp = '/Users/jainik/Desktop/data.csv'

files = {'file': open(fp, 'rb')}
payload = {'file_id': '1234'}

response = requests.put(url, files=files, data=payload, verify=False)

Please note that you don't need to explicitly specify any content type.

NOTE: Wanted to comment on one of the above answers but could not because of low reputation so drafted a new response here.

How to coerce a list object to type 'double'

If your list as multiple elements that need to be converted to numeric, you can achieve this with lapply(a, as.numeric).

Gson - convert from Json to a typed ArrayList<T>

Kotlin

data class Player(val name : String, val surname: String)

val json = [
  {
    "name": "name 1",
    "surname": "surname 1"
  },
  {
    "name": "name 2",
    "surname": "surname 2"
  },
  {
    "name": "name 3",
    "surname": "surname 3"
  }
]

val typeToken = object : TypeToken<List<Player>>() {}.type
val playerArray = Gson().fromJson<List<Player>>(json, typeToken)

OR

val playerArray = Gson().fromJson(json, Array<Player>::class.java)

Refresh a page using PHP

You can do it with PHP:

header("Refresh:0");

It refreshes your current page, and if you need to redirect it to another page, use following:

header("Refresh:0; url=page2.php");

Access-Control-Allow-Origin: * in tomcat

Please check your web.xml again. You might be making some silly mistake. As my application is working fine with the same init-param configuration...

Please copy paste the web.xml, if the problem still persists.

Django: Calling .update() on a single model instance retrieved by .get()?

As @Nils mentionned, you can use the update_fields keyword argument of the save() method to manually specify the fields to update.

obj_instance = Model.objects.get(field=value)
obj_instance.field = new_value
obj_instance.field2 = new_value2

obj_instance.save(update_fields=['field', 'field2'])

The update_fields value should be a list of the fields to update as strings.

See https://docs.djangoproject.com/en/2.1/ref/models/instances/#specifying-which-fields-to-save

How can I stop the browser back button using JavaScript?

<script>
    window.location.hash = "no-back-button";

    // Again because Google Chrome doesn't insert
    // the first hash into the history
    window.location.hash = "Again-No-back-button"; 

    window.onhashchange = function(){
        window.location.hash = "no-back-button";
    }
</script>

Screenshot sizes for publishing android app on Google Play

The files need to be in a JPEG or PNG format of 24 bits, in a 2:1 ratio if it is a portrait and a 16:9 ratio for landscapes. Be careful that if you go for different sizes: the maximum size should not be more than twice bigger than the minimum size.

error: function returns address of local variable

a is an array local to the function.Once the function returns it does not exist anymore and hence you should not return the address of a local variable.
In other words the lifetime of a is within the scope({,}) of the function and if you return a pointer to it what you have is a pointer pointing to some memory which is not valid. Such variables are also called automatic variabels because their lifetime is automatically managed you do not need to manage it explicitly.

Since you need to extend the variable to persist beyond the scope of the function you You need to allocate a array on heap and return a pointer to it.

char *a = malloc(1000); 

This way the array a resides in memory untill you call a free() on the same address.
Do not forget to do so or you end up with a memory leak.

Can I add color to bootstrap icons only using CSS?

It is actually very easy:

just use:

.icon-name{
color: #0C0;}

For example:

.icon-compass{
color: #C30;}

That's it.

How to run Ruby code from terminal?

You can run ruby commands in one line with the -e flag:

ruby -e "puts 'hi'"

Check the man page for more information.

How to get the last row of an Oracle a table

select * from table_name ORDER BY primary_id DESC FETCH FIRST 1 ROWS ONLY;

That's the simplest one without doing sub queries

Create MSI or setup project with Visual Studio 2012

Please see:

Visual Studio setup projects (vdproj) will not ship with future versions of VS

Windows Installer Deployment

It was announced 1 1/2 years ago that the project types were being killed. Alternatives are:

  1. Use A VS2008/2010 Solution to build your installer
  2. Switch to another tool such as InstallShield or Windows Installer XML

Printing to the console in Google Apps Script?

Answering the OP questions

A) What do I not understand about how the Google Apps Script console works with respect to printing so that I can see if my code is accomplishing what I'd like?

The code on .gs files of a Google Apps Script project run on the server rather than on the web browser. The way to log messages was to use the Class Logger.

B) Is it a problem with the code?

As the error message said, the problem was that console was not defined but nowadays the same code will throw other error:

ReferenceError: "playerArray" is not defined. (line 12, file "Code")

That is because the playerArray is defined as local variable. Moving the line out of the function will solve this.

var playerArray = [];

function addplayerstoArray(numplayers) {
  for (i=0; i<numplayers; i++) {
    playerArray.push(i);
  }
}  

addplayerstoArray(7);

console.log(playerArray[3])

Now that the code executes without throwing errors, instead to look at the browser console we should look at the Stackdriver Logging. From the Google Apps Script editor UI click on View > Stackdriver Logging.

Addendum

On 2017 Google released to all scripts Stackdriver Logging and added the Class Console, so including something like console.log('Hello world!') will not throw an error but the log will be on Google Cloud Platform Stackdriver Logging Service instead of the browser console.

From Google Apps Script Release Notes 2017

June 23, 2017

Stackdriver Logging has been moved out of Early Access. All scripts now have access to Stackdriver logging.

From Logging > Stackdriver logging

The following example shows how to use the console service to log information in Stackdriver.

function measuringExecutionTime() {
  // A simple INFO log message, using sprintf() formatting.
  console.info('Timing the %s function (%d arguments)', 'myFunction', 1);

  // Log a JSON object at a DEBUG level. The log is labeled
  // with the message string in the log viewer, and the JSON content
  // is displayed in the expanded log structure under "structPayload".
  var parameters = {
      isValid: true,
      content: 'some string',
      timestamp: new Date()
  };
  console.log({message: 'Function Input', initialData: parameters});

  var label = 'myFunction() time';  // Labels the timing log entry.
  console.time(label);              // Starts the timer.
  try {
    myFunction(parameters);         // Function to time.
  } catch (e) {
    // Logs an ERROR message.
    console.error('myFunction() yielded an error: ' + e);
  }
  console.timeEnd(label);      // Stops the timer, logs execution duration.
}

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

Adding calculated column(s) to a dataframe in pandas

The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,

def lower_wick_vec(o, l, c):
    min_oc = numpy.where(o > c, c, o)
    return min_oc - l

where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:

def lower_wick_df(df):
    min_oc = df[['Open', 'Close']].min(axis=1)
    return min_oc - l

The other three will work on columns or vectors just as they are. Then you can finish off with

def is_hammer(df):
    lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"]) 
    cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
    return cl & lw

Bit operators can perform set logic on boolean vectors, & for and, | for or etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.

For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.

How to check list A contains any value from list B?

You can Intersect the two lists:

if (A.Intersect(B).Any())

Codeigniter $this->input->post() empty while $_POST is working correctly

Upgrading from 2.2.x to 3.0.x -- reason post method fails. If you are upgrading CI 3.x, need to keep the index_page in config file. Also check the .htaccess file for mod_rewrite. CI_3.x

$config['index_page'] = ''; // ci 2.x
$config['index_page'] = 'index.php'; // ci 3.x

My .htaccess

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
 ErrorDocument 404 /index.php
</IfModule>

Auto-Submit Form using JavaScript

This solution worked for me:

<body onload="setTimeout(function() { document.myform.submit() }, 5000)">
   <form action=TripRecorder name="myform">
      <textarea id="result1"  name="res1" value="str1" cols="20" rows="1" ></textarea> <br> <br/>
      <textarea id="result2" name="res2" value="str2" cols="20" rows="1" ></textarea>
   </form>
</body>

Oracle date function for the previous month

Data for last month-

select count(distinct switch_id)
  from [email protected]
 where dealer_name =  'XXXX'
   and to_char(CREATION_DATE,'MMYYYY') = to_char(add_months(trunc(sysdate),-1),'MMYYYY');

Good MapReduce examples

One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.

Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.

Vector of Vectors to create matrix

What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vector you have named matrix in your example.

One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.

Please try this out :

int num;
for(int i=0; i<RR; i++){

      vector<int>inter_mat;       //Intermediate matrix to help insert(push) contents of whole row at a time

      for(int j=0; j<CC; j++){
           cin>>num;             //Extra variable in helping push our number to vector
           vin.push_back(num);   //Inserting numbers in a row, one by one 
          }

      v.push_back(vin);          //Inserting the whole row at once to original 2D matrix 
}

How to stop Python closing immediately when executed in Microsoft Windows

I know a simple answer! Open your cmd, the type in: cd C:\directory your file is in and then type python your progam.py

How to sort by dates excel?

For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.

Chrome ignores autocomplete="off"

When using a widget like jQuery UI's Autocomplete make sure to check that it is not adding/changing to autocomplete attribute to off. I found this to be true when using it and will break any work you may have done to override any browser field caching. Make certain that you have a unique name attribute and force a unique autocomplete attribute after the widget initializes. See below for some hints on how that might work for your situation.

<?php $autocomplete = 'off_'.time(); ?>
<script>
   $('#email').autocomplete({
      create: function( event, ui ) {
         $(this).attr('autocomplete','<? echo $autocomplete; ?>');
      },
      source: function (request, response) { //your code here },
      focus: function( event, ui ) { //your code here },
      select: function( event, ui ) { //your code here },
   });
</script>
<input type="email" id="email" name="email_<? echo $autocomplete; ?>" autocomplete="<? echo $autocomplete; ?>" />

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

How do I set a cookie on HttpClient's HttpRequestMessage

Here's how you could set a custom cookie value for the request:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = await client.PostAsync("/test", content);
    result.EnsureSuccessStatusCode();
}

Staging Deleted files

Ian Mackinnon found the answer, but it's better with xargs:

git ls-files --deleted -z | xargs -r0 git rm

As a git alias:

git config --global alias.rm-deleted '!git ls-files --deleted -z | xargs -r0 git rm'

This uses xargs with NUL termination (the only byte guarranteed not to appear in a path) and the option to not run git rm if the file list is empty.

This syntax is also fish compatible.

How to get evaluated attributes inside a custom directive

For an attribute value that needs to be interpolated in a directive that is not using an isolated scope, e.g.,

<input my-directive value="{{1+1}}">

use Attributes' method $observe:

myApp.directive('myDirective', function () {
  return function (scope, element, attr) {
    attr.$observe('value', function(actual_value) {
      element.val("value = "+ actual_value);
    })
 }
});

From the directive page,

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

If the attribute value is just a constant, e.g.,

<input my-directive value="123">

you can use $eval if the value is a number or boolean, and you want the correct type:

return function (scope, element, attr) {
   var number = scope.$eval(attr.value);
   console.log(number, number + 1);
});

If the attribute value is a string constant, or you want the value to be string type in your directive, you can access it directly:

return function (scope, element, attr) {
   var str = attr.value;
   console.log(str, str + " more");
});

In your case, however, since you want to support interpolated values and constants, use $observe.

Git: How do I list only local branches?

There's a great answer to a post about how to delete local only branches. In it, the fellow builds a command to list out the local branches:

git branch -vv | cut -c 3- | awk '$3 !~/\[/ { print $1 }'

The answer has a great explanation about how this command was derived, so I would suggest you go and read that post.

What is the difference between Python and IPython?

From my experience I've found that some commands which run in IPython do not run in base Python. For example, pwd and ls don't work alone in base Python. However they will work if prefaced with a % such as: %pwd and %ls.

Also, in IPython, you can run the cd command like: cd C:\Users\... This doesn't seem to work in base python, even when prefaced with a % however.

Decompile an APK, modify it and then recompile it

This is a way:

  1. Using apktool to decode:

     $ apktool d -f {apkfile} -o {output folder}
    
  2. Next, using JADX (at github.com/skylot/jadx)

     $ jadx -d {output folder} {apkfile}
    

2 tools extract and decompiler to same output folder.

Easy way: Using Online APK Decompiler

Tomcat won't stop or restart

Make sure Tomcat is not currently running and the PID file is removed. Them you should start Tomcat successfully.

If you start fresh then:

  1. Create setenv.sh file in <CATALINA_HOME>/bin.
  2. In it I set CATALINA_PID=/tmp/tomcat.pid (or other directory of your choice) so you have more control over the Tomcat process.

Then to start Tomcat find catalina.sh in <CATALINA_HOME>/bin and execute:

./catalina.sh start

and to stop it run:

./catalina.sh stop 10 -force

From catalina.sh script's doc:

./catalina.sh

Usage: catalina.sh ( commands ... )
commands:

start             Start Catalina in a separate window
stop              Stop Catalina, waiting up to 5 seconds for the process to end
stop n            Stop Catalina, waiting up to n seconds for the process to end
stop -force       Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
stop n -force     Stop Catalina, wait up to n seconds and then use kill -KILL if still running

Note: If you want to use -force flag then setting CATALINA_PID is mandatory.

$_SERVER['HTTP_REFERER'] missing

function redirectHome($theMsg, $url = null, $seconds = 3) {
    if ($url === null) {
        $url  = 'index.php';
        $link = 'Homepage';
    } else {
        if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] !== '') {
            $url = $_SERVER['HTTP_REFERER'];
            $link = 'Previous Page';
        } else {
            $url = 'index.php';
            $link = 'Homepage';
        }
    }
    echo $theMsg;
    echo "<div class='alert alert-info'>You Will Be Redirected to $link After $seconds Seconds.</div>";
    header("refresh:$seconds;url=$url");
    exit();
}

bower command not found

This turned out to NOT be a bower problem, though it showed up for me with bower.

It seems to be a node-which problem. If a file is in the path, but has the setuid/setgid bit set, which will not find it.

Here is a files with the s bit set: (unix 'which' will find it with no problems).

ls -al /usr/local/bin -rwxrwsr-- 110 root nmt 5535636 Jul 17 2012 git

Here is a node-which attempt:

> which.sync('git')
Error: not found: git

I change the permissions (chomd 755 git). Now node-which can find it.

> which.sync('git')
'/usr/local/bin/git'

Hope this helps.

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

How can I get Apache gzip compression to work?

Your .htaccess should run just fine; it depends on four different Apache modules (one per each <IfModule> directive). I guess one of the following:

  • your Apache server doesn't have either mod_filter, mod_deflate, mod_headers and/or mod_setenvif modules installed and running. If you can access the server config, please check /etc/apache2/httpd.conf (and the related Apache config files); otherwise, you can see which modules are loaded via phpinfo(), under the apache2handler section (see attached image); (EDIT) OR, you can open a terminal window and issue the command sudo apachectl -M that will list the loaded modules;

  • if you get an http 500 internal server error, your server may not be allowed to use .htaccess files;

  • you are trying to load a PHP file that sends its own headers (overwriting Apache'sheaders), thus "confusing" the browser.

In any case, you should double-check your server config and error logs to see what's going wrong. Just to be sure, try to use the fastest way suggested here in Apache docs:

AddOutputFilterByType DEFLATE text/html text/plain text/xml

and then try to load a large textfile (preferably, clean your cache first).

(EDIT) If the needed modules are there (in the Apache modules dir) but aren't loaded, just edit /etc/apache2/httpd.conf and add a LoadModule directive for each one of them.

If the needed modules aren't there (neither loaded, nor in the Apache modules directory), I fear that the only option is reinstalling Apache (a complete version).

phpinfo() apache2handler section

SQL Insert Multiple Rows

1--> {Simple Insertion when table column sequence is known}
    Insert into Table1
    values(1,2,...)

2--> {Simple insertion mention column}  
    Insert into Table1(col2,col4)
    values(1,2)

3--> {bulk insertion when num of selected collumns of a table(#table2) are equal to Insertion table(Table1) }   
    Insert into Table1 {Column sequence}
    Select * -- column sequence should be same.
       from #table2

4--> {bulk insertion when you want to insert only into desired column of a table(table1)}
    Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
    Select Column1,Column2..desired column from #table2

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

Got it! Solved the issue modifying the user properties in security session of SQL Server. In SQL Server Management, go into security -> Logon -> Choose the user used for DB connection and go into his properties. Go to "Securators" tab and look for line "Connect SQL", mark "Grant" option and take a try. It works for me!

Regards

Find a value in an array of objects in Javascript

function getValue(){
    for(var i = 0 ; i< array.length; i++){
        var obj = array[i];
        var arr = array["types"];
        for(var j = 0; j<arr.length;j++ ){
            if(arr[j] == "value"){
                return obj;
            }
        }

    }
}

Possible heap pollution via varargs parameter

When you declare

public static <T> void foo(List<T>... bar) the compiler converts it to

public static <T> void foo(List<T>[] bar) then to

public static void foo(List[] bar)

The danger then arises that you'll mistakenly assign incorrect values into the list and the compiler will not trigger any error. For example, if T is a String then the following code will compile without error but will fail at runtime:

// First, strip away the array type (arrays allow this kind of upcasting)
Object[] objectArray = bar;

// Next, insert an element with an incorrect type into the array
objectArray[0] = Arrays.asList(new Integer(42));

// Finally, try accessing the original array. A runtime error will occur
// (ClassCastException due to a casting from Integer to String)
T firstElement = bar[0].get(0);

If you reviewed the method to ensure that it doesn't contain such vulnerabilities then you can annotate it with @SafeVarargs to suppress the warning. For interfaces, use @SuppressWarnings("unchecked").

If you get this error message:

Varargs method could cause heap pollution from non-reifiable varargs parameter

and you are sure that your usage is safe then you should use @SuppressWarnings("varargs") instead. See Is @SafeVarargs an appropriate annotation for this method? and https://stackoverflow.com/a/14252221/14731 for a nice explanation of this second kind of error.

References:

How to pass credentials to the Send-MailMessage command for sending emails

PSH> $cred = Get-Credential

PSH> $cred | Export-CliXml c:\temp\cred.clixml

PSH> $cred2 = Import-CliXml c:\temp\cred.clixml

That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.

This code works as expected (I just changed the type from double to String):

public static void main(String[] args) {
  String doubleVal = "1.745";
  String doubleVal1 = "0.745";
  BigDecimal bdTest = new BigDecimal(  doubleVal);
  BigDecimal bdTest1 = new BigDecimal(  doubleVal1 );
  bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
  bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
  System.out.println("bdTest:"+bdTest); //1.75
  System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}

How to get JSON from URL in JavaScript?

Axios is a promise based HTTP client for the browser and node.js.

It offers automatic transforms for JSON data and it's the official recommendation from the Vue.js team when migrating from the 1.0 version which included a REST client by default.

Performing a GET request

// Make a request for a user with a given ID
axios.get('http://query.yahooapis.com/v1/publ...')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Or even just axios(url) is enough as a GET request is the default.

How to keep two folders automatically synchronized?

You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed. If you are looking for the more advanced solution, I would suggest checking Resilio Connect. It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.

How to embed matplotlib in pyqt - for Dummies

It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Edit:

Updated to reflect comments and API changes.

  • NavigationToolbar2QTAgg changed with NavigationToolbar2QT
  • Directly import Figure instead of pyplot
  • Replace deprecated ax.hold(False) with ax.clear()

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

I had the same problem. Mine was due to a third jar, but the logcat did not catch the exception, i solved by update the third jar, hope these will help.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

Bootstrap dropdown not working

FYI: If you have bootstrap.js, you should not add bootstrap-dropdown.js.

I'm unsure of the result with bootstrap.min.js.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

The message you mention is quite clear:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

SLF4J API could not find a binding, and decided to default to a NOP implementation. In your case slf4j-log4j12.jar was somehow not visible when the LoggerFactory class was loaded into memory, which is admittedly very strange. What does "mvn dependency:tree" tell you?

The various dependency declarations may not even be directly at cause here. I strongly suspect that a pre-1.6 version of slf4j-api.jar is being deployed without your knowledge.

enabling cross-origin resource sharing on IIS7

One thing that has not been mentioned in these answers is that if you are using IIS and have sub applications with their own separate web.config, you may need to have a web.config in the parent directory containing the following code.

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
  </customHeaders>
</httpProtocol>

Java random numbers using a seed

If you'd want to generate multiple numbers using one seed you can do something like this:

public double[] GenerateNumbers(long seed, int amount) {
    double[] randomList = new double[amount];
    for (int i=0;i<amount;i++) {
        Random generator = new Random(seed);
        randomList[i] = Math.abs((double) (generator.nextLong() % 0.001) * 10000);
        seed--;
    }
    return randomList;
}

It will display the same list if you use the same seed.

validation of input text field in html using javascript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Validation</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
            var tags = document.getElementsByTagName("input");
            var radiotags = document.getElementsByName("gender");
            var compareValidator = ['compare'];
            var formtag = document.getElementsByTagName("form");
            function validation(){
                for(var i=0;i<tags.length;i++){
                    var tagid = tags[i].id;
                    var tagval = tags[i].value;
                    var tagtit = tags[i].title;
                    var tagclass = tags[i].className;
                    //Validation for Textbox Start
                    if(tags[i].type == "text"){
                        if(tagval == "" || tagval == null){
                            var lbl = $(tags[i]).prev().text();
                            lbl = lbl.replace(/ : /g,'')
                            //alert("Please Enter "+lbl);
                            $(".span"+tagid).remove();
                            $("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
                            $("#"+tagid).focus();
                            //return false;
                        }
                        else if(tagval != "" || tagval != null){
                            $(".span"+tagid).remove();
                        }
                        //Validation for compare text in two text boxes Start
                        //put two tags with same class name and put class name in compareValidator.
                        for(var j=0;j<compareValidator.length;j++){
                            if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
                                if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
                                    $("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
                                    $("span").prev("span").remove();
                                    $("."+compareValidator[j]+":last").focus();
                                    //return false;
                                }
                            }
                        }
                        //Validation for compare text in two text boxes End
                        //Validation for Email Start
                        if((tagval != "") && (tagclass.indexOf('email') != -1)){
                        //enter class = email where you want to use email validator
                            var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
                            if (reg.test(tagval)){
                                $(".span"+tagid).remove();
                                return true; 
                            }
                            else{
                                $(".span"+tagid).remove();
                                $("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
                                $("#"+tagid).focus();
                                return false;
                            }
                        }
                        //Validation for Email End
                    }
                    //Validation for Textbox End
                    //Validation for Radio Start
                    else if(tags[i].type == "radio"){
                    //enter class = gender where you want to use gender validator
                        if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
                            $(".span"+tagid).remove();
                            //$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
                            $(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
                            $("#"+tagid).focus();
                            i += 1;
                        }
                        else{
                            $(".span"+tagid).remove();
                        }
                    }
                    //Validation for Radio End              
                    else{

                    }
                }
                //return false;
            }
            function Validate(){
               if(!validation()){
                    return false;
                }
                return true;
            }
            function onloadevents(){
                tags[tags.length -1].onclick = function(){
                    //return Validate();
                }
                for(var j=0;j<formtag.length;j++){
                    formtag[j].onsubmit = function(){
                        return Validate();
                    }
                }
                for(var i=0;i<tags.length;i++){
                    var tagid = tags[i].id;
                    var tagval = tags[i].value;
                    var tagtit = tags[i].title;
                    var tagclass = tags[i].className;
                    if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
                        //enter class = numeric where you want to use numeric validator
                        document.getElementById(tagid).onkeypress = function(){
                            numeric(event);
                        }
                    }
                }
            }
            function numeric(event){
                var KeyBoardCode = (event.which) ? event.which : event.keyCode; 
                if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
                    event.preventDefault();
                    $(".spannum").remove();
                    //$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
                    //$(".numeric").focus();
                    return false;
                }
                    $(".spannum").remove();
                    return true;
            }
            if (document.addEventListener) {
              document.addEventListener("DOMContentLoaded", onloadevents, false);
            }
            //window.onload = onloadevents;
        </script>
    </head>
    <body>
        <form method="post">
            <label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
            <label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
            <label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
            <label for="gender">Gender : </label>
            <input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
            <input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
            <label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
            <label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
            <input type="submit" id="sub" value="Submit">
        </form>
    </body>
</html>

count number of lines in terminal output

Putting the comment of EaterOfCode here as an answer.

grep itself also has the -c flag which just returns the count

So the command and output could look like this.

$ grep -Rl "curl" ./ -c
24

EDIT:

Although this answer might be shorter and thus might seem better than the accepted answer (that is using wc). I do not agree with this anymore. I feel like remembering that you can count lines by piping to wc -l is much more useful as you can use it with other programs than grep as well.

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

How to Iterate over a Set/HashSet without an Iterator?

Enumeration(?):

Enumeration e = new Vector(set).elements();
while (e.hasMoreElements())
    {
        System.out.println(e.nextElement());
    }

Another way (java.util.Collections.enumeration()):

for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
    {
        System.out.println(e1.nextElement());
    }

Java 8:

set.forEach(element -> System.out.println(element));

or

set.stream().forEach((elem) -> {
    System.out.println(elem);
});

How to concatenate items in a list to a single string?

This will help for sure -

arr=['a','b','h','i']     # let this be the list
s=""                      # creating a empty string
for i in arr:
   s+=i                   # to form string without using any function
print(s) 


       

Fastest way to count number of occurrences in a Python list

By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.

If our python list is:-

l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']

To find occurrence of every items in the python list use following:-

\>>from collections import Counter

\>>c=Counter(l)

\>>print c

Counter({'1': 6, '2': 4, '7': 3, '10': 2})

To find most/highest occurrence of items in the python list:-

\>>k=c.most_common()

\>>k

[('1', 6), ('2', 4), ('7', 3), ('10', 2)]

For Highest one:-

\>>k[0][1]

6

For the item just use k[0][0]

\>>k[0][0]

'1'

For nth highest item and its no of occurrence in the list use follow:-

**for n=2 **

\>>print k[n-1][0] # For item

2

\>>print k[n-1][1] # For value

4

ASP.Net 2012 Unobtrusive Validation with jQuery

I suggest to instead this lines

<div>
    <asp:TextBox runat="server" ID="username" />
    <asp:RequiredFieldValidator ErrorMessage="The username is required" ControlToValidate="username" runat="server" Text=" - Required" />
</div>

by this line

<div>
    <asp:TextBox runat="server" ID="username" required />
</div>

Git error: src refspec master does not match any error: failed to push some refs

One classic root cause for this message is:

  • when the repo has been initialized (git init lis4368/assignments),
  • but no commit has ever been made

Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

Try first to create a commit:

  • either by adding (git add .) then git commit -m "first commit"
    (assuming you have the right files in place to add to the index)
  • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

And then try git push -u origin master again.

See "Why do I need to explicitly push a new branch?" for more.

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

You are getting close!

# Find all of the text between paragraph tags and strip out the html
page = soup.find('p').getText()

Using find (as you've noticed) stops after finding one result. You need find_all if you want all the paragraphs. If the pages are formatted consistently ( just looked over one), you could also use something like

soup.find('div',{'id':'ctl00_PlaceHolderMain_RichHtmlField1__ControlWrapper_RichHtmlField'})

to zero in on the body of the article.

Loading and parsing a JSON file with multiple JSON objects

That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [ and ends with ] with a comma at the end of each line, or parse it line by line as separate dictionaries.

How to print spaces in Python?

this is how to print whitespaces in python.

import string  
string.whitespace  
'\t\n\x0b\x0c\r '   
i.e .   
print "hello world"   
print "Hello%sworld"%' '   
print "hello", "world"   
print "Hello "+"world   

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

Returning a value even if no result

MySQL has a function to return a value if the result is null. You can use it on a whole query:

SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123 LIMIT 1) ,'not found');

Reload content in modal (twitter bootstrap)

Here is a coffeescript version that worked for me.

$(document).on 'hidden.bs.modal', (e) ->
  target = $(e.target)
  target.removeData('bs.modal').find(".modal-content").html('')

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;
}
System.out.println(sum);

// while loop

sum = 0;
int j = 1;

while(j<=100){
    sum = sum + j;
    j++;
}

System.out.println(sum);

// do while loop

sum = 0;
j = 1;

do{
    sum = sum + j;
    j++;
}
while(j<=100);

System.out.println(sum);

In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

Confused about __str__ on list in Python

__str__ is only called when a string representation is required of an object.

For example str(uno), print "%s" % uno or print uno

However, there is another magic method called __repr__ this is the representation of an object. When you don't explicitly convert the object to a string, then the representation is used.

If you do this uno.neighbors.append([[str(due),4],[str(tri),5]]) it will do what you expect.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

How to detect iPhone 5 (widescreen devices)?

Here is our codes, test passed on ios7/ios8 for iphone4,iphone5,ipad,iphone6,iphone6p, no matter on devices or simulator:

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) // iPhone and       iPod touch style UI

#define IS_IPHONE_5_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f)
#define IS_IPHONE_6_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0f)
#define IS_IPHONE_6P_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height < 568.0f)

#define IS_IPHONE_5_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 568.0f)
#define IS_IPHONE_6_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 667.0f)
#define IS_IPHONE_6P_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) < 568.0f)

#define IS_IPHONE_5 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_5_IOS8 : IS_IPHONE_5_IOS7 )
#define IS_IPHONE_6 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6_IOS8 : IS_IPHONE_6_IOS7 )
#define IS_IPHONE_6P ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6P_IOS8 : IS_IPHONE_6P_IOS7 )
#define IS_IPHONE_4_AND_OLDER ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_4_AND_OLDER_IOS8 : IS_IPHONE_4_AND_OLDER_IOS7 )

How to fix "unable to write 'random state' " in openssl

It may also be that you need to run the console as an administrator. On windows 7, hold ctrl+shift when you launch the console window.

Is Safari on iOS 6 caching $.ajax results?

A quick work-around for GWT-RPC services is to add this to all the remote methods:

getThreadLocalResponse().setHeader("Cache-Control", "no-cache");

How to ignore the certificate check when ssl

For anyone interested in applying this solution on a per request basis, this is an option and uses a Lambda expression. The same Lambda expression can be applied to the global filter mentioned by blak3r as well. This method appears to require .NET 4.5.

String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

In .NET 4.0, the Lambda Expression can be applied to the global filter as such

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

How to dynamically change header based on AngularJS partial view?

Mr Hash had the best answer so far, but the solution below makes it ideal (for me) by adding the following benefits:

  • Adds no watches, which can slow things down
  • Actually automates what I might have done in the controller, yet
  • Still gives me access from the controller if I still want it.
  • No extra injecting

In the router:

  .when '/proposals',
    title: 'Proposals',
    templateUrl: 'proposals/index.html'
    controller: 'ProposalListCtrl'
    resolve:
      pageTitle: [ '$rootScope', '$route', ($rootScope, $route) ->
        $rootScope.page.setTitle($route.current.params.filter + ' ' + $route.current.title)
      ]

In the run block:

.run(['$rootScope', ($rootScope) ->
  $rootScope.page =
    prefix: ''
    body: ' | ' + 'Online Group Consensus Tool'
    brand: ' | ' + 'Spokenvote'
    setTitle: (prefix, body) ->
      @prefix = if prefix then ' ' + prefix.charAt(0).toUpperCase() + prefix.substring(1) else @prifix
      @body = if body then ' | ' + body.charAt(0).toUpperCase() + body.substring(1) else @body
      @title = @prefix + @body + @brand
])

Processing $http response in service

As far as caching the response in service is concerned , here's another version that seems more straight forward than what I've seen so far:

App.factory('dataStorage', function($http) {
     var dataStorage;//storage for cache

     return (function() {
         // if dataStorage exists returned cached version
        return dataStorage = dataStorage || $http({
      url: 'your.json',
      method: 'GET',
      cache: true
    }).then(function (response) {

              console.log('if storage don\'t exist : ' + response);

              return response;
            });

    })();

});

this service will return either the cached data or $http.get;

 dataStorage.then(function(data) {
     $scope.data = data;
 },function(e){
    console.log('err: ' + e);
 });