Programs & Examples On #Utility method

For questions regarding utility class methods.

How can I create an utility class?

According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.

Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.

Extract data from log file in specified range of time

Use grep and regular expressions, for example if you want 4 minutes interval of logs:

grep "31/Mar/2002:19:3[1-5]" logfile

will return all logs lines between 19:31 and 19:35 on 31/Mar/2002. Supposing you need the last 5 days starting from today 27/Sep/2011 you may use the following:

grep "2[3-7]/Sep/2011" logfile

Custom domain for GitHub project pages

Overview

The documentation is a little confusing when it comes to project pages, as opposed to user pages. It feels like you should have to do more, but actually the process is very easy.

It involves:

  1. Setting up 2 static A records for the naked (no www) domain.
  2. Creating one CNAME record for www which will point to a GitHub URL. This will handle www redirection for you.
  3. Creating a file called CNAME (capitalised) in your project root on the gh-pages branch. This will tell Github what URL to respond to.
  4. Wait for everything to propagate.

What you will get

Your content will be served from a URL of the form http://nicholasjohnson.com.

Visiting http://www.nicholasjohnson.com will return a 301 redirect to the naked domain.

The path will be respected by the redirect, so traffic to http://www.nicholasjohnson.com/angular will be redirected to http://nicholasjohnson.com/angular.

You can have one project page per repository, so if your repos are open you can have as many as you like.

Here's the process:

1. Create A records

For the A records, point @ to the following ip addresses:

@: 185.199.108.153
@: 185.199.109.153
@: 185.199.110.153
@: 185.199.111.153

These are the static Github IP addresses from which your content will be served.

2. Create a CNAME Record

For the CNAME record, point www to yourusername.github.io. Note the trailing full stop. Note also, this is the username, not the project name. You don't need to specify the project name yet. Github will use the CNAME file to determine which project to serve content from.

e.g.

www: forwardadvance.github.io.

The purpose of the CNAME is to redirect all www subdomain traffic to a GitHub page which will 301 redirect to the naked domain.

Here's a screenshot of the configuration I use for my own site http://nicholasjohnson.com:

A and CNAME records required for Github Static Pages

3. Create a CNAME file

Add a file called CNAME to your project root in the gh-pages branch. This should contain the domain you want to serve. Make sure you commit and push.

e.g.

nicholasjohnson.com

This file tells GitHub to use this repo to handle traffic to this domain.

4. Wait

Now wait 5 minutes, your project page should now be live.

How to get highcharts dates in the x axis?

Highcharts will automatically try to find the best format for the current zoom-range. This is done if the xAxis has the type 'datetime'. Next the unit of the current zoom is calculated, it could be one of:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • year

This unit is then used find a format for the axis labels. The default patterns are:

second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'

If you want the day to be part of the "hour"-level labels you should change the dateTimeLabelFormats option for that level include %d or %e. These are the available patters:

  • %a: Short weekday, like 'Mon'.
  • %A: Long weekday, like 'Monday'.
  • %d: Two digit day of the month, 01 to 31.
  • %e: Day of the month, 1 through 31.
  • %b: Short month, like 'Jan'.
  • %B: Long month, like 'January'.
  • %m: Two digit month number, 01 through 12.
  • %y: Two digits year, like 09 for 2009.
  • %Y: Four digits year, like 2009.
  • %H: Two digits hours in 24h format, 00 through 23.
  • %I: Two digits hours in 12h format, 00 through 11.
  • %l (Lower case L): Hours in 12h format, 1 through 11.
  • %M: Two digits minutes, 00 through 59.
  • %p: Upper case AM or PM.
  • %P: Lower case AM or PM.
  • %S: Two digits seconds, 00 through 59

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

Script to get the HTTP status code of a list of urls?

I found a tool "webchk” written in Python. Returns a status code for a list of urls. https://pypi.org/project/webchk/

Output looks like this:

? webchk -i ./dxieu.txt | grep '200'
http://salesforce-case-status.dxi.eu/login ... 200 OK (0.108)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.389)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.401)

Hope that helps!

Removing ul indentation with CSS

This code will remove the indentation and list bullets.

ul {
    padding: 0;
    list-style-type: none;
}

http://jsfiddle.net/qeqtK/2/

How to format numbers by prepending 0 to single-digit numbers?

my example would be:

<div id="showTime"></div>

    function x() {
    var showTime = document.getElementById("showTime");
    var myTime = new Date();
    var hour = myTime.getHours();
    var minu = myTime.getMinutes();
    var secs = myTime.getSeconds();
    if (hour < 10) {
        hour = "0" + hour
    };
    if (minu < 10) {
        minu = "0" + minu
    };
    if (secs < 10) {
        secs = "0" + secs
    };

    showTime.innerHTML = hour + ":" + minu + ":" + secs;
}

setInterval("x()", 1000)

Load JSON text into class object in c#

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

Show a popup/message box from a Windows batch file

This application can do that, if you convert (wrap) your batch files into executable files.


  1. Simple Messagebox

    %extd% /messagebox Title Text
    

  1. Error Messagebox

    %extd% /messagebox  Error "Error message" 16
    
  2. Cancel Try Again Messagebox

    %extd% /messagebox Title "Try again or Cancel" 5
    

4) "Never ask me again" Messagebox

%extd% /messageboxcheck Title Message 0 {73E8105A-7AD2-4335-B694-94F837A38E79}

Floating point exception

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

Python reading from a file and saving to utf-8

You can't do that using open. use codecs.

when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

import codecs
file = codecs.open('data.txt','w','utf-8')

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

Following is the best way to get of the issue , check following on classpath:

  1. Make sure JAVA_HOME system variable must have till jdk e.g C:\Program Files\Java\jdk1.7.0_80 , don't append bin here.

  2. Because MAVEN will look for jre which is under C:\Program Files\Java\jdk1.7.0_80

  3. Set %JAVA_HOME%\bin in classpath .

Then try Maven version .

Hope it will help .

Hibernate error - QuerySyntaxException: users is not mapped [from users]

I recommend this pattern:

@Entity(name = User.PERSISTANCE_NAME)
@Table(name = User.PERSISTANCE_NAME )
public class User {    
    static final String PERSISTANCE_NAME = "USER";

    // Column definitions here

}

Differences between action and actionListener

ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.

If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.

Here is a link that describes the relationship:

http://www.java-samples.com/showtutorial.php?tutorialid=605

'sudo gem install' or 'gem install' and gem locations

Installing Ruby gems on a Mac is a common source of confusion and frustration. Unfortunately, most solutions are incomplete, outdated, and provide bad advice. I'm glad the accepted answer here says to NOT use sudo, which you should never need to do, especially if you don't understand what it does. While I used RVM years ago, I would recommend chruby in 2020.

Some of the other answers here provide alternative options for installing gems, but they don't mention the limitations of those solutions. What's missing is an explanation and comparison of the various options and why you might choose one over the other. I've attempted to cover most common scenarios in my definitive guide to installing Ruby gems on a Mac.

How to append multiple items in one line in Python

mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

How do I debug Node.js applications?

Debugging

Profiling

  1. node --prof ./app.js
  2. node --prof-process ./the-generated-log-file

Heapdumps

Flamegraphs

Tracing

Logging

Libraries that output debugging information

Libraries that enhance stack trace information

Benchmarking

Other

Legacy

These use to work but are no longer maintained or no longer applicable to modern node versions.

How to get first item from a java.util.Set?

As, you mentioned pContext.getParent().getPropertyValue return Set. You can convert Set to List to get the first element. Just change your code like:

 Set<String> siteIdSet = (Set<String>) pContext.getParent().getPropertyValue(..);
 List<String> siteIdList=new ArrayList<>(siteIdSet);

 String firstItem=siteIdList.get(0);

How to automatically indent source code?

In 2010 it is Ctrl+k, Ctrl+d. See image below.

enter image description here

Rounding a variable to two decimal places C#

Use Math.Round and specify the number of decimal places.

Math.Round(pay,2);

Math.Round Method (Double, Int32)

Rounds a double-precision floating-point value to a specified number of fractional digits.

Or Math.Round Method (Decimal, Int32)

Rounds a decimal value to a specified number of fractional digits.

Smooth scrolling with just pure css

You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.

You're likely best placed to use e.g. jQuery, specifically:

$('html, body').stop().animate({
   scrollTop: element.offset().top
}, 1000);

A complete implementation may be:

$('#up, #down').on('click', function(e){
    e.preventDefault();
    var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
    $('html, body').stop().animate({
       scrollTop: target.offset().top
    }, 1000);
});

Where element is the target element to scroll to and 1000 is the delay in ms before completion.

Demo Fiddle

The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.

What are the recommendations for html <base> tag?

Well, wait a minute. I don't think the base tag deserves this bad reputation.

The nice thing about the base tag is that it enables you to do complex URL rewrites with less hassle.

Here's an example. You decide to move http://example.com/product/category/thisproduct to http://example.com/product/thisproduct. You change your .htaccess file to rewrite the first URL to the second URL.

With the base tag in place, you do your .htaccess rewrite and that's it. No problem. But without the base tag, all of your relative links will break.

URL rewrites are often necessary, because tweaking them can help your site's architecture and search engine visibility. True, you'll need workarounds for the "#" and '' problems that folks mentioned. But the base tag deserves a place in the toolkit.

How to import component into another root component in Angular 2

Angular RC5 & RC6

If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({}).

The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.

If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses> is in your template file.

Here is an example:

import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';

describe('CoursesComponent', () => {
  let component: CoursesComponent;
  let fixture: ComponentFixture<CoursesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CoursesComponent
      ],
      imports: [
        BrowserModule
        // If you have any other imports add them here
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoursesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Expanding tuples into arguments

Similar to @Dominykas's answer, this is a decorator that converts multiargument-accepting functions into tuple-accepting functions:

apply_tuple = lambda f: lambda args: f(*args)

Example 1:

def add(a, b):
    return a + b

three = apply_tuple(add)((1, 2))

Example 2:

@apply_tuple
def add(a, b):
    return a + b

three = add((1, 2))

Open PDF in new browser full window

<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>

The above link will open the PDF in full screen mode, that's the best you can achieve.

'negative' pattern matching in python

If the OK line is the first line and the last line is the dot you could consider slice them off like this:

TestString = '''OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt
.
'''
print('\n'.join(TestString.split()[1:-1]))

However if this is a very large string you may run into memory problems.

Split a large pandas dataframe

I also experienced np.array_split not working with Pandas DataFrame my solution was to only split the index of the DataFrame and then introduce a new column with the "group" label:

indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
   df.loc[index,'group'] = i

This makes grouby operations very convenient for instance calculation of mean value of each group:

df.groupby(by='group').mean()

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.

PHP class: Global variable as property in class

class myClass { protected $foo;

public function __construct(&$var)
{
    $this->foo = &$var;
}

public function foo()
{
    return ++$this->foo;
}

}

Using the Web.Config to set up my SQL database connection string?

Web.config file

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

remote rejected master -> master (pre-receive hook declined)

If you run $ heroku logs you may get a "hint" to what the problem is. For me, Heroku could not detect what type of app I was creating. It required me to set the buildpack. Since I was creating a Node.js app, I just had to run $ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-nodejs. You can read more about it here: https://devcenter.heroku.com/articles/buildpacks. No pushing issues after that.

I know this is an old question, but still posting this here incase someone else gets stuck.

How to get the filename without the extension from a path in Python?

@IceAdor's refers to rsplit in a comment to @user2902201's solution. rsplit is the simplest solution that supports multiple periods.

Here it is spelt out:

file = 'my.report.txt'
print file.rsplit('.', 1)[0]

my.report

Importing data from a JSON file into R

An alternative package is RJSONIO. To convert a nested list, lapply can help:

l <- fromJSON('[{"winner":"68694999",  "votes":[ 
   {"ts":"Thu Mar 25 03:13:01 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}},   
   {"ts":"Thu Mar 25 03:13:08 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}}],   
  "lastVote":{"timestamp":1269486788526,"user":
   {"name":"Lamur","user_id":"68694999"}},"startPrice":0}]'
)
m <- lapply(
    l[[1]]$votes, 
    function(x) c(x$user['name'], x$user['user_id'], x['ts'])
)
m <- do.call(rbind, m)

gives information on the votes in your example.

React native text going off my screen, refusing to wrap. What to do?

<View style={{flexDirection:'row'}}> 
   <Text style={{ flex: number }}> You miss fdddddd dddddddd 
     You miss fdd
   </Text>
</View>

{ flex: aNumber } is all you need!

Just set 'flex' to a number that suit for you. And then the text will wrap.

Is there a way to ignore a single FindBugs warning?

Update Gradle

dependencies {
    compile group: 'findbugs', name: 'findbugs', version: '1.0.0'
}

Locate the FindBugs Report

file:///Users/your_user/IdeaProjects/projectname/build/reports/findbugs/main.html

Find the specific message

find bugs

Import the correct version of the annotation

import edu.umd.cs.findbugs.annotations.SuppressWarnings;

Add the annotation directly above the offending code

@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX")

See here for more info: findbugs Spring Annotation

Counting the number of elements with the values of x in a vector

You can make a function to give you results.

# your list
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)

function1<-function(x){
    if(x==value){return(1)}else{ return(0) }
}

# set your value here
value<-4

# make a vector which return 1 if it equal to your value, 0 else
vector<-sapply(numbers,function(x) function1(x))
sum(vector)

result: 2

URL encoding in Android

You don't encode the entire URL, only parts of it that come from "unreliable sources".

  • Java:

    String query = URLEncoder.encode("apples oranges", "utf-8");
    String url = "http://stackoverflow.com/search?q=" + query;
    
  • Kotlin:

    val query: String = URLEncoder.encode("apples oranges", "utf-8")
    val url = "http://stackoverflow.com/search?q=$query"
    

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.

Or use something like

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();

DISTINCT for only one column

You can over that by using GROUP BY like this:

SELECT ID, Email, ProductName, ProductModel
FROM Products
GROUP BY Email

No module named Image

You are missing PIL (Python Image Library and Imaging package). To install PIL I used

 pip install pillow

For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source. http://effbot.org/downloads/Imaging-1.1.6.tar.gz and cd into Download directory. Then run these:

    $ gunzip Imaging-1.1.6.tar.gz
    $ tar xvf Imaging-1.1.6.tar
    $ cd Imaging-1.1.6
    $ python setup.py install

Or if you have PIP installed in your Mac

 pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz

then you can use:

from PIL import Image

in your python code.

Send Mail to multiple Recipients in java

Just use the method message.setRecipients with multiple addresses separated by commas:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected],[email protected],[email protected]"));

message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("[email protected],[email protected],[email protected]"));

works fine with only one address too

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));

How to split a comma-separated string?

You can split it and make an array then access like array

String names = "prappo,prince";
String[] namesList = names.split(",");

you can access like

String name1 = namesList [0];
String name2 = namesList [1];

or using loop

for(String name : namesList){
System.out.println(name);
}

hope it will help you .

Spring-boot default profile for integration tests

To activate "test" profile write in your build.gradle:

    test.doFirst {
        systemProperty 'spring.profiles.active', 'test'
        activeProfiles = 'test'
    }

jQuery click function doesn't work after ajax call?

Since the class is added dynamically, you need to use event delegation to register the event handler like:

$('#LangTable').on('click', '.deletelanguage', function(event) {
    event.preventDefault();
    alert("success");
});

This will attach your event to any anchors within the #LangTable element, reducing the scope of having to check the whole document element tree and increasing efficiency.

FIDDLE DEMO

Extend contigency table with proportions (percentages)

Your code doesn't seem so ugly to me...
however, an alternative (not much better) could be e.g. :

df <- data.frame(table(yn))
colnames(df) <- c('Smoker','Freq')
df$Perc <- df$Freq / sum(df$Freq) * 100

------------------
  Smoker Freq Perc
1     No   19 47.5
2    Yes   21 52.5

XmlSerializer giving FileNotFoundException at constructor

In Visual Studio project properties there is an option saying "generate serialization assembly". Try turning it on for a project that generates [Containing Assembly of MyType].

Change Title of Javascript Alert

You can't. The alert is a simple popup where you only can affect the content text.

If you want to change anything else, you have to use a different way of creating a popup.

Radio Buttons "Checked" Attribute Not Working

Radio inputs must be inside of a form for 'checked' to work.

HTML embedded PDF iframe

If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:

<object data="your_url_to_pdf" type="application/pdf">
    <iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>

Writing handler for UIAlertAction

In Swift 4 :

let alert=UIAlertController(title:"someAlert", message: "someMessage", preferredStyle:UIAlertControllerStyle.alert )

alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
        _ in print("FOO ")
}))

present(alert, animated: true, completion: nil)

jQuery/Javascript function to clear all the fields of a form

I use following solution:

1) Setup Jquery Validation Plugin

2) Then:

$('your form's selector').resetForm();

MySQL selecting yesterday's date

You can use:

SELECT SUBDATE(NOW(), 1);

or

SELECT SUBDATE(NOW(), INTERVAL 1 DAY);

or

SELECT NOW() - INTERVAL 1 DAY;

or

SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);

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

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

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

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

Google maps API V3 method fitBounds()

This happens because LatLngBounds() does not take two arbitrary points as parameters, but SW and NE points

use the .extend() method on an empty bounds object

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

Demo at http://jsfiddle.net/gaby/22qte/

Windows.history.back() + location.reload() jquery

window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh

window.history.back()
window.location.reload()

However a real complete solution would be as follows: I wrote a service to keep track of previous page and then navigate to that page with reload:true

Here is how i did it.

'use strict';

angular.module('tryme5App')
    .factory('RouterTracker', function RouterTracker($rootScope) {
          var routeHistory = [];
          var service = {
            getRouteHistory: getRouteHistory
          };

          $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
              routeHistory = [];
              routeHistory.push({route: from, routeParams: fromParams});
          });

          function getRouteHistory() {
            return routeHistory;
          }

          return service;       
    });

Make sure you have included this js file from you index.html

<script src="scripts/components/util/route.service.js"></script>

Now from you stateprovider or controller you can access this service and navigate

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });

or alternatively even perform checks and conditional routing

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
      $state.go('seat', null, { reload: true });
} else {
      window.history.back()
}

Make sure you have added RouterTracker as an argument in your function in my case it was :

.state('seat.new', {
                parent: 'seat',
                url: '/new',
                data: {
                    authorities: ['ROLE_USER'],
                },
                onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
  $uibModal.open({
      //....Open dialog.....
 }).result.then(function(result) {
            var routeHistory = RouterTracker.getRouteHistory();    
            console.log(routeHistory[0].route.name)
            $state.go(routeHistory[0].route.name, null, { reload: true });
 }, function() {
                    $state.go('^');
 })

Java - Check if JTextField is empty or not

Well, the code that renders the button enabled/disabled:

if(name.getText().equals("")) {
    loginbt.setEnabled(false);
}else {
    loginbt.setEnabled(true);
}

must be written in javax.swing.event.ChangeListener and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?

How to pass anonymous types as parameters?

You can do it like this:

public void LogEmployees<T>(List<T> list) // Or IEnumerable<T> list
{
    foreach (T item in list)
    {

    }
}

... but you won't get to do much with each item. You could call ToString, but you won't be able to use (say) Name and Id directly.

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

in my case my arraylist trhows me that error with the JSONObject , but i fin this solution for my array of String objects

List<String> listStrings= new ArrayList<String>();
String json = new Gson().toJson(listStrings);
return json;

Works like charm with angular Gson version 2.8.5

sort files by date in PHP

An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.

$output = array();
foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {      
        if ( $value->isFile() ) {
            $output[] = array( $value->getMTime(), $value->getRealPath() );
        }
}

usort ( $output, function( $a, $b ) {
    return $a[0] > $b[0];
});

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

How to create unique keys for React elements?

Keys helps React identify which items have changed/added/removed and should be given to the elements inside the array to give the elements a stable identity.

With that in mind, there are basically three different strategies as described bellow:

  1. Static Elements (when you don't need to keep html state (focus, cursor position, etc)
  2. Editable and sortable elements
  3. Editable but not sortable elements

As React Documentation explains, we need to give stable identity to the elements and because of that, carefully choose the strategy that best suits your needs:

STATIC ELEMENTS

As we can see also in React Documentation, is not recommended the use of index for keys "if the order of items may change. This can negatively impact performance and may cause issues with component state".

In case of static elements like tables, lists, etc, I recommend using a tool called shortid.

1) Install the package using NPM/YARN:

npm install shortid --save

2) Import in the class file you want to use it:

import shortid from 'shortid';

2) The command to generate a new id is shortid.generate().

3) Example:

  renderDropdownItems = (): React.ReactNode => {
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={shortid.generate()}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

IMPORTANT: As React Virtual DOM relies on the key, with shortid every time the element is re-rendered a new key will be created and the element will loose it's html state like focus or cursor position. Consider this when deciding how the key will be generated as the strategy above can be useful only when you are building elements that won't have their values changed like lists or read only fields.

EDITABLE (sortable) FIELDS

If the element is sortable and you have a unique ID of the item, combine it with some extra string (in case you need to have the same information twice in a page). This is the most recommended scenario.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${item.id}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

EDITABLE (non sortable) FIELDS (e.g. INPUT ELEMENTS)

As a last resort, for editable (but non sortable) fields like input, you can use some the index with some starting text as element key cannot be duplicated.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach((item:any index:number) => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${index}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

Hope this helps.

How do you debug React Native?

Instead of Cmd+M, for Android Emulator Press F10 in Windows. The emulator starts to show all the react-native debug options.

image

Creating a dynamic choice field

you can filter the waypoints by passing the user to the form init

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        )

from your view while initiating the form pass the user

form = waypointForm(user)

in case of model form

class waypointForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(
            queryset=Waypoint.objects.filter(user=user)
        )

    class Meta:
        model = Waypoint

Multiple inheritance for an anonymous class

I guess nobody understood the question. I guess what this guy wanted was something like this:

return new (class implements MyInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }
});

because this would allow things like multiple interface implementations:

return new (class implements MyInterface, AnotherInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }

    @Override
    public void anotherInterfaceMethod() { /*do something*/ }
});

this would be really nice indeed; but that's not allowed in Java.

What you can do is use local classes inside method blocks:

public AnotherInterface createAnotherInterface() {
    class LocalClass implements MyInterface, AnotherInterface {
        @Override
        public void myInterfaceMethod() { /*do something*/ }

        @Override
        public void anotherInterfaceMethod() { /*do something*/ }
    }
    return new LocalClass();
}

Objective-C ARC: strong vs retain and weak vs assign

From the Transitioning to ARC Release Notes (the example in the section on property attributes).

// The following declaration is a synonym for: @property(retain) MyClass *myObject;

@property(strong) MyClass *myObject;

So strong is the same as retain in a property declaration.

For ARC projects I would use strong instead of retain, I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Oracle - What TNS Names file am I using?

Not direct answer to your question, but I've been quite frustrated myself trying find and update all of the tnsnames files, as I had several oracle installs: Client, BI tools, OWB, etc, each of which had its own oracle home. I ended up creating a utility called TNSNamesSync that will update all of the tnsnames in all of the oracle homes. It's under the MIT license, free to use here https://github.com/artybug/TNSNamesSync/releases

The docs are here: https://github.com/artchik/TNSNamesSync/blob/master/README.md

This is for Windows only, though.

How to do a simple file search in cmd

dir /b/s *.txt  

searches for all txt file in the directory tree. Before using it just change the directory to root using

cd/

you can also export the list to a text file using

dir /b/s *.exe >> filelist.txt

and search within using

type filelist.txt | find /n "filename"

EDIT 1: Although this dir command works since the old dos days but Win7 added something new called Where

where /r c:\Windows *.exe *.dll

will search for exe & dll in the drive c:\Windows as suggested by @SPottuit you can also copy the output to the clipboard with

where /r c:\Windows *.exe |clip

just wait for the prompt to return and don't copy anything until then.

EDIT 2: If you are searching recursively and the output is big you can always use more to enable paging, it will show -- More -- at the bottom and will scroll to the next page once you press SPACE or moves line by line on pressing ENTER

where /r c:\Windows *.exe |more

For more help try

where/?

Include CSS,javascript file in Yii Framework

This was also an easy way to add script and css in main.php

<script src="<?=Yii::app()->theme->baseUrl; ?>/js/bootstrap.min.js"></script>
<link href="<?=Yii::app()->theme->baseUrl; ?>/css/bootstrap.css" rel="stylesheet" type="text/css">

Python error "ImportError: No module named"

Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

How to remove an element from the flow?

There's display: none, but I think that might be a bit more than what you're looking for.

add new row in gridview after binding C#, ASP.net

protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
   {
      GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
      for (int i = 0; i < e.Row.Cells.Count; i++)
      {
         TableCell tCell = new TableCell();
         tCell.Text = "&nbsp;";
         gvRow.Cells.Add(tCell);
         Table tbl = e.Row.Parent as Table;
         tbl.Rows.Add(gvRow);
      }
   }
}

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

Failed to execute 'createObjectURL' on 'URL':

My code was broken because I was using a deprecated technique. It used to be this:

video.src = window.URL.createObjectURL(localMediaStream);
video.play();

Then I replaced that with this:

video.srcObject = localMediaStream;
video.play();

That worked beautifully.

EDIT: Recently localMediaStream has been deprecated and replaced with MediaStream. The latest code looks like this:

video.srcObject = new MediaStream();

References:

  1. Deprecated technique: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
  2. Modern deprecated technique: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
  3. Modern technique: https://developer.mozilla.org/en-US/docs/Web/API/MediaStream

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

SQL alias for SELECT statement

You can do this using the WITH clause of the SELECT statement:

;
WITH my_select As (SELECT ... FROM ...) 
SELECT * FROM foo
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)

That's the ANSI/ISO SQL Syntax. I know that SQL Server, Oracle and DB2 support it. Not sure about the others...

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

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

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

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

public static class MyExtension
{
    public static string ToPrettySize(this float Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    public static string ToPrettySize(this int Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    private static string ConvertToPrettySize(float Size, int R)
    {
        float F = Size / 1024f;
        if (F < 1)
        {
            switch (R)
            {
                case 0:
                    return string.Format("{0:0.00} byte", Size);
                case 1:
                    return string.Format("{0:0.00} kb", Size);
                case 2:
                    return string.Format("{0:0.00} mb", Size);
                case 3:
                    return string.Format("{0:0.00} gb", Size);
            }
        }
        return ConvertToPrettySize(F, ++R);
    }
}

Why does ASP.NET webforms need the Runat="Server" attribute?

If you use it on normal html tags, it means that you can programatically manipulate them in event handlers etc, eg change the href or class of an anchor tag on page load... only do that if you have to, because vanilla html tags go faster.

As far as user controls and server controls, no, they just wont work without them, without having delved into the innards of the aspx preprocessor, couldn't say exactly why, but would take a guess that for probably good reasons, they just wrote the parser that way, looking for things explicitly marked as "do something".

If @JonSkeet is around anywhere, he will probably be able to provide a much better answer.

OnItemCLickListener not working in listview

  1. Add this in main Layout

    android:descendantFocusability="blocksDescendants"
    
  2. Write this code into every button,Textview,ImageView etc which have onClick

    android:focusable="false"
    
    android:clickable="false"
    

Hope it will work.

Output first 100 characters in a string

String formatting using % is a great way to handle this. Here are some examples.

The formatting code '%s' converts '12345' to a string, but it's already a string.

>>> '%s' % '12345'

'12345'

'%.3s' specifies to use only the first three characters.

>>> '%.3s' % '12345'

'123'

'%.7s' says to use the first seven characters, but there are only five. No problem.

>>> '%.7s' % '12345'

'12345'

'%7s' uses up to seven characters, filling missing characters with spaces on the left.

>>> '%7s' % '12345'

'  12345'

'%-7s' is the same thing, except filling missing characters on the right.

>>> '%-7s' % '12345'

'12345  '

'%5.3' says use the first three characters, but fill it with spaces on the left to total five characters.

>>> '%5.3s' % '12345'

'  123'

Same thing except filling on the right.

>>> '%-5.3s' % '12345'

'123  '

Can handle multiple arguments too!

>>> 'do u no %-4.3sda%3.2s wae' % ('12345', 6789)

'do u no 123 da 67 wae'

If you require even more flexibility, str.format() is available too. Here is documentation for both.

Waiting for background processes to finish before exiting script

WARNING: Long script ahead.

A while ago, I faced a similar problem: from a Tcl script, launch a number of processes, then wait for all of them to finish. Here is a demo script I wrote to solve this problem.

main.tcl

#!/usr/bin/env tclsh

# Launches many processes and wait for them to finish.
# This script will works on systems that has the ps command such as
# BSD, Linux, and OS X

package require Tclx; # For process-management utilities

proc updatePidList {stat} {
    global pidList
    global allFinished

    # Parse the process ID of the just-finished process
    lassign $stat processId howProcessEnded exitCode

    # Remove this process ID from the list of process IDs
    set pidList [lindex [intersect3 $pidList $processId] 0]
    set processCount [llength $pidList]

    # Occasionally, a child process quits but the signal was lost. This
    # block of code will go through the list of remaining process IDs
    # and remove those that has finished
    set updatedPidList {}
    foreach pid $pidList {
        if {![catch {exec ps $pid} errmsg]} {
            lappend updatedPidList $pid
        }
    }

    set pidList $updatedPidList

    # Show the remaining processes
    if {$processCount > 0} {
        puts "Waiting for [llength $pidList] processes"
    } else {
        set allFinished 1
        puts "All finished"
    }
}

# A signal handler that gets called when a child process finished.
# This handler needs to exit quickly, so it delegates the real works to
# the proc updatePidList
proc childTerminated {} {
    # Restart the handler
    signal -restart trap SIGCHLD childTerminated

    # Update the list of process IDs
    while {![catch {wait -nohang} stat] && $stat ne {}} {
        after idle [list updatePidList $stat]
    }
}

#
# Main starts here
#

puts "Main begins"
set NUMBER_OF_PROCESSES_TO_LAUNCH 10
set pidList {}
set allFinished 0

# When a child process exits, call proc childTerminated
signal -restart trap SIGCHLD childTerminated

# Spawn many processes
for {set i 0} {$i < $NUMBER_OF_PROCESSES_TO_LAUNCH} {incr i} {
    set childId [exec tclsh child.tcl $i &]
    puts "child #$i, pid=$childId"
    lappend pidList $childId
    after 1000
}

# Do some processing
puts "list of processes: $pidList"
puts "Waiting for child processes to finish"
# Do some more processing if required

# After all done, wait for all to finish before exiting
vwait allFinished

puts "Main ends"

child.tcl

#!/usr/bin/env tclsh
# child script: simulate some lengthy operations

proc randomInteger {min max} {
    return [expr int(rand() * ($max - $min + 1) * 1000 + $min)]
}

set duration [randomInteger 10 30]
puts "  child #$argv runs for $duration miliseconds"
after $duration
puts "  child #$argv ends"

Sample output for running main.tcl

Main begins
child #0, pid=64525
  child #0 runs for 17466 miliseconds
child #1, pid=64526
  child #1 runs for 14181 miliseconds
child #2, pid=64527
  child #2 runs for 10856 miliseconds
child #3, pid=64528
  child #3 runs for 7464 miliseconds
child #4, pid=64529
  child #4 runs for 4034 miliseconds
child #5, pid=64531
  child #5 runs for 1068 miliseconds
child #6, pid=64532
  child #6 runs for 18571 miliseconds
  child #5 ends
child #7, pid=64534
  child #7 runs for 15374 miliseconds
child #8, pid=64535
  child #8 runs for 11996 miliseconds
  child #4 ends
child #9, pid=64536
  child #9 runs for 8694 miliseconds
list of processes: 64525 64526 64527 64528 64529 64531 64532 64534 64535 64536
Waiting for child processes to finish
Waiting for 8 processes
Waiting for 8 processes
  child #3 ends
Waiting for 7 processes
  child #2 ends
Waiting for 6 processes
  child #1 ends
Waiting for 5 processes
  child #0 ends
Waiting for 4 processes
  child #9 ends
Waiting for 3 processes
  child #8 ends
Waiting for 2 processes
  child #7 ends
Waiting for 1 processes
  child #6 ends
All finished
Main ends

Array versus List<T>: When to use which?

Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."

You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.

Python: PIP install path, what is the correct location for this and other addons?

Also, when you uninstall the package, the first item listed is the directory to the executable.

In C#, what is the difference between public, private, protected, and having no access modifier?

Regarding the question of Nothing

  • Namespace types are internal by default
  • Any type member, including nested types are private by default

How to pass arguments and redirect stdin from a file to program run in gdb?

Start GDB on your project.

  1. Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:

    gdb projectExecutablename

This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)

  1. Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:

    (gdb) b main

  2. Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:

    (gdb) r mulder/xfiles

Hope this helps.

Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.

How to create a function in SQL Server

You can use stuff in place of replace for avoiding the bug that Hamlet Hakobyan has mentioned

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250)) 
RETURNS VARCHAR(250) 
AS BEGIN
   DECLARE @Work VARCHAR(250)
   SET @Work = @Input

   --SET @Work = REPLACE(@Work, 'www.', '')
   SET @Work = Stuff(@Work,1,4, '')
   SET @Work = REPLACE(@Work, '.com', '')

   RETURN @work 
END

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

Changing MongoDB data store directory

I found a special case that causes symlinks to appear to fail:

I did a standard enterprise install of mongodb but changed the /var/lib/mongodb to a symlink as I wanted to use an XFS filesystem for my database folder and a third filesystem for the log folder.

$sudo systemctl start mongod (fails with a message no permission to write to mongodb.log).. but it succceded if I started with the same configuration file:

.. as the owner of the external drives (ziggy) I was able to start $mongod --config /etc/mongodb.conf --fork

I eventually discovered that .. the symlinks pointed to a different filesystem and the mongodb (user) did not have permission to browse the folder that the symlink referred. Both the symlinks and the folders the symlinks referred had expansive rights to the mongod user so it made no sense?

/var/log/mongodb was changed (from the std ent install) to a symlink AND I had checked before:

$ ll /var/log/mongodb lrwxrwxrwx 1 mongodb mongodb 38 Oct 28 21:58 /var/log/mongodb -> /media/ziggy/XFS_DB/mongodb/log/

$ ll -d /media/ziggy/Ext4DataBase/mongodb/log drwxrwxrwx 2 mongodb mongodb 4096 Nov 1 12:05 /media/ashley/XFS_DB/mongodb/log/

.. But so it seemed to make no sense.. of course user mongodb had rwx access to the link, the folder and to the file mongodb.log .. but it couldnt find it via the symlink because the BASE folder of the media couldnt be searched by mongodb.

SO.. I EVENTUALLY DID THIS: $ ll /media/ziggy/ . . drwx------ 5 ziggy ziggy 4096 Oct 28 21:49 XFS_DB/

and found the offending missing x permissions..

$chmod a+x /media/ziggy/XFS_DB solved the problem

Seems stupid in hindsight but no searches turned up anything useful.

How to run a specific Android app using Terminal?

I keep this build-and-run script handy, whenever I am working from command line:

#!/usr/bin/env bash

PACKAGE=com.example.demo
ACTIVITY=.MainActivity
APK_LOCATION=app/build/outputs/apk/app-debug.apk
echo "Package: $PACKAGE"

echo "Building the project with tasks: $TASKS"
./gradlew $TASKS

echo "Uninstalling $PACKAGE"
adb uninstall $PACKAGE

echo "Installing $APK_LOCATION"
adb install $APK_LOCATION

echo "Starting $ACTIVITY"
adb shell am start -n $PACKAGE/$ACTIVITY

The import com.google.android.gms cannot be resolved

Above solutions should solve your problem. If these do not, make sure you update your Android sdk using SDK manager and install the latest lib project and then repeat the above steps again.

substring index range

See the javadoc. It's an inclusive index for the first argument and exclusive for the second.

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

android ellipsize multiline textview

I combined the solutions by Micah Hainline, Alex Balu?, and Paul Imhoff to create an ellipsizing multiline TextView that also supports Spanned text.

You only need to set android:ellipsize and android:maxLines.

/*
 * Copyright (C) 2011 Micah Hainline
 * Copyright (C) 2012 Triposo
 * Copyright (C) 2013 Paul Imhoff
 * Copyright (C) 2014 Shahin Yousefi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class EllipsizingTextView extends TextView {
    private static final CharSequence ELLIPSIS = "\u2026";
    private static final Pattern DEFAULT_END_PUNCTUATION
            = Pattern.compile("[\\.!?,;:\u2026]*$", Pattern.DOTALL);
    private final List<EllipsizeListener> mEllipsizeListeners = new ArrayList<>();
    private EllipsizeStrategy mEllipsizeStrategy;
    private boolean isEllipsized;
    private boolean isStale;
    private boolean programmaticChange;
    private CharSequence mFullText;
    private int mMaxLines;
    private float mLineSpacingMult = 1.0f;
    private float mLineAddVertPad = 0.0f;

    private Pattern mEndPunctPattern;

    public EllipsizingTextView(Context context) {
        this(context, null);
    }


    public EllipsizingTextView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }


    public EllipsizingTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs,
                new int[]{ android.R.attr.maxLines }, defStyle, 0);
        setMaxLines(a.getInt(0, Integer.MAX_VALUE));
        a.recycle();
        setEndPunctuationPattern(DEFAULT_END_PUNCTUATION);
    }

    public void setEndPunctuationPattern(Pattern pattern) {
        mEndPunctPattern = pattern;
    }

    public void addEllipsizeListener(@NonNull EllipsizeListener listener) {
        mEllipsizeListeners.add(listener);
    }

    public void removeEllipsizeListener(EllipsizeListener listener) {
        mEllipsizeListeners.remove(listener);
    }

    public boolean isEllipsized() {
        return isEllipsized;
    }

    @SuppressLint("Override")
    public int getMaxLines() {
        return mMaxLines;
    }

    @Override
    public void setMaxLines(int maxLines) {
        super.setMaxLines(maxLines);
        mMaxLines = maxLines;
        isStale = true;
    }

    public boolean ellipsizingLastFullyVisibleLine() {
        return mMaxLines == Integer.MAX_VALUE;
    }

    @Override
    public void setLineSpacing(float add, float mult) {
        mLineAddVertPad = add;
        mLineSpacingMult = mult;
        super.setLineSpacing(add, mult);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (!programmaticChange) {
            mFullText = text;
            isStale = true;
        }
        super.setText(text, type);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (ellipsizingLastFullyVisibleLine()) isStale = true;
    }

    @Override
    public void setPadding(int left, int top, int right, int bottom) {
        super.setPadding(left, top, right, bottom);
        if (ellipsizingLastFullyVisibleLine()) isStale = true;
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        if (isStale) resetText();
        super.onDraw(canvas);
    }

    private void resetText() {
        int maxLines = getMaxLines();
        CharSequence workingText = mFullText;
        boolean ellipsized = false;

        if (maxLines != -1) {
            if (mEllipsizeStrategy == null) setEllipsize(null);
            workingText = mEllipsizeStrategy.processText(mFullText);
            ellipsized = !mEllipsizeStrategy.isInLayout(mFullText);
        }

        if (!workingText.equals(getText())) {
            programmaticChange = true;
            try {
                setText(workingText);
            } finally {
                programmaticChange = false;
            }
        }

        isStale = false;
        if (ellipsized != isEllipsized) {
            isEllipsized = ellipsized;
            for (EllipsizeListener listener : mEllipsizeListeners) {
                listener.ellipsizeStateChanged(ellipsized);
            }
        }
    }

    @Override
    public void setEllipsize(TruncateAt where) {
        if (where == null) {
            mEllipsizeStrategy = new EllipsizeNoneStrategy();
            return;
        }

        switch (where) {
            case END:
                mEllipsizeStrategy = new EllipsizeEndStrategy();
                break;
            case START:
                mEllipsizeStrategy = new EllipsizeStartStrategy();
                break;
            case MIDDLE:
                mEllipsizeStrategy = new EllipsizeMiddleStrategy();
                break;
            case MARQUEE:
                super.setEllipsize(where);
                isStale = false;
            default:
                mEllipsizeStrategy = new EllipsizeNoneStrategy();
                break;
        }
    }

    public interface EllipsizeListener {
        void ellipsizeStateChanged(boolean ellipsized);
    }

    private abstract class EllipsizeStrategy {
        public CharSequence processText(CharSequence text) {
            return !isInLayout(text) ? createEllipsizedText(text) : text;
        }

        public boolean isInLayout(CharSequence text) {
            Layout layout = createWorkingLayout(text);
            return layout.getLineCount() <= getLinesCount();
        }

        protected Layout createWorkingLayout(CharSequence workingText) {
            return new StaticLayout(workingText, getPaint(),
                    getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
                    Alignment.ALIGN_NORMAL, mLineSpacingMult,
                    mLineAddVertPad, false /* includepad */);
        }

        protected int getLinesCount() {
            if (ellipsizingLastFullyVisibleLine()) {
                int fullyVisibleLinesCount = getFullyVisibleLinesCount();
                return fullyVisibleLinesCount == -1 ? 1 : fullyVisibleLinesCount;
            } else {
                return mMaxLines;
            }
        }

        protected int getFullyVisibleLinesCount() {
            Layout layout = createWorkingLayout("");
            int height = getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
            int lineHeight = layout.getLineBottom(0);
            return height / lineHeight;
        }

        protected abstract CharSequence createEllipsizedText(CharSequence fullText);
    }

    private class EllipsizeNoneStrategy extends EllipsizeStrategy {
        @Override
        protected CharSequence createEllipsizedText(CharSequence fullText) {
            return fullText;
        }
    }

    private class EllipsizeEndStrategy extends EllipsizeStrategy {
        @Override
        protected CharSequence createEllipsizedText(CharSequence fullText) {
            Layout layout = createWorkingLayout(fullText);
            int cutOffIndex = layout.getLineEnd(mMaxLines - 1);
            int textLength = fullText.length();
            int cutOffLength = textLength - cutOffIndex;
            if (cutOffLength < ELLIPSIS.length()) cutOffLength = ELLIPSIS.length();
            String workingText = TextUtils.substring(fullText, 0, textLength - cutOffLength).trim();
            String strippedText = stripEndPunctuation(workingText);

            while (!isInLayout(strippedText + ELLIPSIS)) {
                int lastSpace = workingText.lastIndexOf(' ');
                if (lastSpace == -1) break;
                workingText = workingText.substring(0, lastSpace).trim();
                strippedText = stripEndPunctuation(workingText);
            }

            workingText = strippedText + ELLIPSIS;
            SpannableStringBuilder dest = new SpannableStringBuilder(workingText);

            if (fullText instanceof Spanned) {
                TextUtils.copySpansFrom((Spanned) fullText, 0, workingText.length(), null, dest, 0);
            }
            return dest;
        }

        public String stripEndPunctuation(CharSequence workingText) {
            return mEndPunctPattern.matcher(workingText).replaceFirst("");
        }
    }

    private class EllipsizeStartStrategy extends EllipsizeStrategy {
        @Override
        protected CharSequence createEllipsizedText(CharSequence fullText) {
            Layout layout = createWorkingLayout(fullText);
            int cutOffIndex = layout.getLineEnd(mMaxLines - 1);
            int textLength = fullText.length();
            int cutOffLength = textLength - cutOffIndex;
            if (cutOffLength < ELLIPSIS.length()) cutOffLength = ELLIPSIS.length();
            String workingText = TextUtils.substring(fullText, cutOffLength, textLength).trim();

            while (!isInLayout(ELLIPSIS + workingText)) {
                int firstSpace = workingText.indexOf(' ');
                if (firstSpace == -1) break;
                workingText = workingText.substring(firstSpace, workingText.length()).trim();
            }

            workingText = ELLIPSIS + workingText;
            SpannableStringBuilder dest = new SpannableStringBuilder(workingText);

            if (fullText instanceof Spanned) {
                TextUtils.copySpansFrom((Spanned) fullText, textLength - workingText.length(),
                        textLength, null, dest, 0);
            }
            return dest;
        }
    }

    private class EllipsizeMiddleStrategy extends EllipsizeStrategy {
        @Override
        protected CharSequence createEllipsizedText(CharSequence fullText) {
            Layout layout = createWorkingLayout(fullText);
            int cutOffIndex = layout.getLineEnd(mMaxLines - 1);
            int textLength = fullText.length();
            int cutOffLength = textLength - cutOffIndex;
            if (cutOffLength < ELLIPSIS.length()) cutOffLength = ELLIPSIS.length();
            cutOffLength += cutOffIndex % 2;    // Make it even.
            String firstPart = TextUtils.substring(
                    fullText, 0, textLength / 2 - cutOffLength / 2).trim();
            String secondPart = TextUtils.substring(
                    fullText, textLength / 2 + cutOffLength / 2, textLength).trim();

            while (!isInLayout(firstPart + ELLIPSIS + secondPart)) {
                int lastSpaceFirstPart = firstPart.lastIndexOf(' ');
                int firstSpaceSecondPart = secondPart.indexOf(' ');
                if (lastSpaceFirstPart == -1 || firstSpaceSecondPart == -1) break;
                firstPart = firstPart.substring(0, lastSpaceFirstPart).trim();
                secondPart = secondPart.substring(firstSpaceSecondPart, secondPart.length()).trim();
            }

            SpannableStringBuilder firstDest = new SpannableStringBuilder(firstPart);
            SpannableStringBuilder secondDest = new SpannableStringBuilder(secondPart);

            if (fullText instanceof Spanned) {
                TextUtils.copySpansFrom((Spanned) fullText, 0, firstPart.length(),
                        null, firstDest, 0);
                TextUtils.copySpansFrom((Spanned) fullText, textLength - secondPart.length(),
                        textLength, null, secondDest, 0);
            }
            return TextUtils.concat(firstDest, ELLIPSIS, secondDest);
        }
    }
}

Complete source: EllipsizingTextView.java

How to validate Google reCAPTCHA v3 on server side?

this is solution

index.html

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
      <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
    </form>
  </body>
</html>

verify.php

<?php
    $email; $comment; $captcha;

    if(isset($_POST['email']))
        $email=$_POST['email'];
    if(isset($_POST['comment']))
        $comment=$_POST['comment'];
    if(isset($_POST['g-recaptcha-response']))
        $captcha=$_POST['g-recaptcha-response'];

    if(!$captcha){
        echo '<h2>Please check the the captcha form.</h2>';
        exit;
    }

    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
    {
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
    }
    else
    {
        echo '<h2>Thanks for posting comment.</h2>';
    }
?>

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/

Generating a Random Number between 1 and 10 Java

The standard way to do this is as follows:

Provide:

  • min Minimum value
  • max Maximum value

and get in return a Integer between min and max, inclusive.

Random rand = new Random();

// nextInt as provided by Random is exclusive of the top value so you need to add 1 

int randomNum = rand.nextInt((max - min) + 1) + min;

See the relevant JavaDoc.

As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.

Is there a simple way to remove multiple spaces in a string?

def unPretty(S):
   # Given a dictionary, JSON, list, float, int, or even a string...
   # return a string stripped of CR, LF replaced by space, with multiple spaces reduced to one.
   return ' '.join(str(S).replace('\n', ' ').replace('\r', '').split())

Creating a PHP header/footer

Besides just using include() or include_once() to include the header and footer, one thing I have found useful is being able to have a custom page title or custom head tags to be included for each page, yet still have the header in a partial include. I usually accomplish this as follows:

In the site pages:

<?php

$PageTitle="New Page Title";

function customPageHeader(){?>
  <!--Arbitrary HTML Tags-->
<?php }

include_once('header.php');

//body contents go here

include_once('footer.php');
?>

And, in the header.php file:

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title><?= isset($PageTitle) ? $PageTitle : "Default Title"?></title>
    <!-- Additional tags here -->
    <?php if (function_exists('customPageHeader')){
      customPageHeader();
    }?>
  </head>
  <body>

Maybe a bit beyond the scope of your original question, but it is useful to allow a bit more flexibility with the include.

OSError - Errno 13 Permission denied

Simply try:

sudo cp /source /destination

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Usage of $broadcast(), $emit() And $on() in AngularJS

This little example shows how the $rootScope emit a event that will be listen by a children scope in another controller.

(function(){


angular
  .module('ExampleApp',[]);

angular
  .module('ExampleApp')
  .controller('ExampleController1', Controller1);

Controller1.$inject = ['$rootScope'];

function Controller1($rootScope) {
  var vm = this, 
      message = 'Hi my children scope boy';

  vm.sayHi = sayHi;

  function sayHi(){
    $rootScope.$broadcast('greeting', message);
  }

}

angular
  .module('ExampleApp')
  .controller('ExampleController2', Controller2);

Controller2.$inject = ['$scope'];

function Controller2($scope) {
  var vm = this;

  $scope.$on('greeting', listenGreeting)

  function listenGreeting($event, message){
    alert(['Message received',message].join(' : '));
  }

}


})();

http://codepen.io/gpincheiraa/pen/xOZwqa

The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope and $rootScope.

No mapping found for HTTP request with URI Spring MVC

First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.

If not you have some compilation errors in your java classes.

Linux find and grep command together

Now that the question is clearer, you can just do this in one

grep -R --include "*bills*" "put" .

With relevant flags

   -R, -r, --recursive
          Read  all  files  under  each  directory,  recursively;  this is
          equivalent to the -d recurse option.
   --include=GLOB
          Search only files whose base name matches GLOB  (using  wildcard
          matching as described under --exclude).

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I got this error message because I had a different user than what the repo expected in my git config.

This would obviously trigger the SSL Cert failures mentioned above.

Fixing to the correct user resolved this issue for me.

Dockerfile copy keep subdirectory structure

If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.

COPY . destinatio-directory/ 

How to push both value and key into PHP array

array_push($GET, $GET['one']=1);

It works for me.

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

Tab space instead of multiple non-breaking spaces ("nbsp")?

It depends on which character set you want to use.

There's no tab entity defined in ISO-8859-1 HTML - but there are a couple of whitespace characters other than &nbsp; such as &thinsp;, &ensp;,and &emsp;.

In ASCII, &#09; is a tab.

Here is a complete listing of HTML entities and a useful discussion of whitespace on Wikipedia.

How do I serialize an object and save it to a file in Android?

I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:

Option1:

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();

Option2:

SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();

Option 2 is twice quicker than option 1

The option 2 inconvenience is that you have to make specific code for read:

Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
    events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);

How to display my location on Google Maps for Android API v2

Java code:

public class MapActivity extends FragmentActivity implements LocationListener  {

    GoogleMap googleMap;
    LatLng myPosition;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment)
        getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            // Getting latitude of the current location
            double latitude = location.getLatitude();

            // Getting longitude of the current location
            double longitude = location.getLongitude();

            // Creating a LatLng object for the current location
            LatLng latLng = new LatLng(latitude, longitude);

            myPosition = new LatLng(latitude, longitude);

            googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
        }
    }
}

activity_map.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:map="http://schemas.android.com/apk/res-auto"
  android:id="@+id/map"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  class="com.google.android.gms.maps.SupportMapFragment"/>

You will get your current location in a blue circle.

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

Ok found out the Tomcat file server.xml must be configured as well for the data source to work. So just add:

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
  />

What is WebKit and how is it related to CSS?

A good documentation about WebEngines especially webKit and its developers you can read at: WebKit

How to restart service using command prompt?

You can use sc start [service] to start a service and sc stop [service] to stop it. With some services net start [service] is doing the same.

But if you want to use it in the same batch, be aware that sc stop won't wait for the service to be stopped. In this case you have to use net stop [service] followed by net start [service]. This will be executed synchronously.

jquery click event not firing?

You need to prevent the default event (following the link), otherwise your link will load a new page:

    $(document).ready(function(){
        $('.play_navigation a').click(function(e){
            e.preventDefault();
            console.log("this is the click");
        });
    });

As pointed out in comments, if your link has no href, then it's not a link, use something else.

Not working? Your code is A MESS! and ready() events everywhere... clean it, put all your scripts in ONE ready event and then try again, it will very likely sort things out.

How to open a new file in vim in a new window

Check out gVim. You can launch that in its own window.

gVim makes it really easy to manage multiple open buffers graphically.

You can also do the usual :e to open a new file, CTRL+^ to toggle between buffers, etc...

Another cool feature lets you open a popup window that lists all the buffers you've worked on.

This allows you to switch between open buffers with a single click.

To do this, click on the Buffers menu at the top and click the dotted line with the scissors.

enter image description here

Otherwise you can just open a new tab from your terminal session and launch vi from there.

You can usually open a new tab from terminal with CTRL+T or CTRL+ALT+T

Once vi is launched, it's easy to open new files and switch between them.

How to know Hive and Hadoop versions from command prompt?

You can not get hive version from command line.

You can checkout hadoop version as mentioned by Dave.

Also if you are using cloudera distribution, then look directly at the libs:

ls /usr/lib/hive/lib/ and check for hive library

hive-hwi-0.7.1-cdh3u3.jar

You can also check the compatible versions here:

http://www.cloudera.com/content/cloudera/en/documentation/cdh5/v5-1-x/CDH-Version-and-Packaging-Information/CDH-Version-and-Packaging-Information.html

How to remove unused dependencies from composer?

following commands will do the same perfectly

rm -rf vendor

composer install 

Owl Carousel, making custom navigation

The following code works for me on owl carousel .

https://github.com/OwlFonk/OwlCarousel

$(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    navigation: true,
    navigationText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

For OwlCarousel2

https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html

 $(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    nav: true,
    navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Link to Flask static files with url_for

In my case I had special instruction into nginx configuration file:

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

All clients have received '404' because nginx nothing known about Flask.

I hope it help someone.

How can a LEFT OUTER JOIN return more records than exist in the left table?

It isn't impossible. The number of records in the left table is the minimum number of records it will return. If the right table has two records that match to one record in the left table, it will return two records.

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

Adding values to specific DataTable cells

I think you can't do that but atleast you can update it. In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.

Example,

DataSet1.Tables(0).Rows(4).Item(0) = "Updated Company Name"
DataSet1.Tables(0).Rows(4).Item(1) = "Seattle"

SOURCE HERE

How to redirect to an external URL in Angular2?

An Angular approach to the methods previously described is to import DOCUMENT from @angular/common (or @angular/platform-browser in Angular < 4) and use

document.location.href = 'https://stackoverflow.com';

inside a function.

some-page.component.ts

import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: Document) { }

goToUrl(): void {
    this.document.location.href = 'https://stackoverflow.com';
}

some-page.component.html

<button type="button" (click)="goToUrl()">Click me!</button>

Check out the plateformBrowser repo for more info.

How to print SQL statement in codeigniter model

use get_compiled_select() to retrieve query instead of replace it

Laravel Rule Validation for Numbers

Laravel min and max validation do not work properly with a numeric rule validation. Instead of numeric, min and max, Laravel provided a rule digits_between.

$this->validate($request,[
        'field_name'=>'digits_between:2,5',
       ]);

Parsing arguments to a Java command line program

I realize that the question mentions a preference for Commons CLI, but I guess that when this question was asked, there was not much choice in terms of Java command line parsing libraries. But nine years later, in 2020, would you not rather write code like the below?

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;

@Command(name = "myprogram", mixinStandardHelpOptions = true,
  description = "Does something useful.", version = "1.0")
public class MyProgram implements Callable<Integer> {

    @Option(names = "-r", description = "The r option") String rValue;
    @Option(names = "-S", description = "The S option") String sValue;
    @Option(names = "-A", description = "The A file") File aFile;
    @Option(names = "--test", description = "The test option") boolean test;
    @Parameters(description = "Positional params") List<String> positional;

    @Override
    public Integer call() {
        System.out.printf("-r=%s%n", rValue);
        System.out.printf("-S=%s%n", sValue);
        System.out.printf("-A=%s%n", aFile);
        System.out.printf("--test=%s%n", test);
        System.out.printf("positionals=%s%n", positional);
        return 0;
    }

    public static void main(String... args) {
        System.exit(new CommandLine(new MyProgram()).execute(args));
    }
}

Execute by running the command in the question:

java MyProgram -r opt1 -S opt2 arg1 arg2 arg3 arg4 --test -A opt3

What I like about this code is that it is:

  • compact - no boilerplate
  • declarative - using annotations instead of a builder API
  • strongly typed - annotated fields can be any type, not just String
  • no duplication - option declaration and getting parse result are together in the annotated field
  • clear - the annotations express the intention better than imperative code
  • separation of concerns - the business logic in the call method is free of parsing-related logic
  • convenient - one line of code in main wires up the parser and runs the business logic in the Callable
  • powerful - automatic usage and version help with the built-in --help and --version options
  • user-friendly - usage help message uses colors to contrast important elements like option names from the rest of the usage help to reduce the cognitive load on the user

The above functionality is only part of what you get when you use the picocli (https://picocli.info) library.

Now, bear in mind that I am totally, completely, and utterly biased, being the author of picocli. :-) But I do believe that in 2020 we have better alternatives for building a command line apps than Commons CLI.

How do you overcome the HTML form nesting limitation?

HTML5 has an idea of "form owner" - the "form" attribute for input elements. It allows to emulate nested forms and will solve the issue.

Add column to dataframe with constant value

Summing up what the others have suggested, and adding a third way

You can:

where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.

'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).

All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).

How to capitalize first letter of each word, like a 2-word city?

function convertCase(str) {
  var lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}

How to recover stashed uncommitted changes

To check your stash content :-

git stash list

apply a particular stash no from stash list:-

git stash apply stash@{2}

or for applying just the first stash:-

git stash pop

Note: git stash pop will remove the stash from your stash list whereas git stash apply wont. So use them accordingly.

How to sum array of numbers in Ruby?

Or try the Ruby 1.9 way:

array.inject(0, :+)

Note: the 0 base case is needed otherwise nil will be returned on empty arrays:

> [].inject(:+)
nil
> [].inject(0, :+)
0

SQL Server NOLOCK and joins

I won't address the READ UNCOMMITTED argument, just your original question.

Yes, you need WITH(NOLOCK) on each table of the join. No, your queries are not the same.

Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK) hint on it.

VBA code to set date format for a specific column as "yyyy-mm-dd"

It works, when you use both lines:

Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

How can I programmatically determine if my app is running in the iphone simulator?

All those answer are good, but it somehow confuses newbie like me as it does not clarify compile check and runtime check. Preprocessor are before compile time, but we should make it clearer

This blog article shows How to detect the iPhone simulator? clearly

Runtime

First of all, let’s shortly discuss. UIDevice provides you already information about the device

[[UIDevice currentDevice] model]

will return you “iPhone Simulator” or “iPhone” according to where the app is running.

Compile time

However what you want is to use compile time defines. Why? Because you compile your app strictly to be run either inside the Simulator or on the device. Apple makes a define called TARGET_IPHONE_SIMULATOR. So let’s look at the code :

#if TARGET_IPHONE_SIMULATOR

NSLog(@"Running in Simulator - no app store or giro");

#endif

Measure string size in Bytes in php

PHP's strlen() function returns the number of ASCII characters.

strlen('borsc') -> 5 (bytes)

strlen('boršc') -> 7 (bytes)

$limit_in_kBytes = 20000;

$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
    $str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
    // here you can handle (0 - n) parts of string
    $pointer++;
}

$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string

.. or you can use a function like this:

function parseStrToArr($string, $limit_in_kBytes){
    $ret = array();

    $pointer = 0;
    while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
        $ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
        $pointer++;
    }

    $ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);

    return $ret;
}

$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);

How to fix docker: Got permission denied issue

We always forget about ACLs . See setfacl.


sudo setfacl -m user:$USER:rw /var/run/docker.sock

Why can't static methods be abstract in Java?

  • An abstract method is defined only so that it can be overridden in a subclass. However, static methods can not be overridden. Therefore, it is a compile-time error to have an abstract, static method.

    Now the next question is why static methods can not be overridden??

  • It's because static methods belongs to a particular class and not to its instance. If you try to override a static method you will not get any compilation or runtime error but compiler would just hide the static method of superclass.

Maintain/Save/Restore scroll position when returning to a ListView

use this below code :

int index,top;

@Override
protected void onPause() {
    super.onPause();
    index = mList.getFirstVisiblePosition();

    View v = challengeList.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
}

and whenever your refresh your data use this below code :

adapter.notifyDataSetChanged();
mList.setSelectionFromTop(index, top);

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Syntax errors is not checked easily in external servers, just runtime errors.

What I do? Just like you, I use

ini_set('display_errors', 'On');
error_reporting(E_ALL);

However, before run I check syntax errors in a PHP file using an online PHP syntax checker.

The best, IMHO is PHP Code Checker

I copy all the source code, paste inside the main box and click the Analyze button.

It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely

how to make div click-able?

As you updated your question, here's an obtrustive example:

window.onload = function()
{
    var div = document.getElementById("mydiv");

    div.style.cursor = 'pointer';
    div.onmouseover = function()
    {
        div.style.background = "#ff00ff";
    };
}

".addEventListener is not a function" why does this error occur?

_x000D_
_x000D_
var comment = document.getElementsByClassName("button");_x000D_
_x000D_
function showComment() {_x000D_
  var place = document.getElementById('textfield');_x000D_
  var commentBox = document.createElement('textarea');_x000D_
  place.appendChild(commentBox);_x000D_
}_x000D_
_x000D_
for (var i in comment) {_x000D_
  comment[i].onclick = function() {_x000D_
    showComment();_x000D_
  };_x000D_
}
_x000D_
<input type="button" class="button" value="1">_x000D_
<input type="button" class="button" value="2">_x000D_
<div id="textfield"></div>
_x000D_
_x000D_
_x000D_

How do I run a Java program from the command line on Windows?

Complile a Java file to generate a class:

javac filename.java

Execute the generated class:

java filename

byte[] to file in Java

////////////////////////// 1] File to Byte [] ///////////////////

Path path = Paths.get(p);
                    byte[] data = null;                         
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                    }

/////////////////////// 2] Byte [] to File ///////////////////////////

 File f = new File(fileName);
 byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
                            try {
                                Files.write(path, fileContent);
                            } catch (IOException ex) {
                                Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
                            }

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

Error inflating class android.support.design.widget.NavigationView

I had the same error, I resolved it by adding app:itemTextColor="@color/a_color" to my navigation view :

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="left"
    app:headerLayout="@layout/layout_drawer_header"
    app:menu="@menu/drawer_menu"
    app:itemTextColor="@color/primary"/>

You can still use android:textColorPrimary and android:textColorSecondary in your theme with this method.

Check if image exists on server using JavaScript?

You can do this with your axios by setting relative path to the corresponding images folder. I have done this for getting a json file. You can try the same method for an image file, you may refer these examples

If you have already set an axios instance with baseurl as a server in different domain, you will have to use the full path of the static file server where you deploy the web application.

  axios.get('http://localhost:3000/assets/samplepic.png').then((response) => {
            console.log(response)
        }).catch((error) => {
            console.log(error)
        })

If the image is found the response will be 200 and if not, it will be 404.

Also, if the image file is present in assets folder inside src, you can do a require, get the path and do the above call with that path.

var SampleImagePath = require('./assets/samplepic.png');
axios.get(SampleImagePath).then(...)

How to download an entire directory and subdirectories using wget?

You may use this in shell:

wget -r --no-parent http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r     //recursive Download

and

--no-parent // Don´t download something from the parent directory

If you don't want to download the entire content, you may use:

-l1 just download the directory (tzivi in your case)

-l2 download the directory and all level 1 subfolders ('tzivi/something' but not 'tivizi/somthing/foo')  

And so on. If you insert no -l option, wget will use -l 5 automatically.

If you insert a -l 0 you´ll download the whole Internet, because wget will follow every link it finds.

When should iteritems() be used instead of items()?

Just as @Wessie noted, dict.iteritems, dict.iterkeys and dict.itervalues (which return an iterator in Python2.x) as well as dict.viewitems, dict.viewkeys and dict.viewvalues (which return view objects in Python2.x) were all removed in Python3.x

And dict.items, dict.keys and dict.values used to return a copy of the dictionary's list in Python2.x now return view objects in Python3.x, but they are still not the same as iterator.

If you want to return an iterator in Python3.x, use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

How to Find the Default Charset/Encoding in Java?

Is this a bug or feature?

Looks like undefined behaviour. I know that, in practice, you can change the default encoding using a command-line property, but I don't think what happens when you do this is defined.

Bug ID: 4153515 on problems setting this property:

This is not a bug. The "file.encoding" property is not required by the J2SE platform specification; it's an internal detail of Sun's implementations and should not be examined or modified by user code. It's also intended to be read-only; it's technically impossible to support the setting of this property to arbitrary values on the command line or at any other time during program execution.

The preferred way to change the default encoding used by the VM and the runtime system is to change the locale of the underlying platform before starting your Java program.

I cringe when I see people setting the encoding on the command line - you don't know what code that is going to affect.

If you do not want to use the default encoding, set the encoding you do want explicitly via the appropriate method/constructor.

pandas python how to count the number of records or rows in a dataframe

To get the number of rows in a dataframe use:

df.shape[0]

(and df.shape[1] to get the number of columns).

As an alternative you can use

len(df)

or

len(df.index)

(and len(df.columns) for the columns)

shape is more versatile and more convenient than len(), especially for interactive work (just needs to be added at the end), but len is a bit faster (see also this answer).

To avoid: count() because it returns the number of non-NA/null observations over requested axis

len(df.index) is faster

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(24).reshape(8, 3),columns=['A', 'B', 'C'])
df['A'][5]=np.nan
df
# Out:
#     A   B   C
# 0   0   1   2
# 1   3   4   5
# 2   6   7   8
# 3   9  10  11
# 4  12  13  14
# 5 NaN  16  17
# 6  18  19  20
# 7  21  22  23

%timeit df.shape[0]
# 100000 loops, best of 3: 4.22 µs per loop

%timeit len(df)
# 100000 loops, best of 3: 2.26 µs per loop

%timeit len(df.index)
# 1000000 loops, best of 3: 1.46 µs per loop

df.__len__ is just a call to len(df.index)

import inspect 
print(inspect.getsource(pd.DataFrame.__len__))
# Out:
#     def __len__(self):
#         """Returns length of info axis, but here we use the index """
#         return len(self.index)

Why you should not use count()

df.count()
# Out:
# A    7
# B    8
# C    8

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

fetch gives an empty response body

fetch("http://localhost:8988/api", {
        //mode: "no-cors",
        method: "GET",
        headers: {
            "Accept": "application/json"
        }
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        return data;
    })
    .catch(error => {
        return error;
    });

This works for me.

Android Studio 3.0 Flavor Dimension Issue

Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
    production {
        dimension 'yourAppName' //you just need to add this line
        //here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.

    }

    staging {
        dimension 'yourAppName' //added here also
        applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
        //or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
        //versionNameSuffix "-staging"

    }

    develop {
        dimension 'yourAppName' //add here too
        applicationIdSuffix ".develop"
        //versionNameSuffix "-develop"

    }

Bootstrap 3 unable to display glyphicon properly

For me placing my fonts folder as per location specified in bootstrap.css solved the problem

Mostly its fonts folder should be in parent directory of bootstrap.css file .

I faced this problem , and researching many answers , if anyone still in 2015 faces this problem then its either a CSS problem , or location mismatch for files .

The bug has already been solved by bootstrap

Return char[]/string from a function

If you want to return a char* from a function, make sure you malloc() it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.

change it to

char* createStr() {
    char char1= 'm';
    char char2= 'y';
    char *str = malloc(3 * sizeof(char));
    if(str == NULL) return NULL;
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';
    return str;
}

What is the preferred/idiomatic way to insert into a map?

In short, [] operator is more efficient for updating values because it involves calling default constructor of the value type and then assigning it a new value, while insert() is more efficient for adding values.

The quoted snippet from Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers, Item 24 might help.

template<typename MapType, typename KeyArgType, typename ValueArgType>
typename MapType::iterator
insertKeyAndValue(MapType& m, const KeyArgType&k, const ValueArgType& v)
{
    typename MapType::iterator lb = m.lower_bound(k);

    if (lb != m.end() && !(m.key_comp()(k, lb->first))) {
        lb->second = v;
        return lb;
    } else {
        typedef typename MapType::value_type MVT;
        return m.insert(lb, MVT(k, v));
    }
}

You may decide to choose a generic-programming-free version of this, but the point is that I find this paradigm (differentiating 'add' and 'update') extremely useful.

How do you grep a file and get the next 5 lines

You want:

grep -A 5 '19:55' file

From man grep:

Context Line Control

-A NUM, --after-context=NUM

Print NUM lines of trailing context after matching lines.  
Places a line containing a gup separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-B NUM, --before-context=NUM

Print NUM lines of leading context before matching lines.  
Places a line containing a group separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-C NUM, -NUM, --context=NUM

Print NUM lines of output context.  Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.  
With the -o or --only-matching option,  this  has  no effect and a warning
is given.

--group-separator=SEP

Use SEP as a group separator. By default SEP is double hyphen (--).

--no-group-separator

Use empty string as a group separator.

Protecting cells in Excel but allow these to be modified by VBA script

A basic but simple to understand answer:

Sub Example()
    ActiveSheet.Unprotect
    Program logic...
    ActiveSheet.Protect
End Sub

What's the best way to check if a String represents an integer in Java?

If you want to check if the string represents an integer that fits in an int type, I did a little modification to the jonas' answer, so that strings that represent integers bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE, will now return false. For example: "3147483647" will return false because 3147483647 is bigger than 2147483647, and likewise, "-2147483649" will also return false because -2147483649 is smaller than -2147483648.

public static boolean isInt(String s) {
  if(s == null) {
    return false;
  }
  s = s.trim(); //Don't get tricked by whitespaces.
  int len = s.length();
  if(len == 0) {
    return false;
  }
  //The bottom limit of an int is -2147483648 which is 11 chars long.
  //[note that the upper limit (2147483647) is only 10 chars long]
  //Thus any string with more than 11 chars, even if represents a valid integer, 
  //it won't fit in an int.
  if(len > 11) {
    return false;
  }
  char c = s.charAt(0);
  int i = 0;
  //I don't mind the plus sign, so "+13" will return true.
  if(c == '-' || c == '+') {
    //A single "+" or "-" is not a valid integer.
    if(len == 1) {
      return false;
    }
    i = 1;
  }
  //Check if all chars are digits
  for(; i < len; i++) {
    c = s.charAt(i);
    if(c < '0' || c > '9') {
      return false;
    }
  }
  //If we reached this point then we know for sure that the string has at
  //most 11 chars and that they're all digits (the first one might be a '+'
  // or '-' thought).
  //Now we just need to check, for 10 and 11 chars long strings, if the numbers
  //represented by the them don't surpass the limits.
  c = s.charAt(0);
  char l;
  String limit;
  if(len == 10 && c != '-' && c != '+') {
    limit = "2147483647";
    //Now we are going to compare each char of the string with the char in
    //the limit string that has the same index, so if the string is "ABC" and
    //the limit string is "DEF" then we are gonna compare A to D, B to E and so on.
    //c is the current string's char and l is the corresponding limit's char
    //Note that the loop only continues if c == l. Now imagine that our string
    //is "2150000000", 2 == 2 (next), 1 == 1 (next), 5 > 4 as you can see,
    //because 5 > 4 we can guarantee that the string will represent a bigger integer.
    //Similarly, if our string was "2139999999", when we find out that 3 < 4,
    //we can also guarantee that the integer represented will fit in an int.
    for(i = 0; i < len; i++) {
      c = s.charAt(i);
      l = limit.charAt(i);
      if(c > l) {
        return false;
      }
      if(c < l) {
        return true;
      }
    }
  }
  c = s.charAt(0);
  if(len == 11) {
    //If the first char is neither '+' nor '-' then 11 digits represent a 
    //bigger integer than 2147483647 (10 digits).
    if(c != '+' && c != '-') {
      return false;
    }
    limit = (c == '-') ? "-2147483648" : "+2147483647";
    //Here we're applying the same logic that we applied in the previous case
    //ignoring the first char.
    for(i = 1; i < len; i++) {
      c = s.charAt(i);
      l = limit.charAt(i);
      if(c > l) {
        return false;
      }
      if(c < l) {
        return true;
      }
    }
  }
  //The string passed all tests, so it must represent a number that fits
  //in an int...
  return true;
}

Best way to "push" into C# array

There are couple of ways this can be done.

First, is converting to list and then to array again:

List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();

Now this is not recommended as you convert to list and back again to array. If you do not want to use a list, you can use the second way which is assigning values directly into the array:

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

This is the direct approach and if you do not want to tangle with lists and conversions, this is recommended for you.

How to make a JFrame button open another JFrame class in Netbeans?

JFrame.setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

How to replace a character by a newline in Vim

Here's the answer that worked for me. From this guy:

----quoting Use the vi editor to insert a newline char in replace


Something else I have to do and cannot remember and then have to look up.

In vi, to insert a newline character in a search and replace, do the following:

:%s/look_for/replace_with^M/g

The command above would replace all instances of “look_for” with “replace_with\n” (with \n meaning newline).

To get the “^M”, enter the key combination Ctrl + V, and then after that (release all keys) press the Enter key.


How to obtain image size using standard Python class (without using external library)?

Regarding Fred the Fantastic's answer:

Not every JPEG marker between C0-CF are SOF markers; I excluded DHT (C4), DNL (C8) and DAC (CC). Note that I haven't looked into whether it is even possible to parse any frames other than C0 and C2 in this manner. However, the other ones seem to be fairly rare (I personally haven't encountered any other than C0 and C2).

Either way, this solves the problem mentioned in comments by Malandy with Bangles.jpg (DHT erroneously parsed as SOF).

The other problem mentioned with 1431588037-WgsI3vK.jpg is due to imghdr only being able detect the APP0 (EXIF) and APP1 (JFIF) headers.

This can be fixed by adding a more lax test to imghdr (e.g. simply FFD8 or maybe FFD8FF?) or something much more complex (possibly even data validation). With a more complex approach I've only found issues with: APP14 (FFEE) (Adobe); the first marker being DQT (FFDB); and APP2 and issues with embedded ICC_PROFILEs.

Revised code below, also altered the call to imghdr.what() slightly:

import struct
import imghdr

def test_jpeg(h, f):
    # SOI APP2 + ICC_PROFILE
    if h[0:4] == '\xff\xd8\xff\xe2' and h[6:17] == b'ICC_PROFILE':
        print "A"
        return 'jpeg'
    # SOI APP14 + Adobe
    if h[0:4] == '\xff\xd8\xff\xee' and h[6:11] == b'Adobe':
        return 'jpeg'
    # SOI DQT
    if h[0:4] == '\xff\xd8\xff\xdb':
        return 'jpeg'
imghdr.tests.append(test_jpeg)

def get_image_size(fname):
    '''Determine the image type of fhandle and return its size.
    from draco'''
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            return
        what = imghdr.what(None, head)
        if what == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif what == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif what == 'jpeg':
            try:
                fhandle.seek(0) # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf or ftype in (0xc4, 0xc8, 0xcc):
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
                # We are at a SOFn block
                fhandle.seek(1, 1)  # Skip `precision' byte.
                height, width = struct.unpack('>HH', fhandle.read(4))
            except Exception: #IGNORE:W0703
                return
        else:
            return
        return width, height

Note: Created a full answer instead of a comment, since I'm not yet allowed to.

Responsive css styles on mobile devices ONLY

Why not use a media query range.

I'm currently working on a responsive layout for my employer and the ranges I'm using are as follows:

You have your main desktop styles in the body of the CSS file (1024px and above) and then for specific screen sizes I'm using:

@media all and (min-width:960px) and (max-width: 1024px) {
  /* put your css styles in here */
}

@media all and (min-width:801px) and (max-width: 959px) {
  /* put your css styles in here */
}

@media all and (min-width:769px) and (max-width: 800px) {
  /* put your css styles in here */
}

@media all and (min-width:569px) and (max-width: 768px) {
  /* put your css styles in here */
}

@media all and (min-width:481px) and (max-width: 568px) {
  /* put your css styles in here */
}

@media all and (min-width:321px) and (max-width: 480px) {
  /* put your css styles in here */
}

@media all and (min-width:0px) and (max-width: 320px) {
  /* put your css styles in here */
}

This will cover pretty much all devices being used - I would concentrate on getting the styling correct for the sizes at the end of the range (i.e. 320, 480, 568, 768, 800, 1024) as for all the others they will just be responsive to the size available.

Also, don't use px anywhere - use em's or %.

Making a POST call instead of GET using urllib2

Do it in stages, and modify the object, like this:

# make a string with the request type in it:
method = "POST"
# create a handler. you can specify different handlers here (file uploads etc)
# but we go for the default
handler = urllib2.HTTPHandler()
# create an openerdirector instance
opener = urllib2.build_opener(handler)
# build a request
data = urllib.urlencode(dictionary_of_POST_fields_or_None)
request = urllib2.Request(url, data=data)
# add any other information you want
request.add_header("Content-Type",'application/json')
# overload the get method function with a small anonymous function...
request.get_method = lambda: method
# try it; don't forget to catch the result
try:
    connection = opener.open(request)
except urllib2.HTTPError,e:
    connection = e

# check. Substitute with appropriate HTTP code.
if connection.code == 200:
    data = connection.read()
else:
    # handle the error case. connection.read() will still contain data
    # if any was returned, but it probably won't be of any use

This way allows you to extend to making PUT, DELETE, HEAD and OPTIONS requests too, simply by substituting the value of method or even wrapping it up in a function. Depending on what you're trying to do, you may also need a different HTTP handler, e.g. for multi file upload.

Difference between e.target and e.currentTarget

e.target is what triggers the event dispatcher to trigger and e.currentTarget is what you assigned your listener to.

Groovy built-in REST/HTTP client?

You can take advantage of Groovy features like with(), improvements to URLConnection, and simplified getters/setters:

GET:

String getResult = new URL('http://mytestsite/bloop').text

POST:

String postResult
((HttpURLConnection)new URL('http://mytestsite/bloop').openConnection()).with({
    requestMethod = 'POST'
    doOutput = true
    setRequestProperty('Content-Type', '...') // Set your content type.
    outputStream.withPrintWriter({printWriter ->
        printWriter.write('...') // Your post data. Could also use withWriter() if you don't want to write a String.
    })
    // Can check 'responseCode' here if you like.
    postResult = inputStream.text // Using 'inputStream.text' because 'content' will throw an exception when empty.
})

Note, the POST will start when you try to read a value from the HttpURLConnection, such as responseCode, inputStream.text, or getHeaderField('...').

How to check if a character in a string is a digit or letter

You could do this by Regular Expression as follows you could use this code

EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();

if (Number.matches(NumberPattern) && s.length() > 0)
{ 
    //code for number
}
else
{
    //code for incorrect number pattern
}

Java generics - get class?

I'm not 100% sure if this works in all cases (needs at least Java 1.5):

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Main 
{
    public class A
    {   
    }

    public class B extends A
    {       
    }


    public Map<A, B> map = new HashMap<Main.A, Main.B>();

    public static void main(String[] args) 
    {

        try
        {
            Field field = Main.class.getField("map");           
            System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());

            Type genericType = field.getGenericType();

            if(genericType instanceof ParameterizedType)
            {
                ParameterizedType type = (ParameterizedType) genericType;               
                Type[] typeArguments = type.getActualTypeArguments();

                for(Type typeArgument : typeArguments) 
                {   
                    Class<?> classType = ((Class<?>)typeArgument);                  
                    System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }    
}

This will output:

Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B

Centering text in a table in Twitter Bootstrap

I had the same problem and a better way to solve it without using !important was defining the following in my CSS:

table th.text-center, table td.text-center { 
    text-align: center;
}

That way the specifity of the text-center class works correctly in tables.

git commit error: pathspec 'commit' did not match any file(s) known to git

if there are anybodys using python os to invoke git,u can use os.system('git commit -m " '+str(comment)+'"')

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

You can't, you can NEVER restore from a higher version to a lower version of SQL Server. Your only option is to script out the database and then transfer the data via SSIS, BCP, linked server or scripting out the data

jQuery UI DatePicker to show year only

  $(function() {
    $('#datepicker1').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    });
});?

Style should be

.ui-datepicker-calendar {
    display: none;
    }?

working demo

Leading zeros for Int in Swift

With Swift 5, you may choose one of the three examples shown below in order to solve your problem.


#1. Using String's init(format:_:) initializer

Foundation provides Swift String a init(format:_:) initializer. init(format:_:) has the following declaration:

init(format: String, _ arguments: CVarArg...)

Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted.

The following Playground code shows how to create a String formatted from Int with at least two integer digits by using init(format:_:):

import Foundation

let string0 = String(format: "%02d", 0) // returns "00"
let string1 = String(format: "%02d", 1) // returns "01"
let string2 = String(format: "%02d", 10) // returns "10"
let string3 = String(format: "%02d", 100) // returns "100"

#2. Using String's init(format:arguments:) initializer

Foundation provides Swift String a init(format:arguments:) initializer. init(format:arguments:) has the following declaration:

init(format: String, arguments: [CVarArg])

Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.

The following Playground code shows how to create a String formatted from Int with at least two integer digits by using init(format:arguments:):

import Foundation

let string0 = String(format: "%02d", arguments: [0]) // returns "00"
let string1 = String(format: "%02d", arguments: [1]) // returns "01"
let string2 = String(format: "%02d", arguments: [10]) // returns "10"
let string3 = String(format: "%02d", arguments: [100]) // returns "100"

#3. Using NumberFormatter

Foundation provides NumberFormatter. Apple states about it:

Instances of NSNumberFormatter format the textual representation of cells that contain NSNumber objects and convert textual representations of numeric values into NSNumber objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.

The following Playground code shows how to create a NumberFormatter that returns String? from a Int with at least two integer digits:

import Foundation

let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2

let optionalString0 = formatter.string(from: 0) // returns Optional("00")
let optionalString1 = formatter.string(from: 1) // returns Optional("01")
let optionalString2 = formatter.string(from: 10) // returns Optional("10")
let optionalString3 = formatter.string(from: 100) // returns Optional("100")

How to wait for the 'end' of 'resize' event and only then perform an action?

This is the code that I write according to @Mark Coleman answer:

$(window).resize(function() {
    clearTimeout(window.resizedFinished);
    window.resizedFinished = setTimeout(function(){
        console.log('Resized finished.');
    }, 250);
});

Thanks Mark!

Using jq to parse and display multiple fields in a json serially

I recommend using String Interpolation:

jq '.users[] | "\(.first) \(.last)"'

reference

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

Python: How to get values of an array at certain index positions?

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

How to disable HTML links

You can use this to disabled the Hyperlink of asp.net or link buttons in html.

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

How to configure robots.txt to allow everything?

If you want to allow every bot to crawl everything, this is the best way to specify it in your robots.txt:

User-agent: *
Disallow:

Note that the Disallow field has an empty value, which means according to the specification:

Any empty value, indicates that all URLs can be retrieved.


Your way (with Allow: / instead of Disallow:) works, too, but Allow is not part of the original robots.txt specification, so it’s not supported by all bots (many popular ones support it, though, like the Googlebot). That said, unrecognized fields have to be ignored, and for bots that don’t recognize Allow, the result would be the same in this case anyway: if nothing is forbidden to be crawled (with Disallow), everything is allowed to be crawled.
However, formally (per the original spec) it’s an invalid record, because at least one Disallow field is required:

At least one Disallow field needs to be present in a record.

Looking for simple Java in-memory cache

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

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

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

Links:

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

jquery - is not a function error

It works on my case:

import * as JQuery from "jquery";
const $ = JQuery.default;

Extension gd is missing from your system - laravel composer Update

If you are working in PHP version 5.* then you have to install

sudo apt-get install php5-gd

And if you are working in PHP version 7.* then you have to install

sudo apt-get install php7.0-gd

Hope it will work...

And if you are working in PHP version 7.2 then you have to install

sudo apt-get install php7.2-gd... it worked for me

Develop Android app using C#

You could use Mono for Android:

http://xamarin.com/monoforandroid

An alternative is dot42:

http://www.dot42.com/

dot42 provides a free community licence as well as a professional licence for $399.

How to list imported modules?

It's actually working quite good with:

import sys
mods = [m.__name__ for m in sys.modules.values() if m]

This will create a list with importable module names.

setTimeout in React Native

Write a new function for settimeout. Pls try this.

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

componentDidMount() {
  this.setTimeout( () => {
     this.setTimePassed();
  },1000);
}

setTimePassed() {
   this.setState({timePassed: true});
}


render() {

if (!this.state.timePassed){
  return <LoadingPage/>;
}else{
  return (
    <NavigatorIOS
      style = {styles.container}
      initialRoute = {{
        component: LoginPage,
        title: 'Sign In',
      }}/>
  );
}
}
}

calculating the difference in months between two dates

The accepted answer works perfectly when you want full months.

I needed partial months. This is the solution I came up with for partial months:

    /// <summary>
    /// Calculate the difference in months.
    /// This will round up to count partial months.
    /// </summary>
    /// <param name="lValue"></param>
    /// <param name="rValue"></param>
    /// <returns></returns>
    public static int MonthDifference(DateTime lValue, DateTime rValue)
    {
        var yearDifferenceInMonths = (lValue.Year - rValue.Year) * 12;
        var monthDifference = lValue.Month - rValue.Month;

        return yearDifferenceInMonths + monthDifference + 
            (lValue.Day > rValue.Day
                ? 1 : 0); // If end day is greater than start day, add 1 to round up the partial month
    }

I also needed a year difference with the same need for partial years. Here is the solution I came up with:

    /// <summary>
    /// Calculate the differences in years.
    /// This will round up to catch partial months.
    /// </summary>
    /// <param name="lValue"></param>
    /// <param name="rValue"></param>
    /// <returns></returns>
    public static int YearDifference(DateTime lValue, DateTime rValue)
    {
        return lValue.Year - rValue.Year +
               (lValue.Month > rValue.Month // Partial month, same year
                   ? 1
                   : ((lValue.Month = rValue.Month) 
                     && (lValue.Day > rValue.Day)) // Partial month, same year and month
                   ? 1 : 0);
    }

Make index.html default, but allow index.php to be visited if typed in

Hi,

Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.

Here how I do that...

# Accesible Index Page
<IfModule dir_module>
 DirectoryIndex index.php index.html
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
 RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>

The above code simply captures any index.* and redirect it to the main domain.

Thank you

awk - concatenate two string variable and assign to a third

Just use var = var1 var2 and it will automatically concatenate the vars var1 and var2:

awk '{new_var=$1$2; print new_var}' file

You can put an space in between with:

awk '{new_var=$1" "$2; print new_var}' file

Which in fact is the same as using FS, because it defaults to the space:

awk '{new_var=$1 FS $2; print new_var}' file

Test

$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am

You can play around with it in ideone: http://ideone.com/4u2Aip

iOS download and save image inside app

You cannot save anything inside the app's bundle, but you can use +[NSData dataWithContentsOfURL:] to store the image in your app's documents directory, e.g.:

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];

Not exactly permanent, but it stays there at least until the user deletes the app.

jQuery & CSS - Remove/Add display:none

The only way to remove an inline "display:none" via jQuery's css-api is by resetting it with the empty string (null does NOT work btw!!).

According to the jQuery docu this is the general way to "remove" a once set inline style property.

$("#mydiv").css("display","");

or

$("#mydiv").css({display:""});

should do the trick properly.

IMHO there is a method missing in jQuery that could be called "unhide" or "reveal" which instead of just setting another inline style property unsets the display value properly as described above. Or maybe hide() should store the initial inline value and show() should restore that...

How to iterate through an ArrayList of Objects of ArrayList of Objects?

You want to follow the same pattern as before:

for (Type curInstance: CollectionOf<Type>) {
  // use currInstance
}

In this case it would be:

for (Bullet bullet : gunList.get(2).getBullet()) {
   System.out.println(bullet);
}

Reportviewer tool missing in visual studio 2017 RC

Download Microsoft Rdlc Report Designer for Visual Studio from this link. https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftRdlcReportDesignerforVisualStudio-18001

Microsoft explain the steps in details:

https://docs.microsoft.com/en-us/sql/reporting-services/application-integration/integrating-reporting-services-using-reportviewer-controls-get-started?view=sql-server-2017

The following steps summarizes the above article.

Adding the Report Viewer control to a new web project:

  1. Create a new ASP.NET Empty Web Site or open an existing ASP.NET project.

  2. Install the Report Viewer control NuGet package via the NuGet package manager console. From Visual Studio -> Tools -> NuGet Package Manager -> Package Manager Console

    Install-Package Microsoft.ReportingServices.ReportViewerControl.WebForms
    
  3. Add a new .aspx page to the project and register the Report Viewer control assembly for use within the page.

    <%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
    
  4. Add a ScriptManagerControl to the page.

  5. Add the Report Viewer control to the page. The snippet below can be updated to reference a report hosted on a remote report server.

     <rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
     <ServerReport ReportPath="" ReportServerUrl="" /></rsweb:ReportViewer>
    

The final page should look like the following.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Sample" %>

<%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>

<!DOCTYPE html>

<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager runat="server"></asp:ScriptManager>        
       <rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
           <ServerReport ReportServerUrl="https://AContosoDepartment/ReportServer" ReportPath="/LatestSales" />
    </rsweb:ReportViewer>
    </form>
</body>

What is the "__v" field in Mongoose

We can use versionKey: false in Schema definition

'use strict';

const mongoose = require('mongoose');

export class Account extends mongoose.Schema {

    constructor(manager) {

        var trans = {
            tran_date: Date,
            particulars: String,
            debit: Number,
            credit: Number,
            balance: Number
        }

        super({
            account_number: Number,
            account_name: String,
            ifsc_code: String,
            password: String,
            currency: String,
            balance: Number,
            beneficiaries: Array,
            transaction: [trans]
        }, {
            versionKey: false // set to false then it wont create in mongodb
        });

        this.pre('remove', function(next) {
            manager
                .getModel(BENEFICIARY_MODEL)
                .remove({
                    _id: {
                        $in: this.beneficiaries
                    }
                })
                .exec();
            next();
        });
    }

}