Programs & Examples On #Binaryreader

In .net is a class used to read binary values. In general, it is a class or a program to read and manipulate binary data.

How to convert byte array to string

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);

Cancel a vanilla ECMAScript 6 Promise chain

Try promise-abortable: https://www.npmjs.com/package/promise-abortable

$ npm install promise-abortable
import AbortablePromise from "promise-abortable";

const timeout = new AbortablePromise((resolve, reject, signal) => {
  setTimeout(reject, timeToLive, error);
  signal.onabort = resolve;
});

Promise.resolve(fn()).then(() => {
  timeout.abort();
});

SQL- Ignore case while searching for a string

Use something like this -

SELECT DISTINCT COL_NAME FROM myTable WHERE UPPER(COL_NAME) LIKE UPPER('%PriceOrder%')

or

SELECT DISTINCT COL_NAME FROM myTable WHERE LOWER(COL_NAME) LIKE LOWER('%PriceOrder%')

How to import load a .sql or .csv file into SQLite?

SQLite is extremely flexible as it also allows the SQLite specific dot commands in the SQL syntax, (although they are interpreted by CLI.) This means that you can do things like this.

Create a sms table like this:

# sqlite3 mycool.db '.schema sms'
CREATE TABLE sms (_id integer primary key autoincrement, Address VARCHAR, Display VARCHAR, Class VARCHAR, ServiceCtr VARCHAR, Message VARCHAR, Timestamp TIMESTAMP NOT NULL DEFAULT current_timestamp);

Then two files:

# echo "1,ADREZZ,DizzPlay,CLAZZ,SMSC,DaTestMessage,2015-01-24 21:00:00">test.csv

# cat test.sql
.mode csv
.header on
.import test.csv sms

To test the import of the CSV file using the SQL file, run:

# sqlite3 -csv -header mycool.db '.read test.sql'

In conclusion, this means that you can use the .import statement in SQLite SQL, just as you can do in any other RDB, like MySQL with LOAD DATA INFILE etc. However, this is not recommended.

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

css 100% width div not taking up full width of parent

html, body{ 
  width:100%;
}

This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.

You may want to set a min width instead.

html, body{ 
  min-width:100%;
}

So it will be 100% as a minimum, bot more if needed.

npm ERR! network getaddrinfo ENOTFOUND

Well, everybody giving their answer so I thought I write too.

I am having the same proxy issue as all others. To solve this I tried many solutions but it did not work.

Search .npmrc file name in C:\Users\your_username drive and than add this line:

http://proxy.company.com:8888

enter image description here

I did only this and my is solved.

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

A bit too late but I got the same issue and fixed it switching schemalocation into schemaLocation in the persistence.xml file (line 1).

Java Strings: "String s = new String("silly");"

I would just add that Java has Copy constructors...

Well, that's an ordinary constructor with an object of same type as argument.

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

How does the bitwise complement operator (~ tilde) work?

Basically action is a complement not a negation .

Here x= ~x produce results -(x+1) always .

x = ~2

-(2+1)

-3

Commit empty folder structure (with git)

Just add a file .gitkeep in every folder you want committed.

On windows do so by right clicking when in the folder and select: Git bash from here. Then type: touch .gitkeep

Rendering HTML in a WebView with custom CSS

I assume that your style-sheet "style.css" is already located in the assets-folder

  1. load the web-page with jsoup:

    doc = Jsoup.connect("http://....").get();
    
  2. remove links to external style-sheets:

    // remove links to external style-sheets
    doc.head().getElementsByTag("link").remove();
    
  3. set link to local style-sheet:

    // set link to local stylesheet
    // <link rel="stylesheet" type="text/css" href="style.css" />
    doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
    
  4. make string from jsoup-doc/web-page:

    String htmldata = doc.outerHtml();
    
  5. display web-page in webview:

    WebView webview = new WebView(this);
    setContentView(webview);
    webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
    

using favicon with css

There is no explicit way to change the favicon globally using CSS that I know of. But you can use a simple trick to change it on the fly.

First just name, or rename, the favicon to "favicon.ico" or something similar that will be easy to remember, or is relevant for the site you're working on. Then add the link to the favicon in the head as you usually would. Then when you drop in a new favicon just make sure it's in the same directory as the old one, and that it has the same name, and there you go!

It's not a very elegant solution, and it requires some effort. But dropping in a new favicon in one place is far easier than doing a find and replace of all the links, or worse, changing them manually. At least this way doesn't involve messing with the code.

Of course dropping in a new favicon with the same name will delete the old one, so make sure to backup the old favicon in case of disaster, or if you ever want to go back to the old design.

Flutter Countdown Timer

Countdown timer in one line

CountdownTimer(Duration(seconds: 5), Duration(seconds: 1)).listen((data){
})..onData((data){
  print('data $data');
})..onDone((){
  print('onDone.........');
});

SQL: IF clause within WHERE clause

To clarify some of the logical equivalence solutions.

An if statement

if (a) then b

is logically equivalent to

(!a || b)

It's the first line on the Logical equivalences involving conditional statements section of the Logical equivalence wikipedia article.

To include the else, all you would do is add another conditional

if(a) then b; 
if(!a) then c;

which is logically equivalent to (!a || b) && (a || c)

So using the OP as an example:

IF IsNumeric(@OrderNumber) = 1
    OrderNumber = @OrderNumber
ELSE
    OrderNumber LIKE '%' + @OrderNumber + '%'

the logical equivalent would be:

(IsNumeric(@OrderNumber) <> 1 OR OrderNumber = @OrderNumber)
AND (IsNumeric(@OrderNumber) = 1 OR OrderNumber LIKE '%' + @OrderNumber + '%' )

Getting results between two dates in PostgreSQL

 SELECT *
   FROM mytable
  WHERE (start_date, end_date) OVERLAPS ('2012-01-01'::DATE, '2012-04-12'::DATE);

Datetime functions is the relevant section in the docs.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

check your image cmd using the command docker inspect image_name . The output might be like this:

"Cmd": [
    "/bin/bash",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/bash\"]"
],

So use the command docker exec -it container_id /bin/bash. If your cmd output is different like this:

"Cmd": [
    "/bin/sh",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/sh\"]"
],

Use /bin/sh instead of /bin/bash in the command above.

Type List vs type ArrayList in Java

Out of the following two:

(1) List<?> myList = new ArrayList<?>();
(2) ArrayList<?> myList = new ArrayList<?>();

First is generally preferred. As you will be using methods from List interface only, it provides you the freedom to use some other implementation of List e.g. LinkedList in future. So it decouples you from specific implementation. Now there are two points worth mentioning:

  1. We should always program to interface. More here.
  2. You will almost always end up using ArrayList over LinkedList. More here.

I am wondering if anyone uses (2)

Yes sometimes (read rarely). When we need methods that are part of implementation of ArrayList but not part of the interface List. For example ensureCapacity.

Also, how often (and can I please get an example) does the situation actually require using (1) over (2)

Almost always you prefer option (1). This is a classical design pattern in OOP where you always try to decouple your code from specific implementation and program to the interface.

can't start MySql in Mac OS 10.6 Snow Leopard

open Terminal

cd /usr/local/mysql/support-files
sudo nano mysql.server

Find the lines:

basedir=
datadir=

change them to

basedir=/usr/local/mysql
datadir=/usr/local/mysql/data

How to create an object property from a variable value in JavaScript?

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.

Example #1:

(function(o,a,b){return o[a]=b,o})({},'key','val');

Example: #2:

var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');

As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).

Result #1: { key: 'val' }

Result #2: { foo: 'bar', key: 'val' }

How to prove that a problem is NP complete?

  1. Get familiar to a subset of NP Complete problems
  2. Prove NP Hardness : Reduce an arbitrary instance of an NP complete problem to an instance of your problem. This is the biggest piece of a pie and where the familiarity with NP Complete problems pays. The reduction will be more or less difficult depending on the NP Complete problem you choose.
  3. Prove that your problem is in NP : design an algorithm which can verify in polynomial time whether an instance is a solution.

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For me it was missing MySQL PDO, I recompiled my PHP with the --with-pdo-mysql option, installed it and restarted apache and it was all working

'Java' is not recognized as an internal or external command

Search environment variables. enter image description here

open the "edit the system environment variables". then click on "environment variables". enter image description here

Under "User variables" click on "Path" then "Edit". enter image description here

Find your Java path and click "Edit". enter image description here

then paste the path of your java installation folder. Mostly you can find it on a path similar to this. C:\Program Files\Java\jdk-12.0.2\bin

Then click OK. now in the start menu, type cmd. open the command prompt. type java -version If you did it right,it should show something like this. enter image description here

Using Address Instead Of Longitude And Latitude With Google Maps API

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
  zoom: 8,
  center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == 'OK') {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
    });
  } else {
    alert('Geocode was not successful for the following reason: ' + status);
  }
});
}

<body onload="initialize()">
 <div id="map" style="width: 320px; height: 480px;"></div>
 <div>
   <input id="address" type="textbox" value="Sydney, NSW">
   <input type="button" value="Encode" onclick="codeAddress()">
 </div>
</body>

Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding

html form - make inputs appear on the same line

You can make a class for each label and inside it put:

display: inline-block;

And width the value that you need.

Pretty graphs and charts in Python

You can also use pygooglechart, which uses the Google Chart API. This isn't something you'd always want to use, but if you want a small number of good, simple, charts, and are always online, and especially if you're displaying in a browser anyway, it's a good choice.

How can I conditionally import an ES6 module?

require() is a way to import some module on the run time and it equally qualifies for static analysis like import if used with string literal paths. This is required by bundler to pick dependencies for the bundle.

const defaultOne = require('path/to/component').default;
const NamedOne = require('path/to/component').theName;

For dynamic module resolution with complete static analysis support, first index modules in an indexer(index.js) and import indexer in host module.

// index.js
export { default as ModuleOne } from 'path/to/module/one';
export { default as ModuleTwo } from 'path/to/module/two';
export { SomeNamedModule } from 'path/to/named/module';

// host.js
import * as indexer from 'index';
const moduleName = 'ModuleOne';
const Module = require(indexer[moduleName]);

No == operator found while comparing structs in C++

By default structs do not have a == operator. You'll have to write your own implementation:

bool MyStruct1::operator==(const MyStruct1 &other) const {
    ...  // Compare the values, and return a bool result.
  }

Finding which process was killed by Linux OOM killer

Try this out:

grep -i 'killed process' /var/log/messages

Installing RubyGems in Windows

Check that ruby interpreter is already installed and try "ruby setup.rb" in command prompt.

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

You can use this package for get all the queries which are executing when you load your page

https://github.com/barryvdh/laravel-debugbar

Find something in column A then show the value of B for that row in Excel 2010

I figured out such data design:

Main sheet: Column A: Pump codes (numbers)

Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'

=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)

Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.

Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B

=INDIRECT("Ruhrpumpen!A"&$B2)

Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:

=INDIRECT("Ruhrpumpen!B"&$B2)

Sheet 'Ruhrpumpen':

Column A: some data about a certain pump

Column B: some more data

Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.

Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls

Hard reset of a single file

You can use the following command:

git checkout filename

If you have a branch with the same file name you have to use this command:

git checkout -- filename

handling DATETIME values 0000-00-00 00:00:00 in JDBC

you can append the jdbc url with

?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

With the help of this, sql convert '0000-00-00 00:00:00' as null value.

eg:

jdbc:mysql:<host-name>/<db-name>?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

Permission denied when launch python script via bash

Okay, so first of all check if you are in the correct directory where your python script is located.
On the net, they say to run the command :

python3 your_file_name.py

But it doesn't work.
What worked for me however was:

python -u my_file_name.py

Java 8 Filter Array Using Lambda

Yes, you can do this by creating a DoubleStream from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:

double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]

If you want to filter a reference array that is not an Object[] you will need to use the toArray method which takes an IntFunction to get an array of the original type as the result:

String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

How to do a PUT request with curl?

An example PUT following Martin C. Martin's comment:

curl -T filename.txt http://www.example.com/dir/

With -T (same as --upload-file) curl will use PUT for HTTP.

Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.

Get real path from URI, Android KitKat new storage access framework

the answer below is written by https://stackoverflow.com/users/3082682/cvizv on a page which does not exist anymore, since he has not enough rep to answer a question, I am posting it. No credits by me.

public String getImagePath(Uri uri){
   Cursor cursor = getContentResolver().query(uri, null, null, null, null);
   cursor.moveToFirst();
   String document_id = cursor.getString(0);
   document_id = document_id.substring(document_id.lastIndexOf(":")+1);
   cursor.close();

   cursor = getContentResolver().query( 
   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
   null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
   cursor.moveToFirst();
   String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
   cursor.close();

   return path;
}

Edit: There is a flow on the code; if device has more than one external storage (external sdcard, external usb etc.), above the code won't work non primary storages.

Is a view faster than a simple query?

Against all expectation, views are way slower in some circumstances.

I discovered this recently when I had problems with data which was pulled from Oracle which needed to be massaged into another format. Maybe 20k source rows. A small table. To do this we imported the oracle data as unchanged as I could into a table and then used views to extract data. We had secondary views based on those views. Maybe 3-4 levels of views.

One of the final queries, which extracted maybe 200 rows would take upwards of 45 minutes! That query was based on a cascade of views. Maybe 3-4 levels deep.

I could take each of the views in question, insert its sql into one nested query, and execute it in a couple of seconds.

We even found that we could even write each view into a temp table and query that in place of the view and it was still way faster than simply using nested views.

What was even odder was that performance was fine until we hit some limit of source rows being pulled into the database, performs just dropped off a cliff over the space of a couple of days - a few more source rows was all it took.

So, using queries which pull from views which pull from views is much slower than a nested query - which makes no sense for me.

How do I POST urlencoded form data with $http without jQuery?

URL-encoding variables using only AngularJS services

With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:

  1. $httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)

  2. $httpParamSerializer - a serializer used by Angular itself for GET requests

Example usage

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).then(function(response) { /* do something here */ });

See a more verbose Plunker demo


How are $httpParamSerializerJQLike and $httpParamSerializer different

In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.

For example (ignoring percent encoding of brackets):

Encoding an array

{sites:['google', 'Facebook']} // Object with array property

sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike

sites=google&sites=facebook // Result with $httpParamSerializer

Encoding an object

{address: {city: 'LA', country: 'USA'}} // Object with object property

address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike

address={"city": "LA", country: "USA"} // Result with $httpParamSerializer

Converting String to Cstring in C++

string name;
char *c_string;

getline(cin, name);

c_string = new char[name.length()];

for (int index = 0; index < name.length(); index++){
    c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
                              // the char array

I know this is not the predefined method but thought it may be useful to someone nevertheless.

How to remove a web site from google analytics

UPDATED ANSWER

Google Analytics Admin panel has 3 panels, wherein deleting can be done on any of the following :

  1. Account (Contains multiple properties, and views)
  2. Properties (Contains Views, a subset of Account)
  3. Views (subset of properties)

Google Analytics Admin Panel


Deleting an Account

Deleting the account, will remove all data pertaining to that account, along with all properties/profiles it contains. This is (usually) as good as removing the entire website data.

To delete the account, follow the following steps : (refer to image below)

  • Choose the account you want to delete.

Choose the account you want to delete

  • Click on Account Settings

Click Account Settings

  • Bottom right, a small link that says delete this account.

Delete account

  • You will get a confirmation, if you are sure to, click Delete Account
  • It will give you details, and will confirm deletion (and provide additional info like to remove GA snippet on your website, etc)

Note : If you have multiple accounts linked with your login, the other accounts are NOT touched, only this account will be deleted.


Deleting a property

Deleting a property will remove the selected property, and all the views it holds. To delete a property, delete all views it contains individually (see below for deleting views)

  • Choose the property

Property choice

  • All profiles related to that property appear on the right
  • Delete all the views related to the property individually (details in next section).

Deleting a View (profile)

Deleting a profile will remove only data pertaining to that view, if there is a single profile, the property is automatically deleted.

  • Choose the profile you want to delete

Choose profile

  • Click View Settings

Settings

  • Click on delete View (Bottom right)

Delete the view

  • Click Confirm, and that view will be deleted. If there is only a single view in the property, that property gets automatically deleted.

I want to keep the data, but not see them in the list

Sometimes you have a lot of websites, which you want to keep the data, but remove them from the list, since you don't view them often. I thought of a workaround, in case you do not want to delete the data.

Use another account.

  1. Say, your primary account is A, and you make another account B.
  2. Make B an administrator from A
  3. Remove A

Since A was your primary account, you no longer will be able to access it from the list!
And you still have your data saved, just that you'll have to log in via the other (spare) account.


Previous Answer :

These are the steps to delete a profile from Google Support page :

Delete profiles

Remember, too, that when you delete a profile, you also delete all data associated with that profile, and it is not possible to retrieve that deleted data.

To delete a profile:

  1. Click the Admin tab at the top right of any Analytics page.
  2. Click the account that contains the profile you want to delete.
  3. Click the web property from which you want to delete the profile.
  4. Use the Profile menu to select the profile.
  5. Click the Profile Settings tab.
  6. Click Delete this profile at the bottom of the page.
  7. Click Delete in the confirmation message.

How to download a branch with git?

git checkout -b branch/name

git pull origin branch/name

Absolute and Flexbox in React Native

This solution worked for me:

tabBarOptions: {
      showIcon: true,
      showLabel: false,
      style: {
        backgroundColor: '#000',
        borderTopLeftRadius: 40,
        borderTopRightRadius: 40,
        position: 'relative',
        zIndex: 2,
        marginTop: -48
      }
  }

Easiest way to convert month name to month number in JS ? (Jan = 01)

var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

then just call monthNames[1] that will be Feb

So you can always make something like

  monthNumber = "5";
  jQuery('#element').text(monthNames[monthNumber])

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Here is some weak adobe documentation on different flash 9 wmode settings.

A note of caution on wmode transparent is here in the adobe bug trac.

And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.

How to linebreak an svg text within javascript?

I have adapted a bit the solution by @steco, switching the dependency from d3 to jquery and adding the height of the text element as parameter

function wrap(text, width, height) {
  text.each(function(idx,elem) {
    var text = $(elem);
    text.attr("dy",height);
        var words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat( text.attr("dy") ),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (elem.getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

OrderBy descending in Lambda expression?

Try this:

List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);

foreach (var item in list.OrderByDescending(x => x))
{
    Console.WriteLine(item);                
}

How to use class from other files in C# with visual studio?

It would be more beneficial for us if we could see the actual project structure, as the classes alone do not say that much.

Assuming that both .cs files are in the same project (if they are in different projects inside the same solution, you'd have to add a reference to the project containing Class2.cs), you can click on the Class2 occurrence in your code that is underlined in red and press CTRL + . (period) or click on the blue bar that should be there. The first option appearing will then add the appropriate using statement automatically. If there is no such menu, it may indicate that there is something wrong with the project structure or a reference missing.

You could try making Class2 public, but it sounds like this can't be a problem here, since by default what you did is internal class Class2 and thus Class2 should be accessible if both are living in the same project/assembly. If you are referencing a different assembly or project wherein Class2 is contained, you have to make it public in order to access it, as internal classes can't be accessed from outside their assembly.

As for renaming: You can click Program.cs in the Solution Explorer and press F2 to rename it. It will then open up a dialog window asking you if the class Program itself and all references thereof should be renamed as well, which is usually what you want. Or you could just rename the class Program in the declaration and again open up the menu with the small blue bar (or, again, CTRL+.) and do the same, but it won't automatically rename the actual file accordingly.

Edit after your question edit: I have never used this option you used, but from quick checking I think that it's really not inside the same project then. Do the following when adding new classes to a project: In the Solution Explorer, right click the project you created and select [Add] -> [Class] or [Add] -> [New Item...] and then select 'Class'. This will automatically make the new class part of the project and thus the assembly (the assembly is basically the 'end product' after building the project). For me, there is also the shortcut Alt+Shift+C working to create a new class.

Re-assign host access permission to MySQL user

For reference, the solution is:

UPDATE mysql.user SET host = '10.0.0.%' WHERE host = 'internalfoo' AND user != 'root';
UPDATE mysql.db SET host = '10.0.0.%' WHERE host = 'internalfoo' AND user != 'root';
FLUSH PRIVILEGES;

How to log a method's execution time exactly in milliseconds?

For fine-grained timing on OS X, you should use mach_absolute_time( ) declared in <mach/mach_time.h>:

#include <mach/mach_time.h>
#include <stdint.h>

// Do some stuff to setup for timing
const uint64_t startTime = mach_absolute_time();
// Do some stuff that you want to time
const uint64_t endTime = mach_absolute_time();

// Time elapsed in Mach time units.
const uint64_t elapsedMTU = endTime - startTime;

// Get information for converting from MTU to nanoseconds
mach_timebase_info_data_t info;
if (mach_timebase_info(&info))
   handleErrorConditionIfYoureBeingCareful();

// Get elapsed time in nanoseconds:
const double elapsedNS = (double)elapsedMTU * (double)info.numer / (double)info.denom;

Of course the usual caveats about fine-grained measurements apply; you're probably best off invoking the routine under test many times, and averaging/taking a minimum/some other form of processing.

Additionally, please note that you may find it more useful to profile your application running using a tool like Shark. This won't give you exact timing information, but it will tell you what percentage of the application's time is being spent where, which is often more useful (but not always).

What is a PDB file?

PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.

This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb files. So effectively pdb files are really a boon to developers while debugging a program.

Generally it is not recommended to exclude the generation of *.pdb files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.

If you still want to disable generation of *.pdb files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none from "Debug Info" drop-down box -> press OK as shown in the snapshot below.

None Debug Info setting for a C# Project

Note: This setting will have to be done separately for "Debug" and "Release" build configurations.

PHP: How to remove specific element from an array?

Use array_search to get the key and remove it with unset if found:

if (($key = array_search('strawberry', $array)) !== false) {
    unset($array[$key]);
}

array_search returns false (null until PHP 4.2.0) if no item has been found.

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}

List<T> or IList<T>

If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change.

If you are just using it internally, you may not care so much, and using List<T> may be ok.

Batch Renaming of Files in a Directory

Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/

I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.

This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.

The program's source code is also available.

LINQ - Left Join, Group By, and Count

While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.

Here's my solution:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }

Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)

How to export a Vagrant virtual machine to transfer it

None of the above answers worked for me. I have been 2 days working out the way to migrate a Vagrant + VirtualBox Machine from a computer to another... It's possible!

First, you need to understand that the virtual machine is separated from your sync / shared folder. So when you pack your machine you're packing it without your files, but with the databases.

What you need to do:

1- Open the CMD of your computer 1 host machine (Command line. Open it as Adminitrator with the right button -> "Run as administrator") and go to your vagrant installed files. On my case: C:/VVV You will see your Vagrantfile an also these folders:

/config/
/database/
/log/
/provision/
/www/
Vagrantfile
...

The /www/ folder is where I have my Sync Folder with my development domains. You may have your sync folder in other place, just be sure to understand what you are doing. Also /config and /database are sync folders.

2- run this command: vagrant package --vagrantfile Vagrantfile

(This command does a package of your virtual machine using you Vagrantfile configuration.)

Here's what you can read on the Vagrant documentation about the command:

A common misconception is that the --vagrantfile option will package a Vagrantfile that is used when vagrant init is used with this box. This is not the case. Instead, a Vagrantfile is loaded and read as part of the Vagrant load process when the box is used. For more information, read about the Vagrantfile load order.

https://www.vagrantup.com/docs/cli/package.html

When finnished, you will have a package.box file.

3- Copy all these files (/config, /database, Vagrantfile, package.box, etc.) and paste them on your Computer 2 just where you want to install your virtual machine (on my case D:/VVV).

Now you have a copy of everything you need on your computer 2 host.

4- run this: vagrant box add package.box --name VVV

(The --name is used to name your virtual machine. On my case it's named VVV) (You can use --force if you already have a virtual machine with this name and want to overwrite it. (Use carefully !))

This will unpack your new vagrant Virtual machine.

5- When finnished, run: vagrant up

The machine will install and you should see it on the "Oracle virtual machine box manager". If you cannot see the virtual machine, try running the Oracle VM box as administrator (right click -> Run as administrator)

You now may have everything ok but remember to see if your hosts are as you expected:

c:/windows/system32/hosts

6- Maybe it's a good idea to copy your host file from your Computer 1 to your Computer 2. Or copy the lines you need. In my case these are the hosts I need:

192.168.50.4 test.dev
192.168.50.4 vvv.dev
...

Where the 192.168.50.4 is the IP of my Virtual machine and test.dev and vvv.dev are developing hosts.

I hope this can help you :) I'll be happy if you feedback your go.

Some particularities of my case that you may find:

When I ran vagrant up, there was a problem with mysql, it wasn't working. I had to run on the Virtual server (right click on the oracle virtual machine -> Show console): apt-get install mysql-server

After this, I ran again vagrant up and everything was working but without data on the databases. So I did a mysqldump all-tables from the Computer 1 and upload them to Computer 2.

OTHER NOTES: My virtual machine is not exactly on Computer 1 and Computer 2. For example, I made some time ago internal configuration to use NFS (to speed up the server sync folders) and I needed to run again this command on the Computer 2 host: vagrant plugin install vagrant-winnfsd

How to write to a file in Scala?

This is one of the features missing from standard Scala that I have found so useful that I add it to my personal library. (You probably should have a personal library, too.) The code goes like so:

def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
  val p = new java.io.PrintWriter(f)
  try { op(p) } finally { p.close() }
}

and it's used like this:

import java.io._
val data = Array("Five","strings","in","a","file!")
printToFile(new File("example.txt")) { p =>
  data.foreach(p.println)
}

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

Display UIViewController as Popup in iPhone

You can do this in Interface Builder.

  • For the view you wish to present modally set its outermost view background to transparent
  • Control + click and drag from the host view controller to the modal view controller
  • Select present modally
  • Click on the newly created segue and in the Attribute Inspector (on the right) set "Presentation" to "Over Current Context"

Bundler: Command not found

I think bundle executable is on :

/opt/ruby-enterprise-1.8.7-2010.02/lib/ruby/gems/1.8/gems/bin and it's not in your $PATH

How to un-commit last un-pushed git commit without losing the changes

2020 simple way :

git reset <commit_hash>

Commit hash of the last commit you want to keep.

Visual Studio breakpoints not being hit

In my case the actual process was different from the original started process.

Usually we bind the local-hosted services through the w3wp.exe process. In my case a custom process was used. Changing to that solved the problem.

One more thing, change from Release to Debug mode. In release mode PDB files are not getting updated with breakpoints details. So make sure you are debugging your application in Debug mode.

Hashset vs Treeset

1.HashSet allows null object.

2.TreeSet will not allow null object. If you try to add null value it will throw a NullPointerException.

3.HashSet is much faster than TreeSet.

e.g.

 TreeSet<String> ts = new TreeSet<String>();
 ts.add(null); // throws NullPointerException

 HashSet<String> hs = new HashSet<String>();
 hs.add(null); // runs fine

MySQL - how to front pad zip code with "0"?

LPAD works with VARCHAR2 as it does not put spaces for left over bytes. LPAD changes leftover/null bytes to zeros on LHS SO datatype should be VARCHAR2

How to load/reference a file as a File instance from the classpath

Try getting hold of a URL for your classpath resource:

URL url = this.getClass().getResource("/com/path/to/file.txt")

Then create a file using the constructor that accepts a URI:

File file = new File(url.toURI());

Copy file or directories recursively in Python

The python shutil.copytree method its a mess. I've done one that works correctly:

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)
    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

How to add the JDBC mysql driver to an Eclipse project?

Try to insert this:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

before getting the JDBC Connection.

Add a common Legend for combined ggplots

If the legend is the same for both plots, there is a simple solution using grid.arrange(assuming you want your legend to align with both plots either vertically or horizontally). Simply keep the legend for the bottom-most or right-most plot while omitting the legend for the other. Adding a legend to just one plot, however, alters the size of one plot relative to the other. To avoid this use the heights command to manually adjust and keep them the same size. You can even use grid.arrange to make common axis titles. Note that this will require library(grid) in addition to library(gridExtra). For vertical plots:

y_title <- expression(paste(italic("E. coli"), " (CFU/100mL)"))

grid.arrange(arrangeGrob(p1, theme(legend.position="none"), ncol=1), 
   arrangeGrob(p2, theme(legend.position="bottom"), ncol=1), 
   heights=c(1,1.2), left=textGrob(y_title, rot=90, gp=gpar(fontsize=20)))

Here is the result for a similar graph for a project I was working on: enter image description here

SUM of grouped COUNT in SQL Query

Please run as below :

Select sum(count) 
  from (select Name, 
               count(Name) as Count 
          from YourTable
      group by Name);  -- 6

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Table header to stay fixed at the top when user scrolls it out of view with jQuery

function fix_table_header_position(){
 var width_list = [];
 $("th").each(function(){
    width_list.push($(this).width());
 });
 $("tr:first").css("position", "absolute");
 $("tr:first").css("z-index", "1000");
 $("th, td").each(function(index){
    $(this).width(width_list[index]);
 });

 $("tr:first").after("<tr height=" + $("tr:first").height() + "></tr>");}

This is my solution

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

You either need to increase the max_connections configuration setting or (probably better) use connection pooling to route a large number of user requests through a smaller connection pool.

https://wiki.postgresql.org/wiki/Number_Of_Database_Connections

How to Compare two Arrays are Equal using Javascript?

If you comparing 2 arrays but values not in same index, then try this

var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

How to display image from URL on Android

Write the code using ASyncTask for http handling.

Bitmap b;
ImageView img;
......
try
    {
        URL url = new URL("http://10.119.120.10:80/img.jpg");
        InputStream is = new BufferedInputStream(url.openStream());
        b = BitmapFactory.decodeStream(is);
    } catch(Exception e){}
......
img.setImageBitmap(b);

Add CSS class to a div in code behind

Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.

public static void RemoveCssClass(this WebControl control, String css) {
  control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}

public static void AddCssClass(this WebControl control, String css) {
  control.RemoveCssClass(css);
  css += " " + control.CssClass;
  control.CssClass = css;
}

Usage: hlCreateNew.AddCssClass("disabled");

Usage: hlCreateNew.RemoveCssClass("disabled");

<!--[if !IE]> not working

Conditional comment is a comment starts with <!--[if IE]> which couldn't be read by any browser except IE.

from 2011 Conditional comment isn't supported starting form IE 10 as announced by Microsoft in that time https://msdn.microsoft.com/en-us/library/hh801214(v=vs.85).aspx

The only option to use the Conditional comments is to request IE to run your site as IE 9 which supports the Conditional comments.

you can write your own css and/or js files for ie only and other browsers won't load or execute it.

this code snippet shows how to make IE 10 or 11 run ie-only.css and ie-only.js which contains custom codes to solve IE compatibility issues.

    <html>
      <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
      <!--[if IE]>
            <meta http-equiv="Content-Type" content="text/html; charset=Unicode">
            <link rel="stylesheet" type="text/css" href='/css/ie-only.css' />
            <script src="/js/ie-only.js"></script>
      <![endif]-->
    </html>

Function to calculate distance between two coordinates

Using Haversine formula, source of the code:

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::                                                                         :::
//:::  This routine calculates the distance between two points (given the     :::
//:::  latitude/longitude of those points). It is being used to calculate     :::
//:::  the distance between two locations using GeoDataSource (TM) prodducts  :::
//:::                                                                         :::
//:::  Definitions:                                                           :::
//:::    South latitudes are negative, east longitudes are positive           :::
//:::                                                                         :::
//:::  Passed to function:                                                    :::
//:::    lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)  :::
//:::    lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)  :::
//:::    unit = the unit you desire for results                               :::
//:::           where: 'M' is statute miles (default)                         :::
//:::                  'K' is kilometers                                      :::
//:::                  'N' is nautical miles                                  :::
//:::                                                                         :::
//:::  Worldwide cities and other features databases with latitude longitude  :::
//:::  are available at https://www.geodatasource.com                         :::
//:::                                                                         :::
//:::  For enquiries, please contact [email protected]                  :::
//:::                                                                         :::
//:::  Official Web site: https://www.geodatasource.com                       :::
//:::                                                                         :::
//:::               GeoDataSource.com (C) All Rights Reserved 2018            :::
//:::                                                                         :::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

function distance(lat1, lon1, lat2, lon2, unit) {
    if ((lat1 == lat2) && (lon1 == lon2)) {
        return 0;
    }
    else {
        var radlat1 = Math.PI * lat1/180;
        var radlat2 = Math.PI * lat2/180;
        var theta = lon1-lon2;
        var radtheta = Math.PI * theta/180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) {
            dist = 1;
        }
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return dist;
    }
}

The sample code is licensed under LGPLv3.

Can VS Code run on Android?

Running VS Code on Android is not possible, at least until Android support is implemented in Electron. This has been rejected by the Electron team in the past, see electron#562

Visual Studio Codespaces and GitHub Codespaces an upcoming services that enables running VS Code in a browser. Since everything runs in a browser, it seems likely that mobile OS' will be supported.

Auto increment in MongoDB to store sequence of Unique User ID

The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:

maxObj = db.CollectionName.aggregate([
  {
    $group : { _id: '$item', maxValue: { $max: '$fieldName' } } 
  }
];
fieldNextValue = maxObj.maxValue + 1;

$fieldName is the name of your field, but without the $ sign.

CollectionName is the name of your collection.

The reason I am not using count() is that the produced value could meet an existing value.

The creation of an enforcing unique index could make it safer:

db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )

Java method to swap primitives

AFAIS, no one mentions of atomic reference.

Integer

public void swap(AtomicInteger a, AtomicInteger b){
    a.set(b.getAndSet(a.get()));
}

String

public void swap(AtomicReference<String> a, AtomicReference<String> b){
    a.set(b.getAndSet(a.get()));
}

Refresh certain row of UITableView based on Int in Swift

SWIFT 4.2

    func reloadYourRows(name: <anyname>) {
    let row = <your array name>.index(of: <name passing in>)
    let reloadPath = IndexPath(row: row!, section: 0)
    tableView.reloadRows(at: [reloadPath], with: .middle)
    }

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Node.js check if path is file or directory

The answers above check if a filesystem contains a path that is a file or directory. But it doesn't identify if a given path alone is a file or directory.

The answer is to identify directory-based paths using "/." like --> "/c/dos/run/." <-- trailing period.

Like a path of a directory or file that has not been written yet. Or a path from a different computer. Or a path where both a file and directory of the same name exists.

// /tmp/
// |- dozen.path
// |- dozen.path/.
//    |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!

// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
    const isPosix = pathItem.includes("/");
    if ((isPosix && pathItem.endsWith("/")) ||
        (!isPosix && pathItem.endsWith("\\"))) {
        pathItem = pathItem + ".";
    }
    return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
    const isPosix = pathItem.includes("/");
    if (pathItem === "." || pathItem ==- "..") {
        pathItem = (isPosix ? "./" : ".\\") + pathItem;
    }
    return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
} 
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
    if (pathItem === "") {
        return false;
    }
    return !isDirectory(pathItem);
}

Node version: v11.10.0 - Feb 2019

Last thought: Why even hit the filesystem?

Adding class to element using Angular JS

AngularJS has some methods called JQlite so we can use it. see link

Select the element in DOM is

angular.element( document.querySelector( '#div1' ) );

add the class like .addClass('alpha');

So finally

var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');

Ruby: Can I write multi-line string with no concatenation?

conn.exec = <<eos
  select attr1, attr2, attr3, attr4, attr5, attr6, attr7
  from table1, table2, table3, etc, etc, etc, etc, etc,
  where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

How to get child element by index in Jquery?

If you know the child element you're interested in is the first:

 $('.second').children().first();

Or to find by index:

 var index = 0
 $('.second').children().eq(index);

How does a Java HashMap handle different objects with the same hash code?

A hashmap works like this (this is a little bit simplified, but it illustrates the basic mechanism):

It has a number of "buckets" which it uses to store key-value pairs in. Each bucket has a unique number - that's what identifies the bucket. When you put a key-value pair into the map, the hashmap will look at the hash code of the key, and store the pair in the bucket of which the identifier is the hash code of the key. For example: The hash code of the key is 235 -> the pair is stored in bucket number 235. (Note that one bucket can store more then one key-value pair).

When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of the key that you gave. The hashmap will then look into the corresponding bucket, and then it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals().

Now you can see how this is very efficient for looking up key-value pairs in a map: by the hash code of the key the hashmap immediately knows in which bucket to look, so that it only has to test against what's in that bucket.

Looking at the above mechanism, you can also see what requirements are necessary on the hashCode() and equals() methods of keys:

  • If two keys are the same (equals() returns true when you compare them), their hashCode() method must return the same number. If keys violate this, then keys that are equal might be stored in different buckets, and the hashmap would not be able to find key-value pairs (because it's going to look in the same bucket).

  • If two keys are different, then it doesn't matter if their hash codes are the same or not. They will be stored in the same bucket if their hash codes are the same, and in this case, the hashmap will use equals() to tell them apart.

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

You can get this error with you have commented out HTML in a Flask application. Here the value for qual.date_expiry is None:

   <!-- <td>{{ qual.date_expiry.date() }}</td> -->

Delete the line or fix it up:

<td>{% if qual.date_attained != None %} {{ qual.date_attained.date() }} {% endif %} </td>

Commenting code in Notepad++

Try the following shortcut:

Ctrl+K.

Listing information about all database files in SQL Server

I've created this query:

SELECT 
    db.name AS                                   [Database Name], 
    mf.name AS                                   [Logical Name], 
    mf.type_desc AS                              [File Type], 
    mf.physical_name AS                          [Path], 
    CAST(
        (mf.Size * 8
        ) / 1024.0 AS DECIMAL(18, 1)) AS         [Initial Size (MB)], 
    'By '+IIF(
            mf.is_percent_growth = 1, CAST(mf.growth AS VARCHAR(10))+'%', CONVERT(VARCHAR(30), CAST(
        (mf.growth * 8
        ) / 1024.0 AS DECIMAL(18, 1)))+' MB') AS [Autogrowth], 
    IIF(mf.max_size = 0, 'No growth is allowed', IIF(mf.max_size = -1, 'Unlimited', CAST(
        (
                CAST(mf.max_size AS BIGINT) * 8
        ) / 1024 AS VARCHAR(30))+' MB')) AS      [MaximumSize]
FROM 
     sys.master_files AS mf
     INNER JOIN sys.databases AS db ON
            db.database_id = mf.database_id

Converting Integer to String with comma for thousands

This is a way that also able you to replace default separator with any characters:

val myNumber = NumberFormat.getNumberInstance(Locale.US)
   .format(123456789)
   .replace(",", "?")

How to source virtualenv activate in a Bash script

When you source, you're loading the activate script into your active shell.

When you do it in a script, you load it into that shell which exits when your script finishes and you're back to your original, unactivated shell.

Your best option would be to do it in a function

activate () {
  . ../.env/bin/activate
}

or an alias

alias activate=". ../.env/bin/activate"

Hope this helps.

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

MySQL config file location - redhat linux server

it is located at /etc/mysql/my.cnf

How to clear jQuery validation error messages?

In my case helped with approach:

$(".field-validation-error span").hide();

How do you execute SQL from within a bash script?

Maybe you can pipe SQL query to sqlplus. It works for mysql:

echo "SELECT * FROM table" | mysql --user=username database

git returns http error 407 from proxy after CONNECT

The following command is needed to force git to send the credentials and authentication method to the proxy:

git config --global http.proxyAuthMethod 'basic'

Source: https://git-scm.com/docs/git-config#git-config-httpproxyAuthMethod

How to read appSettings section in the web.config file?

    using System.Configuration;

    /// <summary>
    /// For read one setting
    /// </summary>
    /// <param name="key">Key correspondent a your setting</param>
    /// <returns>Return the String contains the value to setting</returns>
    public string ReadSetting(string key)
    {
        var appSettings = ConfigurationManager.AppSettings;
        return appSettings[key] ?? string.Empty;
    }

    /// <summary>
    /// Read all settings for output Dictionary<string,string> 
    /// </summary>        
    /// <returns>Return the Dictionary<string,string> contains all settings</returns>
    public Dictionary<string, string> ReadAllSettings()
    {
        var result = new Dictionary<string, string>();
        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            result.Add(key, ConfigurationManager.AppSettings[key]);
        return result;
    }

What is the equivalent of the C++ Pair<L,R> in Java?

You can use Google's AutoValue library - https://github.com/google/auto/tree/master/value.

You create a very small abstract class and annotate it with @AutoValue and the annotation processor generates a concrete class for you that has a value semantic.

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

Additionally, you will see that float values are rounded.

// e.g: given values 41.0473112,29.0077011

float(11,7) | decimal(11,7)
---------------------------
41.0473099  | 41.0473112
29.0077019  | 29.0077011

How to programmatically empty browser cache?

location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete() can also be used for new chrome, firefox and opera.

Build .NET Core console application to output an EXE

Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args].

Of course this assumes that .NET is installed on the target machine.

Here's the code. Feel free to copy!

using System;
using System.Diagnostics;
using System.Text;

namespace dotNetLauncher
{
    class Program
    {
        /*
            If you make .NET Core applications, they have to be launched like .NET blah.dll args here
            This is a convenience EXE file that launches .NET Core applications via name.exe
            Just rename the output exe to the name of the .NET Core DLL file you wish to launch
        */
        static void Main(string[] args)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory;
            var exeName = AppDomain.CurrentDomain.FriendlyName;
            var assemblyName = exeName.Substring(0, exeName.Length - 4);
            StringBuilder passInArgs = new StringBuilder();
            foreach(var arg in args)
            {
                bool needsSurroundingQuotes = false;
                if (arg.Contains(" ") || arg.Contains("\""))
                {
                    passInArgs.Append("\"");
                    needsSurroundingQuotes = true;
                }
                passInArgs.Append(arg.Replace("\"","\"\""));
                if (needsSurroundingQuotes)
                {
                    passInArgs.Append("\"");
                }

                passInArgs.Append(" ");
            }
            string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";

            var p = new Process
            {
                StartInfo = new ProcessStartInfo("dotnet", callingArgs)
                {
                    UseShellExecute = false
                }
            };

            p.Start();
            p.WaitForExit();
        }
    }
}

How do I format a number in Java?

public static void formatDouble(double myDouble){
 NumberFormat numberFormatter = new DecimalFormat("##.000");
 String result = numberFormatter.format(myDouble);
 System.out.println(result);
}

For instance, if the double value passed into the formatDouble() method is 345.9372, the following will be the result: 345.937 Similarly, if the value .7697 is passed to the method, the following will be the result: .770

Cannot uninstall angular-cli

I could not get the angular-cli to go away. I FINALLY figured out a way to find it on my windows machine. If you have Cygwin installed or you are running linux or mac you can run which ng and it will give you the directory the command is running from. In my case it was running from /c/Users/myuser/AppData/Roaming/npm/ng

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

PHP Fatal Error Failed opening required File

I was having the exact same issue, I triple checked the include paths, I also checked that pear was installed and everything looked OK and I was still getting the errors, after a few hours of going crazy looking at this I realized that in my script had this:

include_once "../Mail.php";

instead of:

include_once ("../Mail.php");

Yup, the stupid parenthesis was missing, but there was no generated error on this line of my script which was odd to me

Parsing JSON from URL

public static TargetClassJson downloadPaletteJson(String url) throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String genreJson = IOUtils.toString(new URL(url).openStream());
        return new Gson().fromJson(genreJson, TargetClassJson.class);
    }

How to identify all stored procedures referring a particular table

SELECT
    o.name
FROM
    sys.sql_modules sm
INNER JOIN sys.objects o ON
    o.object_id = sm.object_id
WHERE
    sm.definition LIKE '%<table name>%'

Just keep in mind that this will also turn up SPs where the table name is in the comments or where the table name is a substring of another table name that is being used. For example, if you have tables named "test" and "test_2" and you try to search for SPs with "test" then you'll get results for both.

AndroidStudio: Failed to sync Install build tools

There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.

  • sdk/build-tools/{TARGET_VERSION}

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

Adding the default_url in routes not the right solution although, it works for some cases.

You've to set the default_url in each environment(development, test, production).

You need make these changes.

    config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

 config/environments/test.rb
      config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

  config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

How to check string length with JavaScript

Leaving a reply (and an answer to the question title), For the future googlers...

You can use .length to get the length of a string.

var x = 'Mozilla'; var empty = '';

console.log('Mozilla is ' + x.length + ' code units long');

/*"Mozilla is 7 code units long" */

console.log('The empty string has a length of ' + empty.length);

/*"The empty string has a length of 0" */

If you intend to get the length of a textarea say id="txtarea" then you can use the following code.

txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);

You should be able to get away with using this with BMP Unicode symbols. If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.

How to pause / sleep thread or process in Android?

  class MyActivity{
    private final Handler handler = new Handler();
    private Runnable yourRunnable;
    protected void onCreate(@Nullable Bundle savedInstanceState) {
       // ....
       this.yourRunnable = new Runnable() {
               @Override
               public void run() {
                   //code
               }
            };

        this.handler.postDelayed(this.yourRunnable, 2000);
       }


     @Override
  protected void onDestroy() {
      // to avoid memory leaks
      this.handler.removeCallbacks(this.yourRunnable);
      }
    }

And to be double sure you can be combined it with the "static class" method as described in the tronman answer

Use of var keyword in C#

I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases).

If you've got a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).

A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.

The other thing to remember is that its not a VB type var in that it can't change types - it is a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).

I suspect this one is going to run and run (-:

Murph

Transpose/Unzip Function (inverse of zip)?

zip is its own inverse! Provided you use the special * operator.

>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]

The way this works is by calling zip with the arguments:

zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))

… except the arguments are passed to zip directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.

How can I return two values from a function in Python?

def test():
    r1 = 1
    r2 = 2
    r3 = 3
    return r1, r2, r3

x,y,z = test()
print x
print y
print z


> test.py 
1
2
3

what does numpy ndarray shape do?

.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.

For Example: 1D ARRAY:

d=np.array([1,2,3,4])
print(d)
(1,)

Output: (4,) ie the number4 denotes the no of elements in the 1D Array.

2D Array:

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

Output: (2,3) ie the number of rows and the number of columns.

The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.

How do I convert a javascript object array to a string array of the object attribute I want?

You can do this to only monitor own properties of the object:

var arr = [];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        arr.push(p[key]);
    }
}

How do I use Apache tomcat 7 built in Host Manager gui?

For tomcat 8

1.Go to context.xml file located for instance../home/ubuntu/tomcat/webapps/manager/META-INF/

comment out valve tag. save and exit

2.Go to tomcat-users.xml file located in conf directory of tomcat. Add the respective roles

under the tomcat-users tag. Save and exit.

  1. Restart the tomcat.

Now, you will be able to have access to the manager app.

CSS 3 slide-in from left transition

USE THIS FOR RIGHT TO LEFT SLIDING :

HTML:

   <div class="nav ">
       <ul>
        <li><a href="#">HOME</a></li>
        <li><a href="#">ABOUT</a></li>
        <li><a href="#">SERVICES</a></li>
        <li><a href="#">CONTACT</a></li>
       </ul>
   </div>

CSS:

/*nav*/
.nav{
    position: fixed;
    right:0;
    top: 70px;
    width: 250px;
    height: calc(100vh - 70px);
    background-color: #333;
    transform: translateX(100%);
    transition: transform 0.3s ease-in-out;

}
.nav-view{
    transform: translateX(0);
}
.nav ul{
    margin: 0;
    padding: 0;
}
.nav ul li{
    margin: 0;
    padding: 0;
    list-style-type: none;
}
.nav ul li a{
    color: #fff;
    display: block;
    padding: 10px;
    border-bottom: solid 1px rgba(255,255,255,0.4);
    text-decoration: none;
}

JS:

  $(document).ready(function(){
  $('a#click-a').click(function(){
    $('.nav').toggleClass('nav-view');
  });
});

How to set text color to a text view programmatically

TextView tt;
int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;
tt.setTextColor(color);

also

tt.setBackgroundColor(Integer.parseInt("d4d446", 16)+0xFF000000);

also

tt.setBackgroundColor(Color.parseColor("#d4d446"));

see:

Java/Android String to Color conversion

How do you change the size of figures drawn with matplotlib?

The first link in Google for 'matplotlib figure size' is AdjustingImageSize (Google cache of the page).

Here's a test script from the above page. It creates test[1-3].png files of different sizes of the same image:

#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib

"""

import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.

import pylab
import numpy as np

# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

pylab.plot(x,y)
F = pylab.gcf()

# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI

# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image

# Now make the image twice as big, making all the fonts and lines
# bigger too.

F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.

Output:

using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8.  6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16.  12.]
Size in Inches [ 16.  12.]

Two notes:

  1. The module comments and the actual output differ.

  2. This answer allows easily to combine all three images in one image file to see the difference in sizes.

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.

MySQL: ALTER TABLE if column not exists

Use the following in a stored procedure:

IF NOT EXISTS( SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'tablename'
             AND table_schema = 'db_name'
             AND column_name = 'columnname')  THEN

  ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';

END IF;

yii2 hidden input value

<?= $form->field($model, 'hidden_Input')->hiddenInput(['id'=>'hidden_Input','class'=>'form-control','value'=>$token_name])->label(false)?>

or

<input type="hidden" name="test" value="1" />

Use This.

When is del useful in Python?

del is often seen in __init__.py files. Any global variable that is defined in an __init__.py file is automatically "exported" (it will be included in a from module import *). One way to avoid this is to define __all__, but this can get messy and not everyone uses it.

For example, if you had code in __init__.py like

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

Then your module would export the sys name. You should instead write

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

del sys

ios app maximum memory budget

I think you've answered your own question: try not to go beyond the 70 Mb limit, however it really depends on many things: what iOS version you're using (not SDK), how many applications running in background, what exact memory you're using etc.

Just avoid the instant memory splashes (e.g. you're using 40 Mb of RAM, and then allocating 80 Mb's more for some short computation). In this case iOS would kill your application immediately.

You should also consider lazy loading of assets (load them only when you really need and not beforehand).

git rebase: "error: cannot stat 'file': Permission denied"

I've only ever seen this error on Windows and what it seems to mean is that something blocked git from modifying a file at the moment when it tried to a apply a patch.

Windows tends to give processes exclusive access to files when it shouldn't really be necessary, in the past virus checkers have been one source of suspicion but I've never proved this conclusively.

Probably the easiest thing to do is to abort and try again, hoping that it doesn't happen the next time.

git rebase --abort

You can attempt to use git apply and knowledge of what commit git was actually trying to do before doing a git rebase --continue but in all honesty I wouldn't recommend this. Most of the times I've seen this tried there's been a better than evens chance that something gets accidentally missed or messed up.

How to check if a column exists before adding it to an existing table in PL/SQL?

Normally, I'd suggest trying the ANSI-92 standard meta tables for something like this but I see now that Oracle doesn't support it.

-- this works against most any other database
SELECT
    * 
FROM 
    INFORMATION_SCHEMA.COLUMNS C 
    INNER JOIN 
        INFORMATION_SCHEMA.TABLES T 
        ON T.TABLE_NAME = C.TABLE_NAME 
WHERE 
    C.COLUMN_NAME = 'columnname'
    AND T.TABLE_NAME = 'tablename'

Instead, it looks like you need to do something like

-- Oracle specific table/column query
SELECT
    * 
FROM
    ALL_TAB_COLUMNS 
WHERE
    TABLE_NAME = 'tablename'
    AND COLUMN_NAME = 'columnname'

I do apologize in that I don't have an Oracle instance to verify the above. If it does not work, please let me know and I will delete this post.

How do we check if a pointer is NULL pointer?

Apparently the thread you refer is about C++.

In C your snippet will always work. I like the simpler if (p) { /* ... */ }.

Array String Declaration

You are not initializing your String[]. You either need to initialize it using the exact array size, as suggested by @Tr?nSiLong, or use a List<String> and then convert to a String[] (in case you do not know the length):

String[] title = {
        "Abundance",
        "Anxiety",
        "Bruxism",
        "Discipline",
        "Drug Addiction"
    };
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
List<String> mStrings = new ArrayList<String>();

for(int i=0;i<title.length;i++) {
    mStrings.add(urlbase + title[i].toLowerCase() + imgSel);

    System.out.println(mStrings[i]);
}

String[] strings = new String[mStrings.size()];
strings = mStrings.toArray(strings);//now strings is the resulting array

Can't execute jar- file: "no main manifest attribute"

I had the same issue today. My problem was solved my moving META-INF to the resources folder.

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

How to make program go back to the top of the code instead of closing

Python has control flow statements instead of goto statements. One implementation of control flow is Python's while loop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.

Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the process must be in the foreground for this to work.

while True:
    # do stuff here
    pass

The line # do stuff here is just a comment. It doesn't execute anything. pass is just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."

Now let's say you want to repeatedly ask the user for input forever and ever, and only exit the program if the user inputs the character 'q' for quit.

You could do something like this:

while True:
    cmd = raw_input('Do you want to quit? Enter \'q\'!')
    if cmd == 'q':
        break

cmd will just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmd stores just the letter 'q', the code will forcefully break out of its enclosing loop. The break statement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.

Declaring a python function with an array parameters and passing an array argument to the function call?

Maybe you want unpack elements of array, I don't know if I got it, but below a example:

def my_func(*args):
    for a in args:
        print a

my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)

How to convert float to varchar in SQL Server

Select
cast(replace(convert(decimal(15,2),acs_daily_debit), '.', ',') as varchar(20))

from acs_balance_details

Creating default object from empty value in PHP?

no you do not .. it will create it when you add the success value to the object.the default class is inherited if you do not specify one.

Play audio file from the assets directory

player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());

Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

Pandas group-by and sum

A variation on the .agg() function; provides the ability to (1) persist type DataFrame, (2) apply averages, counts, summations, etc. and (3) enables groupby on multiple columns while maintaining legibility.

df.groupby(['att1', 'att2']).agg({'att1': "count", 'att3': "sum",'att4': 'mean'})

using your values...

df.groupby(['Name', 'Fruit']).agg({'Number': "sum"})

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.

However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:

  1. Make sure your system is in its normal/idle state. Stop all running processes (applications) that you started or that use CPU intensively (or poll over the network).
  2. Your datasize must be greater in size.
  3. Your test must run for something more than 5-10 seconds.
  4. Do not rely on just one sample. Perform your test N times. Collect results and calculate the mean or median of the result.

How to insert a SQLite record with a datetime set to 'now' in Android application?

Based on @e-satis answer I created a private method on my "DBTools" class so adding current date is now really easy:

...
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
...
        private String getNow(){
            // set the format to sql date time
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            return dateFormat.format(date);
        }
...

Use it now like this: values.put("lastUpdate", getNow());

How do I break out of nested loops in Java?

Below is an example where "break" statement pushes the cursor out of the for loop whenever the condition is met.

public class Practice3_FindDuplicateNumber {

    public static void main(String[] args) {
        Integer[] inp = { 2, 3, 4, 3, 3 };
        Integer[] aux_arr = new Integer[inp.length];
        boolean isduplicate = false;
        for (int i = 0; i < aux_arr.length; i++) {

            aux_arr[i] = -1;

        }
        outer: for (int i = 0; i < inp.length; i++) {
            if (aux_arr[inp[i]] == -200) {
                System.out.println("Duplicate Found at index: " + i + " Carrying value: " + inp[i]);
                isduplicate = true;
                break outer;
            } else {
                aux_arr[inp[i]] = -200;
            }
        }

        for (Integer integer : aux_arr) {
            System.out.println(integer);
        }

        if (isduplicate == false) {
            System.out.println("No Duplicates!!!!!");
        } else {
            System.out.println("Duplicates!!!!!");
        }
    }

}

How is a CRC32 checksum calculated?

A CRC is pretty simple; you take a polynomial represented as bits and the data, and divide the polynomial into the data (or you represent the data as a polynomial and do the same thing). The remainder, which is between 0 and the polynomial is the CRC. Your code is a bit hard to understand, partly because it's incomplete: temp and testcrc are not declared, so it's unclear what's being indexed, and how much data is running through the algorithm.

The way to understand CRCs is to try to compute a few using a short piece of data (16 bits or so) with a short polynomial -- 4 bits, perhaps. If you practice this way, you'll really understand how you might go about coding it.

If you're doing it frequently, a CRC is quite slow to compute in software. Hardware computation is much more efficient, and requires just a few gates.

How long will my session last?

This is the one. The session will last for 1440 seconds (24 minutes).

session.gc_maxlifetime  1440    1440

Which port we can use to run IIS other than 80?

Port 8080 might have been used by another process in your computer.

Do netstat in command prompt to find out which server/process is using it.

Have a look at this page (http://en.wikipedia.org/wiki/Port_number) it gives you full explanation on how to use port number

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

How do I convert an Array to a List<object> in C#?

Here is my version:

  List<object> list = new List<object>(new object[]{ "test", 0, "hello", 1, "world" });

  foreach(var x in list)
  {
      Console.WriteLine("x: {0}", x);
  }

Proxies with Python 'Requests' module

I share some code how to fetch proxies from the site "https://free-proxy-list.net" and store data to a file compatible with tools like "Elite Proxy Switcher"(format IP:PORT):

##PROXY_UPDATER - get free proxies from https://free-proxy-list.net/

from lxml.html import fromstring
import requests
from itertools import cycle
import traceback
import re

######################FIND PROXIES#########################################
def get_proxies():
    url = 'https://free-proxy-list.net/'
    response = requests.get(url)
    parser = fromstring(response.text)
    proxies = set()
    for i in parser.xpath('//tbody/tr')[:299]:   #299 proxies max
        proxy = ":".join([i.xpath('.//td[1]/text()') 
        [0],i.xpath('.//td[2]/text()')[0]])
        proxies.add(proxy)
    return proxies



######################write to file in format   IP:PORT######################
try:
    proxies = get_proxies()
    f=open('proxy_list.txt','w')
    for proxy in proxies:
        f.write(proxy+'\n')
    f.close()
    print ("DONE")
except:
    print ("MAJOR ERROR")

jQuery convert line breaks to br (nl2br equivalent)

you can simply do:

textAreaContent=textAreaContent.replace(/\n/g,"<br>");

How to make use of ng-if , ng-else in angularJS

Use ng-switch with expression and ng-switch-when for matching expression value:

<div ng-switch="data.id">
  <div ng-switch-when="5">...</div>
  <div ng-switch-default>...</div>
</div>

Example is here

Angular2 example

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

Suppress/ print without b' prefix for bytes in Python 3

I am a little late but for Python 3.9.1 this worked for me and removed the -b prefix:

print(outputCode.decode())

Operator overloading in Java

In addition to all the people pointing out that + is overloaded for Strings, - is also overloaded for both floating point and integer operations, as are * and /.

[edit] % is also overloaded for floating point, which can be a bit of a surprise for those with a C or C++ background.

How to convert a string or integer to binary in Ruby?

I asked a similar question. Based on @sawa's answer, the most succinct way to represent an integer in a string in binary format is to use the string formatter:

"%b" % 245
=> "11110101"

You can also choose how long the string representation to be, which might be useful if you want to compare fixed-width binary numbers:

1.upto(10).each { |n| puts "%04b" % n }
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010

Maven: How to run a .java file from command line passing arguments

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

Web link to specific whatsapp contact

********* UPDATE ADDED AT THE END *********

I've tried many approaches and I have a winner (see Test 3), here is the result of each one:

(I think the Test 3 will also work for you because if the person visiting your site doesn't have you on their contact list, it's the only option that will allow it.)

In all tests, the number had to be complete, with country and location code without any initial zeros. Example:

  • +55(011) 99999-9999 (NOT)
  • +5511999999999 (YES)

On tests 1 and 2, it only worked with a plus sign on the country code: +5511999999999

Test 1:

<a href="whatsapp://send?abid=phonenumber&text=Hello%2C%20World!">Send Message</a>

This way you must have the phonenumber on your contact list. It doesn't work for me because I wanted to be able to send a message to a number which I may not have on my contact list.

If you don't have the number on your contact list, it opens the Whatsapp listing all your registered contacts, so you can choose one.

It's a good option for sharing stuff.

Test 2:

<a href="intent://send/phonenumber#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">Send Message</a>

This approach only works on Android AND if you have the number on your contact list. If you don't have it, Android opens your SMS app, so you can invite the contact to use Whatsapp.

Test 3 (The Winner):

<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>

This was the only way that worked fully for me.

  • It works on Android, iOS and Web app on the desktop,
  • You can start a conversation with a number that you don't have on your contact list
  • You can create a link with one pre-built message adding &text=[message-url-encoded] like:

https://api.whatsapp.com/send?phone=15551234567&text=Send20%a20%quote

And if you wish to have a bookmarklet for additional ease of use, you may use this one:

javascript: (function() { var val= prompt("Enter phone number",""); if (val) location="https://api.whatsapp.com/send?phone="+escape('972' + val)+""; })()

Youll need to change the country code(or remove it) to you.r target country and paste it in the address field in a chrome/firefox link

Worth notice:

***************** UPDATE (START) *****************

Whatsapp made available other option, now you can create one link to a conversation like this:

https://wa.me/[phonenumber]

The phone number should be in international format:

Like this:

https://wa.me/552196312XXXX

NOT like this:

https://wa.me/+55(021)96312-XXXX

And if you want to add one pre-built message to your link, you can add ?text= at the end with the text URL Encoded:

https://wa.me/552196312XXXX?text=[message-url-encoded]

Exemple:

https://wa.me/552196312XXXX?text=Send20%a20%quote

More info here:

https://faq.whatsapp.com/general/chats/how-to-use-click-to-chat

***************** UPDATE (END) *****************

drag drop files into standard html file input

I made a solution for this.

_x000D_
_x000D_
$(function () {_x000D_
    var dropZoneId = "drop-zone";_x000D_
    var buttonId = "clickHere";_x000D_
    var mouseOverClass = "mouse-over";_x000D_
_x000D_
    var dropZone = $("#" + dropZoneId);_x000D_
    var ooleft = dropZone.offset().left;_x000D_
    var ooright = dropZone.outerWidth() + ooleft;_x000D_
    var ootop = dropZone.offset().top;_x000D_
    var oobottom = dropZone.outerHeight() + ootop;_x000D_
    var inputFile = dropZone.find("input");_x000D_
    document.getElementById(dropZoneId).addEventListener("dragover", function (e) {_x000D_
        e.preventDefault();_x000D_
        e.stopPropagation();_x000D_
        dropZone.addClass(mouseOverClass);_x000D_
        var x = e.pageX;_x000D_
        var y = e.pageY;_x000D_
_x000D_
        if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {_x000D_
            inputFile.offset({ top: y - 15, left: x - 100 });_x000D_
        } else {_x000D_
            inputFile.offset({ top: -400, left: -400 });_x000D_
        }_x000D_
_x000D_
    }, true);_x000D_
_x000D_
    if (buttonId != "") {_x000D_
        var clickZone = $("#" + buttonId);_x000D_
_x000D_
        var oleft = clickZone.offset().left;_x000D_
        var oright = clickZone.outerWidth() + oleft;_x000D_
        var otop = clickZone.offset().top;_x000D_
        var obottom = clickZone.outerHeight() + otop;_x000D_
_x000D_
        $("#" + buttonId).mousemove(function (e) {_x000D_
            var x = e.pageX;_x000D_
            var y = e.pageY;_x000D_
            if (!(x < oleft || x > oright || y < otop || y > obottom)) {_x000D_
                inputFile.offset({ top: y - 15, left: x - 160 });_x000D_
            } else {_x000D_
                inputFile.offset({ top: -400, left: -400 });_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
_x000D_
    document.getElementById(dropZoneId).addEventListener("drop", function (e) {_x000D_
        $("#" + dropZoneId).removeClass(mouseOverClass);_x000D_
    }, true);_x000D_
_x000D_
})
_x000D_
#drop-zone {_x000D_
    /*Sort of important*/_x000D_
    width: 300px;_x000D_
    /*Sort of important*/_x000D_
    height: 200px;_x000D_
    position:absolute;_x000D_
    left:50%;_x000D_
    top:100px;_x000D_
    margin-left:-150px;_x000D_
    border: 2px dashed rgba(0,0,0,.3);_x000D_
    border-radius: 20px;_x000D_
    font-family: Arial;_x000D_
    text-align: center;_x000D_
    position: relative;_x000D_
    line-height: 180px;_x000D_
    font-size: 20px;_x000D_
    color: rgba(0,0,0,.3);_x000D_
}_x000D_
_x000D_
    #drop-zone input {_x000D_
        /*Important*/_x000D_
        position: absolute;_x000D_
        /*Important*/_x000D_
        cursor: pointer;_x000D_
        left: 0px;_x000D_
        top: 0px;_x000D_
        /*Important This is only comment out for demonstration purposes._x000D_
        opacity:0; */_x000D_
    }_x000D_
_x000D_
    /*Important*/_x000D_
    #drop-zone.mouse-over {_x000D_
        border: 2px dashed rgba(0,0,0,.5);_x000D_
        color: rgba(0,0,0,.5);_x000D_
    }_x000D_
_x000D_
_x000D_
/*If you dont want the button*/_x000D_
#clickHere {_x000D_
    position: absolute;_x000D_
    cursor: pointer;_x000D_
    left: 50%;_x000D_
    top: 50%;_x000D_
    margin-left: -50px;_x000D_
    margin-top: 20px;_x000D_
    line-height: 26px;_x000D_
    color: white;_x000D_
    font-size: 12px;_x000D_
    width: 100px;_x000D_
    height: 26px;_x000D_
    border-radius: 4px;_x000D_
    background-color: #3b85c3;_x000D_
_x000D_
}_x000D_
_x000D_
    #clickHere:hover {_x000D_
        background-color: #4499DD;_x000D_
_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="drop-zone">_x000D_
    Drop files here..._x000D_
    <div id="clickHere">_x000D_
        or click here.._x000D_
        <input type="file" name="file" id="file" />_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The Drag and Drop functionality for this method only works with Chrome, Firefox and Safari. (Don't know if it works with IE10), but for other browsers, the "Or click here" button works fine.

The input field simply follow your mouse when dragging a file over an area, and I've added a button as well..

Uncomment opacity:0; the file input is only visible so you can see what's going on.

Detect backspace and del on "input" event?

It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:

document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
    if (e.inputType == "deleteContentBackward") {
        // your code here
    }
});

How to add border radius on table row

Actual Spacing Between Rows

This is an old thread, but I noticed reading the comments from the OP on other answers that the original goal was apparently to have border-radius on the rows, and gaps between the rows. It does not appear that the current solutions exactly do that. theazureshadow's answer is headed in the right direction, but seems to need a bit more.

For those interested in such, here is a fiddle that does separate the rows and applies the radius to each row. (NOTE: Firefox currently has a bug in displaying/clipping background-color at the border radii.)

The code is as follows (and as theazureshadow noted, for earlier browser support, the various vendor prefixes for border-radius need added).

table { 
    border-collapse: separate; 
    border-spacing: 0 10px; 
    margin-top: -10px; /* correct offset on first border spacing if desired */
}
td {
    border: solid 1px #000;
    border-style: solid none;
    padding: 10px;
    background-color: cyan;
}
td:first-child {
    border-left-style: solid;
    border-top-left-radius: 10px; 
    border-bottom-left-radius: 10px;
}
td:last-child {
    border-right-style: solid;
    border-bottom-right-radius: 10px; 
    border-top-right-radius: 10px; 
}

How do you dynamically allocate a matrix?

The other answer describing arrays of arrays are correct.
BUT if you are planning of doing a anything mathematical with the arrays - or need something special like sparse matrices you should look at one of the many maths libs like TNT before re-inventing too many wheels

How to fix java.net.SocketException: Broken pipe?

The above answers illustrate the reason for this java.net.SocketException: Broken pipe: the other end closed the connection. I would like to share experience what happened when I encountered it:

  1. in a client's request, the Content-Type header is mistakenly set larger than request body actually is (in fact there was no body at all)
  2. the bottom service in tomcat socket was waiting for that sized body data (http is on TCP which ensures delivery by encapsulating and ...)
  3. when 60 seconds expired, tomcat throws time out exception: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception java.net.SocketTimeoutException: null
  4. client receives a response with status code 500 because of the timeout exception.
  5. client close connection (because it receives response).
  6. tomcat throws java.net.SocketException: Broken pipe because client closed it.

Sometimes, tomcat does not throw broken pip exception, because timeout exception close the connection, why such a difference is confusing me too.

how to get the value of a textarea in jquery?

all Values is always taken with .val().

see the code bellow:

var message = $('#message').val();

Gaussian fit for Python

sigma = sum(y*(x - mean)**2)

should be

sigma = np.sqrt(sum(y*(x - mean)**2))

ProgressDialog is deprecated.What is the alternate one to use?

You can use this class I wrote. It offers only the basic functions. If you want a fully functional ProgressDialog, then use this lightweight library.

Gradle Setup

Add the following dependency to module/build.gradle:

compile 'com.lmntrx.android.library.livin.missme:missme:0.1.5'

How to use it?

Usage is similar to original ProgressDialog

ProgressDialog progressDialog = new 
progressDialog(YourActivity.this);
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.dismiss();

NB: You must override activity's onBackPressed()

Java8 Implementation:

@Override
public void onBackPressed() {
    progressDialog.onBackPressed(
            () -> {
                super.onBackPressed();
                return null;
            }
    );
}

Kotlin Implementation:

override fun onBackPressed() {
   progressDialog.onBackPressed { super.onBackPressed() }
}
  • Refer Sample App for the full implementation
  • Full documentation can be found here

Finding Number of Cores in Java

This works on Windows with Cygwin installed:

System.getenv("NUMBER_OF_PROCESSORS")

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

How do I connect to a MySQL Database in Python?

Here's one way to do it, using MySQLdb, which only supports Python 2:

#!/usr/bin/python
import MySQLdb

# Connect
db = MySQLdb.connect(host="localhost",
                     user="appuser",
                     passwd="",
                     db="onco")

cursor = db.cursor()

# Execute SQL select statement
cursor.execute("SELECT * FROM location")

# Commit your changes if writing
# In this case, we are only reading data
# db.commit()

# Get the number of rows in the resultset
numrows = cursor.rowcount

# Get and display one row at a time
for x in range(0, numrows):
    row = cursor.fetchone()
    print row[0], "-->", row[1]

# Close the connection
db.close()

Reference here

Set NA to 0 in R

Why not try this

  na.zero <- function (x) {
        x[is.na(x)] <- 0
        return(x)
    }
    na.zero(df)

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Print execution time of a shell command

Adding to @mob's answer:

Appending %N to date +%s gives us nanosecond accuracy:

start=`date +%s%N`;<command>;end=`date +%s%N`;echo `expr $end - $start`

Java Mouse Event Right Click

I've seen

anEvent.isPopupTrigger() 

be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)

How to convert Nvarchar column to INT

CONVERT takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn to an integer instead of the column content.

SELECT convert (int, N'A.my_NvarcharColumn') FROM A;

should instead be

SELECT convert (int, A.my_NvarcharColumn) FROM A;

Simple SQLfiddle here.

Assigning default values to shell variables with a single command in bash

For command line arguments:

VARIABLE="${1:-$DEFAULTVALUE}"

which assigns to VARIABLE the value of the 1st argument passed to the script or the value of DEFAULTVALUE if no such argument was passed. Qouting prevents globbing and word splitting.

how to set select element as readonly ('disabled' doesnt pass select value on server)

see this answer - HTML form readonly SELECT tag/input

You should keep the select element disabled but also add another hidden input with the same name and value.

If you reenable your SELECT, you should copy it's value to the hidden input in an onchange event.

see this fiddle to demnstrate how to extract the selected value in a disabled select into a hidden field that will be submitted in the form.

<select disabled="disabled" id="sel_test">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<input type="hidden" id="hdn_test" />
<div id="output"></div>

$(function(){
    var select_val = $('#sel_test option:selected').val();
    $('#hdn_test').val(select_val);
    $('#output').text('Selected value is: ' + select_val);
});

hope that helps.

SSRS custom number format

Have you tried with the custom format "#,##0.##" ?

Dynamically change color to lighter or darker by percentage CSS (Javascript)

Use the filter pure CSS property. for a complete description of the filter property functions read this awesome article.

I had a same issue like yours, and I fixed it by using the brightness function of filter property:

.my-class {
  background-color: #18d176;
  filter: brightness(90%);
}

To check if string contains particular word

You can use regular expressions:

if (d.matches(".*Hey.*")) {
    c.setText("OUTPUT: SUCCESS!");
} else {
    c.setText("OUTPUT: FAIL!");  
}

.* -> 0 or more of any characters

Hey -> The string you want

If you will be checking this often, it is better to compile the regular expression in a Pattern object and reuse the Pattern instance to do the checking.

private static final Pattern HEYPATTERN = Pattern.compile(".*Hey.*");
[...]
if (HEYPATTERN.matcher(d).matches()) {
    c.setText("OUTPUT: SUCCESS!");
} else {
    c.setText("OUTPUT: FAIL!");  
}

Just note this will also match "Heyburg" for example since you didn't specify you're searching for "Hey" as an independent word. If you only want to match Hey as a word, you need to change the regex to .*\\bHey\\b.*

Difference between HttpModule and HttpClientModule

There is a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

A reason for existing

When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.

This is because Observable<HttpResponse<T>> is tied to HttpResponse.

This tightly couples the http layer with the rest of your code.

This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.

With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the getRaceInfo API called as shown below.

  ngOnInit() {    
    this.service.getRaceInfo(response => this.result = response.result,
                                error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Also, you can still use the traditional route and return Observable<HttpResponse<T>> from Service API.

How to assign an exec result to a sql variable?

From the documentation (assuming that you use SQL-Server):

USE AdventureWorks;
GO
DECLARE @returnstatus nvarchar(15);
SET @returnstatus = NULL;
EXEC @returnstatus = dbo.ufnGetSalesOrderStatusText @Status = 2;
PRINT @returnstatus;
GO

So yes, it should work that way.

python's re: return True if string contains regex pattern

The best one by far is

bool(re.search('ba[rzd]', 'foobarrrr'))

Returns True

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

python: Change the scripts working directory to the script's own directory

Change your crontab command to

* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)

The (...) starts a sub-shell that your crond executes as a single command. The || exit 1 causes your cronjob to fail in case that the directory is unavailable.

Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

You don't have permission to the Python folder.

sudo chown -R $USER /usr/local/lib/python2.7

What does a circled plus mean?

It's not an addition, but an exclusive OR operation. At least the output confirms to the same.

enter image description here

Entity framework left join

adapted from MSDN, how to left join using EF 4

var query = from u in usergroups
            join p in UsergroupPrices on u.UsergroupID equals p.UsergroupID into gj
            from x in gj.DefaultIfEmpty()
            select new { 
                UsergroupID = u.UsergroupID,
                UsergroupName = u.UsergroupName,
                Price = (x == null ? String.Empty : x.Price) 
            };

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

How to make a vertical line in HTML

In the Previous element after which you want to apply the vertical row , You can set CSS ...

border-right-width: thin;
border-right-color: black;
border-right-style: solid;

sending email via php mail function goes to spam

Be careful with your tests. If you in your form you put the same email as the email address which must receive it will be directly in spam :)