Programs & Examples On #Libvirt

libvirt is an open source API, daemon and management tool for managing platform virtualization.[1] It can be used to manage Linux KVM, Xen, VMware ESX,qemu and other virtualization technologies. These APIs are widely used in Orchestration Layer for Hypervisors in the development of a cloud based solution.

How do I force make/GCC to show me the commands?

Build system independent method

make SHELL='sh -x'

is another option. Sample Makefile:

a:
    @echo a

Output:

+ echo a
a

This sets the special SHELL variable for make, and -x tells sh to print the expanded line before executing it.

One advantage over -n is that is actually runs the commands. I have found that for some projects (e.g. Linux kernel) that -n may stop running much earlier than usual probably because of dependency problems.

One downside of this method is that you have to ensure that the shell that will be used is sh, which is the default one used by Make as they are POSIX, but could be changed with the SHELL make variable.

Doing sh -v would be cool as well, but Dash 0.5.7 (Ubuntu 14.04 sh) ignores for -c commands (which seems to be how make uses it) so it doesn't do anything.

make -p will also interest you, which prints the values of set variables.

CMake generated Makefiles always support VERBOSE=1

As in:

mkdir build
cd build
cmake ..
make VERBOSE=1

Dedicated question at: Using CMake with GNU Make: How can I see the exact commands?

How to lookup JNDI resources on WebLogic?

I had a similar problem to this one. It got solved by deleting the java:comp/env/ prefix and using jdbc/myDataSource in the context lookup. Just as someone pointed out in the comments.

Running Python in PowerShell?

Go to Python Website/dowloads/windows. Download Windows x86-64 embeddable zip file. 2. Open Windows Explorer

open zipped folder python-3.7.0 In the windows toolbar with the Red flair saying “Compressed Folder Tool” Press “Extract” button on the tool bar with “File” “Home “Share” “View” Select Extract all Extraction process is not covered yet Once extracted save onto SDD or fastest memory device. Not usb. HDD is fine. SDD Users/butte/ProgramFiles blah blah ooooor D:\Python Or Hook up to your cloud 3. Click your User Icon in the Windows tool bar.

Search environment variable Proceed with progressing with “Environment Variables” button press Under the “user variables” table select “New..” After the Canvas of Information Add Python in Variable Name Select the “D:\Python\python-3.7.0-embed-amd64\python.exe;” click ok Under the “System Variables” label and in the Canvas the first row has a value marked “Path” Select “Edit” when “Path” is highlighted. Select “New” Enter D:\Python\python-3.7.0-embed-amd click ok Ok Save and double check Open Power Shell python --help

python --version

Source to tutorial https://thedishbunnybitch.com/2018/08/11/installing-python-on-windows-10-for-powershell/

Getting new Twitter API consumer and secret keys

consumer_key = API key

consumer_secret = API key secret

Found it hidden in Twitter API Docs

Twitter Docs screenshot

Twitter's naming is just too confusing.

Filter object properties by key in ES6

I know that this already has plenty of answers and is a rather old question. But I just came up with this neat one-liner:

JSON.parse(JSON.stringify(raw, ['key', 'value', 'item1', 'item3']))

That returns another object with just the whitelisted attributes. Note that the key and value is included in the list.

How do I print bold text in Python?

You can use termcolor for this:

 sudo pip install termcolor

To print a colored bold:

 from termcolor import colored
 print(colored('Hello', 'green', attrs=['bold']))

For more information, see termcolor on PyPi.

simple-colors is another package with similar syntax:

 from simple_colors import *
 print(green('Hello', ['bold'])

The equivalent in colorama may be Style.BRIGHT.

How do I delete a Git branch locally and remotely?

Many of the other answers will lead to errors/warnings. This approach is relatively fool proof although you may still need git branch -D branch_to_delete if it's not fully merged into some_other_branch, for example.

git checkout some_other_branch
git push origin :branch_to_delete
git branch -d branch_to_delete

Remote pruning isn't needed if you deleted the remote branch. It's only used to get the most up-to-date remotes available on a repository you're tracking. I've observed git fetch will add remotes, not remove them. Here's an example of when git remote prune origin will actually do something:

User A does the steps above. User B would run the following commands to see the most up-to-date remote branches:

git fetch
git remote prune origin
git branch -r

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

Visual Studio breakpoints not being hit

In my scenario, I've got an MVC app and WebAPI in one solution, and I'm using local IIS (not express).

I also set up the sites in IIS as real domains, and edited my host file so that I can type in the real domain and everything works. I also noticed 2 things:

  1. The MVC code debugging was working perfectly.

  2. Attaching to process worked perfectly too. Just when I was debugging it didn't hit the breakpoint in my API.

This was the solution for me:

Right click webapi project > properties > Web > Project URL

By default it points to localhost, but since I set up the site in IIS, I forgot to change the URL to the website domain (i.e. instead of locahost, it should say http://{domain-name}/).

PuTTY Connection Manager download?

Try SuperPuTTY. It is similar to puttycm.

You can also try mobaxterm or mremoteng

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

The sqlite answer is

update TABLE set mydatetime = datetime('now');

in case someone else was looking for it.

how to check if item is selected from a comboBox in C#

I've found that using this null comparison works well:

if (Combobox.SelectedItem != null){
   //Do something
}
else{
  MessageBox.show("Please select a item");
}

This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.

Is it possible to get multiple values from a subquery?

It's incorrect, but you can try this instead:

select
    a.x,
    ( select b.y from b where b.v = a.v) as by,
    ( select b.z from b where b.v = a.v) as bz
from a

you can also use subquery in join

 select
        a.x,
        b.y,
        b.z
    from a
    left join (select y,z from b where ... ) b on b.v = a.v

or

   select
        a.x,
        b.y,
        b.z
    from a
    left join b on b.v = a.v

How to split one string into multiple variables in bash shell?

Using bash regex capabilities:

re="^([^-]+)-(.*)$"
[[ "ABCDE-123456" =~ $re ]] && var1="${BASH_REMATCH[1]}" && var2="${BASH_REMATCH[2]}"
echo $var1
echo $var2

OUTPUT

ABCDE
123456

Shift column in pandas dataframe up by one?

First shift the column:

df['gdp'] = df['gdp'].shift(-1)

Second remove the last row which contains an NaN Cell:

df = df[:-1]

Third reset the index:

df = df.reset_index(drop=True)

Difference between JE/JNE and JZ/JNZ

From the Intel's manual - Instruction Set Reference, the JE and JZ have the same opcode (74 for rel8 / 0F 84 for rel 16/32) also JNE and JNZ (75 for rel8 / 0F 85 for rel 16/32) share opcodes.

JE and JZ they both check for the ZF (or zero flag), although the manual differs slightly in the descriptions of the first JE rel8 and JZ rel8 ZF usage, but basically they are the same.

Here is an extract from the manual's pages 464, 465 and 467.

 Op Code    | mnemonic  | Description
 -----------|-----------|-----------------------------------------------  
 74 cb      | JE rel8   | Jump short if equal (ZF=1).
 74 cb      | JZ rel8   | Jump short if zero (ZF ? 1).

 0F 84 cw   | JE rel16  | Jump near if equal (ZF=1). Not supported in 64-bit mode.
 0F 84 cw   | JZ rel16  | Jump near if 0 (ZF=1). Not supported in 64-bit mode.

 0F 84 cd   | JE rel32  | Jump near if equal (ZF=1).
 0F 84 cd   | JZ rel32  | Jump near if 0 (ZF=1).

 75 cb      | JNE rel8  | Jump short if not equal (ZF=0).
 75 cb      | JNZ rel8  | Jump short if not zero (ZF=0).

 0F 85 cd   | JNE rel32 | Jump near if not equal (ZF=0).
 0F 85 cd   | JNZ rel32 | Jump near if not zero (ZF=0).

How to remove class from all elements jquery

$(".edgetoedge>li").removeClass("highlight");

Call removeView() on the child's parent first

What I was doing wrong so I got this error is I wasn't instantiating dynamic layout and adding childs to it so got this error

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

send mail from linux terminal in one line

mail can represent quite a couple of programs on a linux system. What you want behind it is either sendmail or postfix. I recommend the latter.

You can install it via your favorite package manager. Then you have to configure it, and once you have done that, you can send email like this:

 echo "My message" | mail -s subject [email protected]

See the manual for more information.

As far as configuring postfix goes, there's plenty of articles on the internet on how to do it. Unless you're on a public server with a registered domain, you generally want to forward the email to a SMTP server that you can send email from.

For gmail, for example, follow http://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/ or any other similar tutorial.

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

Mysql command not found in OS X 10.7

I have tried a lot of the suggestions on SO but this is the one that actually worked for me:

sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'

then you type

mysql

It will prompt you to enter your password.

Recursive file search using PowerShell

When searching folders where you might get an error based on security (e.g. C:\Users), use the following command:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force

What are the differences between virtual memory and physical memory?

I am shamelessly copying the excerpts from man page of top

VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.

SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory

Converting String to Int using try/except in Python

You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Accessing Session Using ASP.NET Web API

Mark, if you check the nerddinner MVC example the logic is pretty much the same.

You only need to retrieve the cookie and set it in the current session.

Global.asax.cs

public override void Init()
{
    this.AuthenticateRequest += new EventHandler(WebApiApplication_AuthenticateRequest);
    base.Init();
}

void WebApiApplication_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

    SampleIdentity id = new SampleIdentity(ticket);
    GenericPrincipal prin = new GenericPrincipal(id, null); 

    HttpContext.Current.User = prin;
}

enter code here

You'll have to define your "SampleIdentity" class, which you can borrow from the nerddinner project.

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

How to connect to MySQL Database?

Another library to consider is MySqlConnector, https://mysqlconnector.net/. Mysql.Data is under a GPL license, whereas MySqlConnector is MIT.

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

Qt jpg image display

I understand your frustration the " Graphics view widget" is not the best way to do this, yes it can be done, but it's almost exactly the same as using a label ( for what you want any way) now all the ways listed do work but...

For you and any one else that may come across this question he easiest way to do it ( what you're asking any way ) is this.

QPixmap pix("Path\\path\\entername.jpeg");
    ui->label->setPixmap(pix);

}

How to export a CSV to Excel using Powershell

This topic really helped me, so I'd like to share my improvements. All credits go to the nixda, this is based on his answer.

For those who need to convert multiple csv's in a folder, just modify the directory. Outputfilenames will be identical to input, just with another extension.

Take care of the cleanup in the end, if you like to keep the original csv's you might not want to remove these.

Can be easily modifed to save the xlsx in another directory.

$workingdir = "C:\data\*.csv"
$csv = dir -path $workingdir
foreach($inputCSV in $csv){
$outputXLSX = $inputCSV.DirectoryName + "\" + $inputCSV.Basename + ".xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
### $Excel.Application.International(3) = ,
### $Excel.Application.International(5) = ;
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

### Execute & delete the import query
$query.Refresh()
$query.Delete()

### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
}
## To exclude an item, use the '-exclude' parameter (wildcards if needed)
remove-item -path $workingdir -exclude *Crab4dq.csv

Where can I read the Console output in Visual Studio 2015

My problem was that I needed to Reset Window Layout.

Reset Window Layout

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

Browser detection

if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
    ...
} 
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
    if (Request.Browser.MajorVersion  < 7)
    { 
        DoSomething(); 
    }
    ...
}
else { }

How to capture Enter key press?

Form approach

As scoota269 says, you should use onSubmit instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)

<form action="#" onsubmit="handle">
    <input type="text" name="txt" />
</form>

<script>
    function handle(e){
        e.preventDefault(); // Otherwise the form will be submitted

        alert("FORM WAS SUBMITTED");
    }
</script>

Textbox approach

If you want to have an event on the input-field then you need to make sure your handle() will return false, otherwise the form will get submitted.

<form action="#">
    <input type="text" name="txt" onkeypress="handle(event)" />
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that runs

            alert("Enter was pressed was presses");
        }
    }
</script>

Check for internet connection with Swift

As of iOS 12, NWPathMonitor replaced Reachability. Use this:

import Network


struct Internet {
 
 private static let monitor = NWPathMonitor()
 
 static var active = false
 static var expensive = false
 
 /// Monitors internet connectivity changes. Updates with every change in connectivity.
 /// Updates variables for availability and if it's expensive (cellular).
 static func start() {
  guard monitor.pathUpdateHandler == nil else { return }
  
  monitor.pathUpdateHandler = { update in
   Internet.active = update.status == .satisfied ? true : false
   Internet.expensive = update.isExpensive ? true : false
  }
  
  monitor.start(queue: DispatchQueue(label: "InternetMonitor"))
 }
 
}

In use:

Internet.start()

if Internet.active {
 // do something
}
  
if Internet.expensive {
 // device is using Cellular data or WiFi hotspot
}

col align right

For Bootstrap 4 I find the following very handy because:

  • the column on the right takes exactly the space it needs and will pull right
  • while the left col always gets the maximum amount of space!.

It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)

<div class="row">
    <div class="col">Left</div>
    <div class="col-auto">Right</div>
</div>

Ideal for aligning words, icons, buttons,... to the right.

An example to have this responsive on small devices:

<div class="row">
    <div class="col">Left</div>
    <div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>

Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/

Bash command to sum a column of numbers

The following command will add all the lines(first field of the awk output)

awk '{s+=$1} END {print s}' filename

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Implementation in Kotlin : Retrofit 2.3.0

private fun getUnsafeOkHttpClient(mContext: Context) : 
OkHttpClient.Builder? {


var mCertificateFactory : CertificateFactory = 
CertificateFactory.getInstance("X.509")
var mInputStream = mContext.resources.openRawResource(R.raw.cert)
            var mCertificate : Certificate = mCertificateFactory.generateCertificate(mInputStream)
        mInputStream.close()
val mKeyStoreType = KeyStore.getDefaultType()
val mKeyStore = KeyStore.getInstance(mKeyStoreType)
mKeyStore.load(null, null)
mKeyStore.setCertificateEntry("ca", mCertificate)

val mTmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
val mTrustManagerFactory = TrustManagerFactory.getInstance(mTmfAlgorithm)
mTrustManagerFactory.init(mKeyStore)

val mTrustManagers = mTrustManagerFactory.trustManagers

val mSslContext = SSLContext.getInstance("SSL")
mSslContext.init(null, mTrustManagers, null)
val mSslSocketFactory = mSslContext.socketFactory

val builder = OkHttpClient.Builder()
builder.sslSocketFactory(mSslSocketFactory, mTrustManagers[0] as X509TrustManager)
builder.hostnameVerifier { _, _ -> true }
return builder

}

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

Simply as bellow;

$this->db->get('table_name')->num_rows();

This will get number of rows/records. however you can use search parameters as well;

$this->db->select('col1','col2')->where('col'=>'crieterion')->get('table_name')->num_rows();

However, it should be noted that you will see bad bad errors if applying as below;

$this->db->get('table_name')->result()->num_rows();

Windows recursive grep command-line

If you have Perl installed, you could use ack, available at http://beyondgrep.com/.

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

You can use the datedif function to find out difference in days.

=DATEDIF(A1,TODAY(),"d")

Quote from excel.datedif.com

The mysterious datedif function in Microsoft Excel

The Datedif function is used to calculate interval between two dates in days, months or years.

This function is available in all versions of Excel but is not documented. It is not even listed in the "Insert Function" dialog box. Hence it must be typed manually in the formula box. Syntax

DATEDIF( start_date, end_date, interval_unit )

start_date from date end_date to date (must be after start_date) interval_unit Unit to be used for output interval Values for interval_unit

interval_unit Description

D Number of days

M Number of complete months

Y Number of complete years

YD Number of days excluding years

MD Number of days excluding months and years

YM Number of months excluding years

Errors

Error Description

#NUM! The end_date is later than (greater than) the start_date or interval_unit has an invalid value. #VALUE! end_date or start_date is invalid.

Creating an array of objects in Java

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

How to do constructor chaining in C#

I just want to bring up a valid point to anyone searching for this. If you are going to work with .NET versions before 4.0 (VS2010), please be advised that you have to create constructor chains as shown above.

However, if you're staying in 4.0, I have good news. You can now have a single constructor with optional arguments! I'll simplify the Foo class example:

class Foo {
  private int id;
  private string name;

  public Foo(int id = 0, string name = "") {
    this.id = id;
    this.name = name;
  }
}

class Main() {
  // Foo Int:
  Foo myFooOne = new Foo(12);
  // Foo String:
  Foo myFooTwo = new Foo(name:"Timothy");
  // Foo Both:
  Foo myFooThree = new Foo(13, name:"Monkey");
}

When you implement the constructor, you can use the optional arguments since defaults have been set.

I hope you enjoyed this lesson! I just can't believe that developers have been complaining about construct chaining and not being able to use default optional arguments since 2004/2005! Now it has taken SO long in the development world, that developers are afraid of using it because it won't be backwards compatible.

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

How does lock work exactly?

The lock statement is translated to calls to the Enter and Exit methods of Monitor.

The lock statement will wait indefinitely for the locking object to be released.

Launch Pycharm from command line (terminal)

Easy solution without need for pathes:

open -b com.jetbrains.pycharm



You can set it as alias for every-day easier usage (put to your .bash_rc etc.):

alias pycharm='open -b com.jetbrains.pycharm'

Usage:

pycharm .
pycharm file.py

Why is super.super.method(); not allowed in Java?

I would put the super.super method body in another method, if possible

class SuperSuperClass {
    public String toString() {
        return DescribeMe();
    }

    protected String DescribeMe() {
        return "I am super super";
    }
}

class SuperClass extends SuperSuperClass {
    public String toString() {
        return "I am super";
    }
}

class ChildClass extends SuperClass {
    public String toString() {
        return DescribeMe();
    }
}

Or if you cannot change the super-super class, you can try this:

class SuperSuperClass {
    public String toString() {
        return "I am super super";
    }
}

class SuperClass extends SuperSuperClass {
    public String toString() {
        return DescribeMe(super.toString());
    }

    protected String DescribeMe(string fromSuper) {
        return "I am super";
    }
}

class ChildClass extends SuperClass {
    protected String DescribeMe(string fromSuper) {
        return fromSuper;
    }
}

In both cases, the

new ChildClass().toString();

results to "I am super super"

Submit form without reloading page

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}

Order a MySQL table by two columns

ORDER BY article_rating, article_time DESC

will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.

? primary sort                         secondary sort ?
1.  50 | This article rocks          | Feb 4, 2009    3.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

but consider:

? primary sort                         secondary sort ?
1.  50 | This article rocks          | Feb 2, 2009    3.
1.  50 | This article rocks, too     | Feb 4, 2009    4.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

Default SecurityProtocol in .NET 4.5

An alternative to hard-coding ServicePointManager.SecurityProtocol or the explicit SchUseStrongCrypto key as mentioned above:
You can tell .NET to use the default SCHANNEL settings with the SystemDefaultTlsVersions key,
e.g.:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319] "SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319] "SystemDefaultTlsVersions"=dword:00000001

In c# is there a method to find the max of 3 numbers?

If, for whatever reason (e.g. Space Engineers API), System.array has no definition for Max nor do you have access to Enumerable, a solution for Max of n values is:

public int Max(int[] values) {
    if(values.Length < 1) {
        return 0;
    }
    if(values.Length < 2) {
        return values[0];
    }
    if(values.Length < 3) {
       return Math.Max(values[0], values[1]); 
    }
    int runningMax = values[0];
    for(int i=1; i<values.Length - 1; i++) {
       runningMax = Math.Max(runningMax, values[i]);
    }
    return runningMax;
}

How to apply shell command to each line of a command output?

You can use a basic prepend operation on each line:

ls -1 | while read line ; do echo $line ; done

Or you can pipe the output to sed for more complex operations:

ls -1 | sed 's/^\(.*\)$/echo \1/'

Pass in an enum as a method parameter

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
    file = new File
    {  
       Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions
    };

    return file.Id;
}

How to change the default message of the required field in the popover of form-control in bootstrap?

Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Here,

this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field

oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.

Thread pooling in C++11

Something like this might help (taken from a working app).

#include <memory>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

struct thread_pool {
  typedef std::unique_ptr<boost::asio::io_service::work> asio_worker;

  thread_pool(int threads) :service(), service_worker(new asio_worker::element_type(service)) {
    for (int i = 0; i < threads; ++i) {
      auto worker = [this] { return service.run(); };
      grp.add_thread(new boost::thread(worker));
    }
  }

  template<class F>
  void enqueue(F f) {
    service.post(f);
  }

  ~thread_pool() {
    service_worker.reset();
    grp.join_all();
    service.stop();
  }

private:
  boost::asio::io_service service;
  asio_worker service_worker;
  boost::thread_group grp;
};

You can use it like this:

thread_pool pool(2);

pool.enqueue([] {
  std::cout << "Hello from Task 1\n";
});

pool.enqueue([] {
  std::cout << "Hello from Task 2\n";
});

Keep in mind that reinventing an efficient asynchronous queuing mechanism is not trivial.

Boost::asio::io_service is a very efficient implementation, or actually is a collection of platform-specific wrappers (e.g. it wraps I/O completion ports on Windows).

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

Easiest way to read from and write to files

using (var file = File.Create("pricequote.txt"))
{
    ...........                        
}

using (var file = File.OpenRead("pricequote.txt"))
{
    ..........
}

Simple, easy and also disposes/cleans up the object once you are done with it.

Android: Create spinner programmatically from array

In Kotlin language you can do it in this way:

val values = arrayOf(
    "cat",
    "dog",
    "chicken"
)

ArrayAdapter(
    this,
    android.R.layout.simple_spinner_item,
    values
).also {
    it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    spinner.adapter = it
}

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

No, image/jpg is not the same as image/jpeg.

You should use image/jpeg. Only image/jpeg is recognised as the actual mime type for JPEG files.

See https://tools.ietf.org/html/rfc3745, https://www.w3.org/Graphics/JPEG/ .

Serving the incorrect Content-Type of image/jpg to IE can cause issues, see http://www.bennadel.com/blog/2609-internet-explorer-aborts-images-with-the-wrong-mime-type.htm.

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

Performing Inserts and Updates with Dapper

We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: https://code.google.com/archive/p/dapper-dot-net/issues/6 for progress.

In the mean time you can do the following

val = "my value";
cnn.Execute("insert into Table(val) values (@val)", new {val});

cnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});

etcetera

See also my blog post: That annoying INSERT problem

Update

As pointed out in the comments, there are now several extensions available in the Dapper.Contrib project in the form of these IDbConnection extension methods:

T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();

Abstract variables in Java?

To add per-class metadata, maybe an annotation might be the correct way to go.

However, you can't enforce the presence of an annotation in the interface, just as you can't enforce static members or the existence of a specific constructor.

Running bash script from within python

Actually, you just have to add the shell=True argument:

subprocess.call("sleep.sh", shell=True)

But beware -

Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

source

How to uncheck checkbox using jQuery Uniform library

you need to call $.uniform.update() if you update element using javascript as mentioned in the documentation.

How to take screenshot of a div with JavaScript?

No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the HTMLCanvasElement object's toDataURL function to get a data: URI with the image's contents.

When the quiz is finished, do this:

var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */

When the user clicks "Capture", do this:

window.open('', document.getElementById('the_canvas_element_id').toDataURL());

This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

Ctrl-Alt-X is the keyboard shortcut I use, although that may because I have Resharper installed - otherwise Ctrl W, X.

From the menu: View -> Toolbox.

You can easily view/change key bindings using Tools -> Options Environment->Keyboard. It has a convenient UI where you can enter a word, and it shows you what key bindings include that word, including View.Toolbox.

You might want to browse through the online MSDN documentation on getting started with Visual Studio.

org.json.simple cannot be resolved

I was facing same issue in my Spring Integration project. I added below JSON dependencies in pom.xml file. It works for me.

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
</dependency>

A list of versions can be found here: https://mvnrepository.com/artifact/org.json/json

How can I detect browser type using jQuery?

You can use this code to find correct browser and you can make changes for any target browser.....

_x000D_
_x000D_
function myFunction() { _x000D_
        if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){_x000D_
            alert('Opera');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Chrome") != -1 ){_x000D_
            alert('Chrome');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Safari") != -1){_x000D_
            alert('Safari');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Firefox") != -1 ){_x000D_
             alert('Firefox');_x000D_
        }_x000D_
        else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){_x000D_
          alert('IE'); _x000D_
        }  _x000D_
        else{_x000D_
           alert('unknown');_x000D_
        }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>Browser detector</title>_x000D_
_x000D_
</head>_x000D_
<body onload="myFunction()">_x000D_
// your code here _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Comparing the contents of two files in Sublime Text

UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation...)

  1. In the Menu bar click on File->Open Folder...
  2. Select a folder (the actual folder does not really matter, this step is just to make the FOLDERS sidebar available)
  3. If there is no Side Bar shown yet, make it appear via View -> Side Bar -> Show Side Bar
  4. Use this FOLDERS-titled Side Bar to navigate to the first file you want to compare.
  5. Select it (click on it), hold down ctrl and select the second file.
  6. Having two files selected, right click on one of the two and select Diff Files...

There should be a new Tab now showing the comparison.


Original short answer:
Note that:

The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.

How to undo "git commit --amend" done instead of "git commit"

Almost 9 years late to this but didn't see this variation mentioned accomplishing the same thing (it's kind of a combination of a few of these, similar to to top answer (https://stackoverflow.com/a/1459264/4642530).

Search all detached heads on branch

git reflog show origin/BRANCH_NAME --date=relative

Then find the SHA1 hash

Reset to old SHA1

git reset --hard SHA1

Then push it back up.

git push origin BRANCH_NAME

Done.

This will revert you back to the old commit entirely.

(Including the date of the prior overwritten detached commit head)

HTTP POST with Json on Body - Flutter/Dart

This one is for using HTTPClient class

 request.headers.add("body", json.encode(map));

I attached the encoded json body data to the header and added to it. It works for me.

'^M' character at end of lines

The ^M is typically caused by the Windows operator newlines, and translated onto Unix looks like a ^M. The command dos2unix should remove them nicely

dos2unix [options] [-c convmode] [-o file ...] [-n infile outfile ...]

The Use of Multiple JFrames: Good or Bad Practice?

I think using multiple Jframes is not a good idea.

Instead we can use JPanels more than one or more JPanel in the same JFrame.

Also we can switch between this JPanels. So it gives us freedom to display more than on thing in the JFrame.

For each JPanel we can design different things and all this JPanel can be displayed on the single JFrameone at a time.

To switch between this JPanels use JMenuBar with JMenuItems for each JPanelor 'JButtonfor eachJPanel`.

More than one JFrame is not a good practice, but there is nothing wrong if we want more than one JFrame.

But its better to change one JFrame for our different needs rather than having multiple JFrames.

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

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

Use the range's NumberFormat property to force the format of the range like this:

Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

How do I connect C# with Postgres?

You want the NPGSQL library. Your only other alternative is ODBC.

Typescript - multidimensional array initialization

Beware of the use of push method, if you don't use indexes, it won't work!

var main2dArray: Things[][] = []

main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)

gives only a 1 line array!

use

main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray

to get your 2d array working!!!

Other beware! foreach doesn't seem to work with 2d arrays!

How can I plot separate Pandas DataFrames as subplots?

You can see e.gs. in the documentation demonstrating joris answer. Also from the documentation, you could also set subplots=True and layout=(,) within the pandas plot function:

df.plot(subplots=True, layout=(1,2))

You could also use fig.add_subplot() which takes subplot grid parameters such as 221, 222, 223, 224, etc. as described in the post here. Nice examples of plot on pandas data frame, including subplots, can be seen in this ipython notebook.

How to "grep" for a filename instead of the contents of a file?

find . | grep KeywordToSearch

Here . means current directory which is value for path parameter for find command. It is piped to grep to search keyword which should return all matching result.

Note: This is case sensitive. So for example fileName and FileName are not same.

How to pass dictionary items as function arguments in python?

You can just pass it

def my_function(my_data):
    my_data["schoolname"] = "something"
    print my_data

or if you really want to

def my_function(**kwargs):
    kwargs["schoolname"] = "something"
    print kwargs

CSS fixed width in a span

In an ideal world you'd achieve this simply using the following css

<style type="text/css">

span {
  display: inline-block;
  width: 50px;
}

</style>

This works on all browsers apart from FF2 and below.

Firefox 2 and lower don't support this value. You can use -moz-inline-box, but be aware that it's not the same as inline-block, and it may not work as you expect in some situations.

Quote taken from quirksmode

TypeScript typed array usage

You have an error in your syntax here:

this._possessions = new Thing[100]();

This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:

this._possessions = [];

Of the array constructor if you want to set the length:

this._possessions = new Array(100);

I have created a brief working example you can try in the playground.

module Entities {  

    class Thing {

    }        

    export class Person {
        private _name: string;
        private _possessions: Thing[];
        private _mostPrecious: Thing;

        constructor (name: string) {
            this._name = name;
            this._possessions = [];
            this._possessions.push(new Thing())
            this._possessions[100] = new Thing();
        }
    }
}

Certificate is trusted by PC but not by Android

could be that you're missing the certificate on your device.

try looking at this answer: How to install trusted CA certificate on Android device? to see how to install the CA on your own device.

Event system in Python

If you wanted to do more complicated things like merging events or retry you can use the Observable pattern and a mature library that implements that. https://github.com/ReactiveX/RxPY . Observables are very common in Javascript and Java and very convenient to use for some async tasks.

from rx import Observable, Observer


def push_five_strings(observer):
        observer.on_next("Alpha")
        observer.on_next("Beta")
        observer.on_next("Gamma")
        observer.on_next("Delta")
        observer.on_next("Epsilon")
        observer.on_completed()


class PrintObserver(Observer):

    def on_next(self, value):
        print("Received {0}".format(value))

    def on_completed(self):
        print("Done!")

    def on_error(self, error):
        print("Error Occurred: {0}".format(error))

source = Observable.create(push_five_strings)

source.subscribe(PrintObserver())

OUTPUT:

Received Alpha
Received Beta
Received Gamma
Received Delta
Received Epsilon
Done!

How to check currently internet connection is available or not in android

Deprecated on API 29.

getActiveNetworkInfo is deprecated from in API 29. So we can use it in bellow 29.

New code in Kotlin for All the API

fun isNetworkAvailable(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
   
    // For 29 api or above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?: return false
        return when {
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ->    true
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ->   true
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ->   true
            else ->     false
         }
    }
    // For below 29 api
    else {
        if (connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo!!.isConnectedOrConnecting) {
            return true
        }
    }
    return false
}

Eclipse DDMS error "Can't bind to local 8600 for debugger"

For people running Android Studio and Eclipse:

I know that answers are already saturated, but I'll just add that it appears that this error surfaces after installing Android Studio and returning to Eclipse to build and run your project.

Make sure you close all other instances of ADB that may be running (including Android Studio). Once you've done this if you are still having troubles try killing all ADB server processes and restarting. If you haven't setup a global variable, open terminal and navigate to the platform-tools folder of the Android SDK Eclipse is referencing, then run:

./adb kill-server
./adb start-server

How do I load a file into the python console?

From the shell command line:

python file.py

From the Python command line

import file

or

from file import *

Using bootstrap with bower

You have install nodeJs on your system in order to execute npm commands. Once npm is properly working you can visit bower.io. There you will find complete documentation on this topic. You will find a command $ npm install bower. this will install bower on your machine. After installing bower you can install Bootstrap easily.

Here is a video tutorial on that

Arithmetic operation resulted in an overflow. (Adding integers)

The maximum value of an integer (which is signed) is 2147483647. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.

If that exception wouldn't be thrown, you'd have a value of -2145629296 for your Volume, which is most probably not wanted.

Solution: Use an Int64 for your volume. With a max value of 9223372036854775807, you're probably more on the safe side.

how to fetch array keys with jQuery?

Don't Reinvent the Wheel, Use Underscore

I know the OP specifically mentioned jQuery but I wanted to put an answer here to introduce people to the helpful Underscore library if they are not aware of it already.

By leveraging the keys method in the Underscore library, you can simply do the following:

_.keys(foo)  #=> ["alfa", "beta"]

Plus, there's a plethora of other useful functions that are worth perusing.

Ignore 'Security Warning' running script from command line

Did you download the script from internet?

Then remove NTFS stream from the file using sysinternal's streams.exe on command line.

cmd> streams.exe .\my.ps1

Now try to run the script again.

how to create dynamic two dimensional array in java?

Here is a simple example. this method will return a 2 dimensional tType array

public tType[][] allocate(Class<tType> c,int row,int column){
        tType [][] matrix = (tType[][]) Array.newInstance(c,row);
        for (int i = 0; i < column; i++) {
            matrix[i] = (tType[]) Array.newInstance(c,column);
        }
        return matrix;

    }

say you want a 2 dimensional String array, then call this function as

String [][] stringArray = allocate(String.class,3,3);

This will give you a two dimensional String array with 3 rows and 3 columns; Note that in Class<tType> c -> c cannot be primitive type like say, int or char or double. It must be non-primitive like, String or Double or Integer and so on.

Getting list of tables, and fields in each, in a database

SELECT * FROM INFORMATION_SCHEMA.COLUMNS

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

Grep regex NOT containing string

patterns[1]="1\.2\.3\.4.*Has exploded"
patterns[2]="5\.6\.7\.8.*Has died"
patterns[3]="\!9\.10\.11\.12.*Has exploded"

for i in {1..3}
 do
grep "${patterns[$i]}" logfile.log
done

should be the the same as

egrep "(1\.2\.3\.4.*Has exploded|5\.6\.7\.8.*Has died)" logfile.log | egrep -v "9\.10\.11\.12.*Has exploded"    

What is the T-SQL syntax to connect to another SQL Server?

Update: for connecting to another sql server and executing sql statements, you have to use sqlcmd Utility. This is typically done in a batch file. You can combine this with xmp_cmdshell if you want to execute it within management studio.


one way is to configure a linked server. then you can append the linked server and the database name to the table name. (select * from linkedserver.database.dbo.TableName)

USE master
GO
EXEC sp_addlinkedserver 
    'SEATTLESales',
    N'SQL Server'
GO

Text to speech(TTS)-Android

public class Texttovoice extends ActionBarActivity implements OnInitListener {
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_texttovoice);
    tts = new TextToSpeech(this, this);

    // Refer 'Speak' button
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    // Refer 'Text' control
    txtText = (EditText) findViewById(R.id.txtText);
    // Handle onClick event for button 'Speak'
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // Method yet to be defined
            speakOut();
        }

    });

}

private void speakOut() {
    // Get the text typed
    String text = txtText.getText().toString();
    // If no text is typed, tts will read out 'You haven't typed text'
    // else it reads out the text you typed
    if (text.length() == 0) {
        tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
    } else {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

    }

}

public void onDestroy() {
    // Don't forget to shutdown!
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.texttovoice, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void onInit(int status) {
    // TODO Auto-generated method stub
    // TTS is successfully initialized
    if (status == TextToSpeech.SUCCESS) {
        // Setting speech language
        int result = tts.setLanguage(Locale.US);
        // If your device doesn't support language you set above
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            // Cook simple toast message with message
            Toast.makeText(getApplicationContext(), "Language not supported",
                    Toast.LENGTH_LONG).show();
            Log.e("TTS", "Language is not supported");
        }
        // Enable the button - It was disabled in main.xml (Go back and
        // Check it)
        else {
            btnSpeak.setEnabled(true);
        }
        // TTS is not initialized properly
    } else {
        Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
                .show();
        Log.e("TTS", "Initilization Failed");
    }
}
   //-------------------------------XML---------------

  <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText" >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="15dip"
    android:text="listen your text"
    android:textColor="#0587d9"
    android:textSize="26dip"
    android:textStyle="bold" />

<EditText
    android:id="@+id/txtText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dip"
    android:layout_marginTop="20dip"
    android:hint="Enter text to speak" />

<Button
    android:id="@+id/btnSpeak"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dip"
    android:enabled="false"
    android:text="Speak" 
    android:onClick="speakout"/>

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

How to add a delay for a 2 or 3 seconds

System.Threading.Thread.Sleep(
    (int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);

Or with using statements:

Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);

I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

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

C++17 has <experimental\filesystem> which is based on the boost version.

Use std::experimental::filesystem::remove_all to remove recursively.

If you need more control, try std::experimental::filesystem::recursive_directory_iterator.

You can also write your own recursion with the non-resursive version of the iterator.

namespace fs = std::experimental::filesystem;
void IterateRecursively(fs::path path)
{
  if (fs::is_directory(path))
  {
    for (auto & child : fs::directory_iterator(path))
      IterateRecursively(child.path());
  }

  std::cout << path << std::endl;
}

How to display errors on laravel 4?

Go to app/config/app.php

and set 'debug' => true,

How to delete all files older than 3 days when "Argument list too long"?

Can also use:

find . -mindepth 1 -mtime +3 -delete

To not delete target directory

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

After downloading the two zip files related to Oracle 11G R2. Create a folder in some directory (For say "Oracle_11G_R2"). Extract both zip files into the same folder "Oracle_11G_R2". And run setup.exe file present inside /database/setup.exe. It should run correctly now.

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

You don't create subfolders of the drawable folder but rather 'sibling' folders next to it under the /res folder for the different screen densities or screen sizes. The /drawable folder (without any dimension) is mostly used for drawables that don't relate to any screen sizes like selectors.

See this screenshot (use the name drawable-hdpi instead of mipmap-hdpi):

enter image description here

org.hibernate.MappingException: Unknown entity: annotations.Users

Use EntityScanner if you can bear external dependency.It will inject your all entity classes seamlessly even from multiple packages. Just add following line after configuration setup.

Configuration configuration = new Configuration().configure();    
EntityScanner.scanPackages("com.fz.epms.db.model.entity").addTo(configuration);
// And following depencency if you are using Maven
<dependency>
        <groupId>com.github.v-ladynev</groupId>
        <artifactId>fluent-hibernate-core</artifactId>
        <version>0.3.1</version>
</dependency>

This way you don't need to declare all entities in hibernate mapping file.

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

Compare dates in MySQL

this is what it worked for me:

select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
 AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load

Database development mistakes made by application developers

Not paying enough attention towards managing database connections in your application. Then you find out the application, the computer, the server, and the network is clogged.

What is the best (and safest) way to merge a Git branch into master?

I always get merge conflicts when doing just git merge feature-branch. This seems to work for me:

git checkout -b feature-branch

Do a bunch of code changes...

git merge -s ours master 
git checkout master
git merge feature-branch

or

git checkout -b feature-branch

Do a bunch of code changes...

git checkout master
git merge -X theirs feature-branch

How to split a single column values to multiple column values?

Your approach won't deal with lot of names correctly but...

SELECT CASE
         WHEN name LIKE '% %' THEN LEFT(name, Charindex(' ', name) - 1)
         ELSE name
       END,
       CASE
         WHEN name LIKE '% %' THEN RIGHT(name, Charindex(' ', Reverse(name)) - 1)
       END
FROM   YourTable 

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

The specific instructions for what you are looking for are in here: https://support.google.com/docs/answer/3093281

Remember your Google Spreadsheets Formulas might use semicolon (;) instead of comma (,) depending on Regional Settings.

Once made the replacement on some examples would look like this:

=GoogleFinance("CURRENCY:USDEUR")
=INDEX(GoogleFinance("USDEUR","price",today()-30,TODAY()),2,2)
=SPARKLINE(GoogleFinance("USDEUR","price",today()-30,today()))

How do I make case-insensitive queries on Mongodb?

To find case Insensitive string use this,

var thename = "Andrew";
db.collection.find({"name":/^thename$/i})

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

This is how you should be using mysql_fetch_assoc():

$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    // Do stuff with $row
}

$result should be a resource. Even if the query returns no rows, $result is still a resource. The only time $result is a boolean value, is if there was an error when querying the database. In which case, you should find out what that error is by using mysql_error() and ensure that it can't happen. Then you don't have to hide from any errors.

You should always cover the base that errors may happen by doing:

if (!$result) {
    die(mysql_error());
}

At least then you'll be more likely to actually fix the error, rather than leave the users with a glaring ugly error in their face.

Changing image size in Markdown

Try:

![image|<SCALE(64x64)>](IMG_URL)

Example:

![image|12x12](https://www.flaticon.com/svg/vstatic/svg/497/497738.svg?token=exp=1611421025~hmac=7f2922952f84017ad7e06a850bb5ce66)

500 internal server error at GetResponse()

For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:

catch (WebException webex)
{
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
}

What is the canonical way to trim a string in Ruby without creating a new string?

Btw, now ruby already supports just strip without "!".

Compare:

p "abc".strip! == " abc ".strip!  # false, because "abc".strip! will return nil
p "abc".strip == " abc ".strip    # true

Also it's impossible to strip without duplicates. See sources in string.c:

static VALUE
rb_str_strip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}

ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

Update 1: As I see now -- it was created in 1999 year (see rev #372 in SVN):

Update2: strip! will not create duplicates — both in 1.9.x, 2.x and trunk versions.

What is the difference between a generative and a discriminative algorithm?

In practice, the models are used as follows.

In discriminative models, to predict the label y from the training example x, you must evaluate:

enter image description here

which merely chooses what is the most likely class y considering x. It's like we were trying to model the decision boundary between the classes. This behavior is very clear in neural networks, where the computed weights can be seen as a complexly shaped curve isolating the elements of a class in the space.

Now, using Bayes' rule, let's replace the enter image description here in the equation by enter image description here. Since you are just interested in the arg max, you can wipe out the denominator, that will be the same for every y. So, you are left with

enter image description here

which is the equation you use in generative models.

While in the first case you had the conditional probability distribution p(y|x), which modeled the boundary between classes, in the second you had the joint probability distribution p(x, y), since p(x | y) p(y) = p(x, y), which explicitly models the actual distribution of each class.

With the joint probability distribution function, given a y, you can calculate ("generate") its respective x. For this reason, they are called "generative" models.

LDAP filter for blank (empty) attribute

The schema definition for an attribute determines whether an attribute must have a value. If the manager attribute in the example given is the attribute defined in RFC4524 with OID 0.9.2342.19200300.100.1.10, then that attribute has DN syntax. DN syntax is a sequence of relative distinguished names and must not be empty. The filter given in the example is used to cause the LDAP directory server to return only entries that do not have a manager attribute to the LDAP client in the search result.

How to check whether a file is empty or not?

if you have the file object, then

>>> import os
>>> with open('new_file.txt') as my_file:
...     my_file.seek(0, os.SEEK_END) # go to end of file
...     if my_file.tell(): # if current position is truish (i.e != 0)
...         my_file.seek(0) # rewind the file for later use 
...     else:
...         print "file is empty"
... 
file is empty

How to create a directory if it doesn't exist using Node.js?

One Line Solution: Creates directory if NOT exist

// import
const fs = require('fs')  // in javascript
import * as fs from "fs"  // in typescript
import fs from "fs"       // in typescript

// use
!fs.existsSync(`./assets/`) && fs.mkdirSync(`./assets/`, { recursive: true })

SyntaxError: cannot assign to operator

What do you think this is supposed to be: ((t[1])/length) * t[1] += string

Python can't parse this, it's a syntax error.

Resetting MySQL Root Password with XAMPP on Localhost

You can configure it with the "XAMPP Shell" (command prompt). Open the shell and execute this command:

mysqladmin.exe -u root password secret

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

Just use multiple in-clauses to get around this:

select field1, field2, field3 from table1 
where  name in ('value1', 'value2', ..., 'value999') 
    or name in ('value1000', ..., 'value1999') 
    or ...;

How to convert a Drawable to a Bitmap?

A Drawable can be drawn onto a Canvas, and a Canvas can be backed by a Bitmap:

(Updated to handle a quick conversion for BitmapDrawables and to ensure that the Bitmap created has a valid size)

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

Detailed 500 error message, ASP + IIS 7.5

I have come to the same problem and fixed the same way as Alex K.

So if "Send Errors To Browser" is not working set also this:

Error Pages -> 500 -> Edit Feature Settings -> "Detailed Errors"

enter image description here

Also note that if the content of the error page sent back is quite short and you're using IE, IE will happily ignore the useful content sent back by the server and show you its own generic error page instead. You can turn this off in IE's options, or use a different browser.

sudo: docker-compose: command not found

The output of dpkg -s ... demonstrates that docker-compose is not installed from a package. Without more information from you there are at least two possibilities:

  1. docker-compose simply isn't installed at all, and you need to install it.

    The solution here is simple: install docker-compose.

  2. docker-compose is installed in your $HOME directory (or other location not on root's $PATH).

    There are several solution in this case. The easiest is probably to replace:

    sudo docker-compose ...
    

    With:

    sudo `which docker-compose` ...
    

    This will call sudo with the full path to docker-compose.

    You could alternatively install docker-compose into a system-wide directory, such as /usr/local/bin.

How to clear radio button in Javascript?

If you have a radio button with same id, then you can clear the selection

Radio Button definition :

<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD

Clearing all values of radio button:

document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;
...

How to select last one week data from today's date

to select records for the last 7 days

WHERE Created_Date >= DATEADD(day, -7, GETDATE())

to select records for the current week

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 8 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

if you want to select records for last week instead of the last 7 days

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM  
WHERE CreatedDate >= DATEADD(day, -(DATEPART(dw, GETDATE()) + 6), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

How to use onClick() or onSelect() on option tag in a JSP page?

example dom onchange usage:

<select name="app_id" onchange="onAppSelection(this);">
    <option name="1" value="1">space.ecoins.beta.v3</option>
    <option name="2" value="2">fun.rotator.beta.v1</option>
    <option name="3" value="3">fun.impactor.beta.v1</option>
    <option name="4" value="4">fun.colorotator.beta.v1</option>
    <option name="5" value="5">fun.rotator.v1</option>
    <option name="6" value="6">fun.impactor.v1</option>
    <option name="7" value="7">fun.colorotator.v1</option>
    <option name="8" value="8">fun.deluxetor.v1</option>
    <option name="9" value="9">fun.winterotator.v1</option>
    <option name="10" value="10">fun.eastertor.v1</option>
    <option name="11" value="11">info.locatizator.v3</option>
    <option name="12" value="12">market.apks.ecoins.v2</option>
    <option name="13" value="13">fun.ecoins.v1b</option>
    <option name="14" value="14">place.sin.v2b</option>
    <option name="15" value="15">cool.poczta.v1b</option>
    <option name="16" value="16" id="app_id" selected="">systems.ecoins.launch.v1b</option>
    <option name="17" value="17">fun.eastertor.v2</option>
    <option name="18" value="18">space.ecoins.v4b</option>
    <option name="19" value="19">services.devcode.v1b</option>
    <option name="20" value="20">space.bonoloto.v1b</option>
    <option name="21" value="21">software.devcode.vpnfree.uk.v1</option>
    <option name="22" value="22">software.devcode.smsfree.v1b</option>
    <option name="23" value="23">services.devcode.smsfree.v1b</option>
    <option name="24" value="24">services.devcode.smsfree.v1</option>
    <option name="25" value="25">software.devcode.smsfree.v1</option>
    <option name="26" value="26">software.devcode.vpnfree.v1b</option>
    <option name="27" value="27">software.devcode.vpnfree.v1</option>
    <option name="28" value="28">software.devcode.locatizator.v1</option>
    <option name="29" value="29">software.devcode.netinfo.v1b</option>
    <option name="-1" value="-1">none</option>
</select>


<script type="text/javascript">

    function onAppSelection(selectBox) {
        // clear selection
        for(var i=0;i<=selectBox.length;i++) {
          var selectedNode  = selectBox.options[i];
             if(selectedNode!=null) {
                  selectedNode.removeAttribute("id");
                  selectedNode.removeAttribute("selected");
            }
        } 
        // assign  id and selected
        var selectedNode = selectBox.options[selectBox.selectedIndex];
        if(selectedNode!=null) {
            selectedNode.setAttribute("id","app_id");
            selectedNode.setAttribute("selected","");
        }
     }

</script>

MetadataException: Unable to load the specified metadata resource

After hours of googling and trying to solve none of the solutions suggested worked. I have listed several solution here. I have also noted the one that worked for me. (I was using EF version 6.1.1, and SQL server 2014 - but an older DB)

  1. Rebuilding the project and try again.
  2. Close and open VS - I don't know how this works
  3. make sure if you have placed the .EDMX file inside a Directory, make sure you include the Directories in your ConnectionString. for example mine is inside DAL folder. SO it looks like this: connectionString="metadata=res://*/DAL.nameModel.csdl|res://*/DAL.nameModel.ssdl|res://*/DAL.nameModel.msl;(these are files. to see them you can toggle Show All Files in solution explorer, under ~/obj/.. directory)

...and many more which I had tried [like: reverting the EntityFramework version to a later version(not sure about it)]


what worked for me:

from this article here, it helped me solve my problem. I just changed my ProviderManifestToken="2012" to ProviderManifestToken="2008" in the EDMX file. To do this:

Solution Explorer

  1. Right click over file .edmx
  2. Open with..
  3. Editor XML
  4. Change ProviderManifestToken="XXXX" with 2008

I hope that helps.

Make a nav bar stick

add to your .nav css block the

position: fixed

and it will work

What is the difference between a pandas Series and a single-column DataFrame?

from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:

import pandas as pd
ds = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.

import pandas as pd
df = pd.DataFrame(data, index=index)

In both of the above index is list

for example: I have a csv file with following data:

,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi

To read above data as series and data frame:

import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index =  file_data.index)

output:

>>> d
BR           Brazil
RU           Russia
IN            India

df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )

output:

>>> df
      area
BR   12015
RU     457
IN  457787

How to get first/top row of the table in Sqlite via Sql Query

LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

JSON forEach get Key and Value

Another easy way to do this is by using the following syntax to iterate through the object, keeping access to the key and value:

for(var key in object){
  console.log(key + ' - ' + object[key])
}

so for yours:

for(var key in obj){
  console.log(key + ' - ' + obj[key])
}

How to: "Separate table rows with a line"

There are several ways to do that. Using HTML alone, you can write

<table border=1 frame=void rules=rows>

or, if you want a border above the first row and below the last row too,

<table border=1 frame=hsides rules=rows>

This is rather inflexible, though; you cannot e.g. make the lines dotted this way, or thicker than one pixel. This is why in the past people used special separator rows, consisting of nothing but some content intended to produce a line (it gets somewhat dirty, especially when you need to make rows e.g. just a few pixels high, but it’s possible).

For the most of it, people nowadays use CSS border properties for the purpose. It’s fairly simple and cross-browser. But note that to make the lines continuous, you need to prevent spacing between cells, using either the cellspacing=0 attribute in the table tag or the CSS rule table { border-collapse: collapse; }. Removing such spacing may necessitate adding some padding (with CSS, preferably) inside the cells.

At the simplest, you could use

<style>
table {
  border-collapse: collapse;
}
tr { 
  border: solid;
  border-width: 1px 0;
}
</style>

This puts a border above the first row and below the last row too. To prevent that, add e.g. the following into the style sheet:

tr:first-child {
  border-top: none;
}
tr:last-child {
  border-bottom: none;
}

initialize a const array in a class initializer in C++

Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.

int* a = new int[N];
// fill a

class C {
  const std::vector<int> v;
public:
  C():v(a, a+N) {}
};

What is the purpose of the vshost.exe file?

It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.

How to measure time taken between lines of code in python?

You can try this as well:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

Change language of Visual Studio 2017 RC

I solved this just created label on desktop with option/parameter --locale en-US

"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installer.exe" --locale en-US

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

echo date('D', strtotime($date));
echo date('l', strtotime($date));

Result

Tue
Tuesday

Is there any method to get the URL without query string?

Use properties of window.location

var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;

You can see more properties at https://developer.mozilla.org/en/DOM/window.location

checking for typeof error in JS

I asked the original question - @Trott's answer is surely the best.

However with JS being a dynamic language and with there being so many JS runtime environments, the instanceof operator can fail especially in front-end development when crossing boundaries such as iframes. See: https://github.com/mrdoob/three.js/issues/5886

If you are ok with duck typing, this should be good:

let isError = function(e){
 return e && e.stack && e.message;
}

I personally prefer statically typed languages, but if you are using a dynamic language, it's best to embrace a dynamic language for what it is, rather than force it to behave like a statically typed language.

if you wanted to get a little more precise, you could do this:

   let isError = function(e){
     return e && e.stack && e.message && typeof e.stack === 'string' 
            && typeof e.message === 'string';
    }

Simple way to understand Encapsulation and Abstraction

Encapsulation is what it sounds like, a way of putting a box around something to protect its contents. Abstraction is extracting the functional properties of something such that you can perform operations using only what you've extracted without knowledge of the inner workings.

When we say that two substances are liquids we are using "liquid" as an abstraction over the properties of those substances we're choosing to discuss. That abstraction tells us the things we can do with the substances given our previous experience with liquids.

Abstraction also doesn't really have anything to do with heirarchies. You can have another abstraction like "metals" that extracts properties of substances in a different way.

Abstractions forget details, so if you're using a particular abstraction you shouldn't ask about properties of the underlying substance that aren't granted by the abstraction. Like if you take milk and water and mix them together, you have a hard time then asking how much milk you have.

A Functor is an abstraction over something that has some notion of map, that is, you can run a function on its inner contents that transforms the inner bit into anything else. The outer something stays the same kind of thing.

Where this gets useful is that if you have a function that works on Lists and you realise you're only depending on the map interface, you can instead depend on Functor and then your function can work with streams, promises, maybes, tuples, and anything else that shares that abstraction.

Functional languages like Haskell have some really great powers of abstraction that make extreme code reuse practical.

MAMP mysql server won't start. No mysql processes are running

You need to leave the mysql database AS IS.

  • Uninstall and reinstall MAMP Pro.
  • For every WP instance that you want to have on your server (localhost), you need to create a NEW database that is not mysql.
  • Go into SequelPro and add database.
  • Use Duplicator to transfer your WP.

Do not use mysql for anything, it appears to be required by MAMP.

Git pull command from different user

Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:

  1. Your friend pushes his changes to GitHub:

    git push origin <branch>
    
  2. Clone the remote repository if you haven't already:

    git clone https://[email protected]/abc/theproject.git
    
  3. Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):

    git fetch origin
    git merge origin/<branch>
    

    Note that git pull is the same as doing the two steps above:

    git pull origin <branch>
    

See Also

"Unknown class <MyClass> in Interface Builder file" error at runtime

Go to the "ProjectName" , click on it , and then go the "Build phases" tab , and then click on the "compile sources" , and then click on "+" button , a window will appear , the choose "MyClass.m" file and then click "add" ,

Build the Project and Run it , the problem will surely get solved out

How to set the height of table header in UITableView?

@kris answer is helpful for me anyone want it in Objective-C.

Here is the code

-(void)viewDidLayoutSubviews{
     [super viewDidLayoutSubviews];
     [self sizeHeaderToFit];
}

-(void)sizeHeaderToFit{
     UIView *headerView = self.tableView.tableHeaderView;
     [headerView setNeedsLayout];
     [headerView layoutIfNeeded];
     CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
     CGRect frame = headerView.frame;
     frame.size.height = height;
     headerView.frame = frame;
     self.tableView.tableHeaderView = headerView;
}

Add a CSS class to <%= f.submit %>

As Srdjan Pejic says, you can use

<%= f.submit 'name', :class => 'button' %>

or the new syntax which would be:

<%= f.submit 'name', class: 'button' %>

Why does Git treat this text file as a binary file?

I had a similar issue as I pasted some text from a binary Kafka message, which inserted non-visible character and caused git to think the file is binary.

I found the offending characters by searching the file using regex [^ -~\n\r\t]+.

  • [ match characters in this set
  • ^ match characters not in this set
  • -~ matches all characters from ' ' (space) to '~'
  • \n newline
  • \r carriage return
  • \t tab
  • ] close set
  • + match one or more of these characters

Setting a system environment variable from a Windows batch file?

SetX is the command that you'll need in most of the cases.Though its possible to use REG or REGEDIT

Using registry editing commands you can avoid some of the restrictions of the SetX command - different data types, variables containing = in their name and so on.

@echo off

:: requires admin elevated permissions
::setting system variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v MyVar /D MyVal
::expandable variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /T REG_EXPAND_SZ /v MyVar /D MyVal


:: does not require admin permissions
::setting user variable
REG ADD "HKEY_CURRENT_USER\Environment" /v =C: /D "C:\\test"

REG is the pure registry client but its possible also to import the data with REGEDIT though it allows using only hard coded values (or generation of a temp files). The example here is a hybrid file that contains both batch code and registry data (should be saved as .bat - mind that in batch ; are ignored as delimiters while they are used as comments in .reg files):

REGEDIT4

; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"SystemVariable"="GlobalValue"

[HKEY_CURRENT_USER\Environment]
"UserVariable"="SomeValue"

jQuery bind/unbind 'scroll' event on $(window)

Very old question, but in case someone else stumbles across it, I would recommend trying:

$j("html, body").stop(true, true).animate({
        scrollTop: $j('#main').offset().top 
}, 300);

Generate signed apk android studio

Read this my answer here

How do I export a project in the Android studio?

This will guide you step by step to generate signed APK and how to create keystore file from Android Studio.

From the link you can do it easily as I added the screenshot of it step by step.

Short answer

If you have Key-store file then you can do same simply.

Go to Build then click on Generate Signed APK

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

There is a package called eclipse-cdt in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++ already, you need to install that as well, so all you need is:

sudo apt-get install eclipse eclipse-cdt g++

Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudos blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get and hope for the best.

How to do Select All(*) in linq to sql

Why don't you use

DbTestDataContext obj = new DbTestDataContext();
var q =from a in obj.GetTable<TableName>() select a;

This is simple.

Home does not contain an export named Home

Use

import Home from './layouts/Home'

rather than

import { Home } from './layouts/Home'

Remove {} from Home

AVD Manager - Cannot Create Android Virtual Device

Launching the AVD Manager from Visual Studio 2015 resolved this issue for me.

I had (a lot of packages) all the required packages installed but hadn't used them for some time & had issues detecting them in the SDK manager. I attempted all the solutions provided above to no avail, including running the AVD after running the monitor.bat file in 'android/sdk/tools'.

I then launched the AVD from VS in 'Tools->Android->Android Emulator Manager' and it detected both 'Google APIs Intel Atom x86' & the ARM EABI v7a system Images right off the bat!

Target is set to API Level 23.

How to rename a component in Angular CLI?

see angular-rename

install

npm install -g angular-rename

use

$ ./angular-rename OldComponentName NewComponentName

Which HTML elements can receive focus?

Maybe this one can help:

_x000D_
_x000D_
function focus(el){_x000D_
 el.focus();_x000D_
 return el==document.activeElement;_x000D_
}
_x000D_
_x000D_
_x000D_

return value: true = success, false = failed

Reff: https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

jQuery add class .active on menu

window.location.href will give you the current url (as shown in the browser address). After parsing it and retrieving the relevant part you would compare it with each link href and assign the active class to the corresponding link.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

If you read the message carefully you will see that you are using the permissions like camera, Microphone, Contacts, Storage and Phone, etc. and you don't supply a privacy policy. you need to supply a privacy policy if you do that. you can find more information about the android privacy policy on google

To Add Privacy Policy In-Play Console,

  1. Find and select All Apps.

  2. Select the application you need to add your Privacy Policy to.

  3. Find the Policy at the end of the page.

  4. Click App content to edit the listing for your app.

  5. Find the field labeled Privacy Policy and place the URL of the page of your Privacy Policy

  6. Click Save and you are good to go.

Note: You need to have a public web page to host your Privacy Policy. Google Play Store won't host the policy for you.

Unable to Cast from Parent Class to Child Class

The instance that your base class reference is referring to is not an instance of your child class. There's nothing wrong.

More specifically:

Base derivedInstance = new Derived();
Base baseInstance = new Base();

Derived good = (Derived)derivedInstance; // OK
Derived fail = (Derived)baseInstance; // Throws InvalidCastException

For the cast to be successful, the instance that you're downcasting must be an instance of the class that you're downcasting to (or at least, the class you're downcasting to must be within the instance's class hierarchy), otherwise the cast will fail.

Eclipse IDE for Java - Full Dark Theme

Update August 2016:

Tejas Padliya adds in the comments:

Dark theme works well with Eclipse 4.5 onward with Windows 10.
No more black text on black background


Update June 2014:

As mentioned din "Dark Theme, Top Eclipse Luna Feature #5", Eclipse 4.4 (Luna) has a dark theme included in it (see informatik01's comment):

http://eclipsesource.com/blogs/wp-content/uploads/2014/06/darklinux.png

When Eclipse 3.0 shipped in 2004 it brought a new look to the workbench. Now, 10 years later, an entirely new Dark Theme is launching.

The theme extends to more than just the Widgets. Syntax highlighting has also been improved to take advantage of the new look.

The What's new page mentions:

A new dark window theme has been introduced. This popular community theme demonstrates the power of the underlying Eclipse 4 styling engine.
You can enable it from the General > Appearance preference page.
Plug-ins can contribute extensions to this theme to style their own specific views and editors to match the window theme.


Update April 2013:

It seems the solution below don't work well with Eclipse Juno 4.2 and Windows 8, according to Lennart in the comments.

One solution which (mostly) work is the Eclipse Chrome Theme (compatible Juno 4.2 and even Kepler 4.3), from the GitHub project eclipse-themes, by Jeeeyul Lee.

This post mentions:

The first is to change the appearance of what is inside the editor windows.
That can be done with the Eclipse Colour Theme plugin (http://eclipsecolorthemes.org/). My favourite editor theme is Vibrant Ink with the Monaco font. They explain how to install their themes very well (http://eclipsecolorthemes.org/?view=how-to-use), although you get a fine set of dark themes with the default plugin install and may not need to come back to their website for any more. Get the plugin here.

The second stage is darkening the chrome of the UI, which is all the widgets and menus and everything outside of the child window canvases.
This plugin gives you a GUI editor for the chrome colour scheme: https://github.com/jeeeyul/eclipse-themes/.
If you want a dark one, go ahead and click away until eclipse is dark.

Once you are done, some GUI surface area will show through the system theme as mentioned at the top of this post.
Rather than using that editor, you could install the pre-baked Dark Juno theme instead.
The install is manual.
Start by downloading it from here: https://github.com/eclipse-color-theme/eclipse-ui-themes.
It has to be copied into your eclipse dropins folder. This lives next to the eclipse executable, not in your workspace or someplace like that. In my case the command to do the copy was:

cp ./plugins/com.github.eclipsecolortheme.themes_1.0.0.201207121019.jar /usr/lib/eclipse/dropins/

You could be running eclipse from any directory though, so which eclipse will tell you where it should go.
Restart eclipse and you should find a Dark Juno option under Preferences::General::Appearance. It is a nice neutral grey with some gradients and is a very good option.

~~~~~~~~~~~~~~

Update December 2012 (20 months later):

The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":

enter image description here

The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form(like library, framework).
New language is not necessary just for this kind of purpose.


Update July 2012 (15 months later):

I have seen one! (Ie, a fully dark theme for Eclipse), as reported by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":

Eclipse fully dark theme

If you want to play with it, you only need to write a plug-in, create a CSS file and use the org.eclipse.e4.ui.css.swt.theme extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.

pixeldude mentions in the comments having publish "Dark Juno" on GitHub!

Komododave mentions that you don't always need a plugin: see "Ubuntu + Eclipse 4.2 - Dark theme - How to darken sidebar backgrounds?" for an example, based on gtkrc resource.


Original answer: March 2011

Note that a full dark theme will be possible with e4.
(see dynamic css with e4 or A week at e4 – Themeing in e4):

dark theme extension

full dark theme

In the meantime, only for editors though (which isn't what you want but still merit to be mentioned):

www.eclipsecolorthemes.org:

"Fresh up your Eclipse with super-awesome color themes!"

themes for editors

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

ORA-00904: invalid identifier

Also make sure the user issuing the query has been granted the necessary permissions.

For queries on tables you need to grant SELECT permission.
For queries on other object types (e.g. stored procedures) you need to grant EXECUTE permission.

How to break out of multiple loops?

# this version uses a level counter to choose how far to break out

break_levels = 0
while True:
    # snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y":
            break_levels = 1        # how far nested, excluding this break
            break
        if ok == "n" or ok == "N":
            break                   # normal break
    if break_levels:
        break_levels -= 1
        break                       # pop another level
if break_levels:
    break_levels -= 1
    break

# ...and so on

Angular bootstrap datepicker date format does not format ng-model value

I can fix this by adding below code in my JSP file. Now both model and UI values are same.

<div ng-show="false">
    {{dt = (dt | date:'dd-MMMM-yyyy') }}
</div>  

How can I get query string values in JavaScript?

function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 3
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3

JavaScript object: access variable property by name as string

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    function displayFile(whatOption, whatColor) {_x000D_
      var Test01 = {_x000D_
        rectangle: {_x000D_
          red: "RectangleRedFile",_x000D_
          blue: "RectangleBlueFile"_x000D_
        },_x000D_
        square: {_x000D_
          red: "SquareRedFile",_x000D_
          blue: "SquareBlueFile"_x000D_
        }_x000D_
      };_x000D_
      var filename = Test01[whatOption][whatColor];_x000D_
      alert(filename);_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

filecontent()
{
    setGUI();
    setRegister();
    showfile();
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

You would have to include a try catch block:

filecontent()
{
    setGUI();
    setRegister();
    try {
        showfile();
    }
    catch (IOException e) {
        // Do something here
    }
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

In the case of the second:

public void actionPerformed(ActionEvent ae)
{
    if (ae.getSource() == submit)
    {
        showfile();
    }
}

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==submit)
    {
        try {
            showfile();
        }
        catch (IOException e) {
            // Do something here
        }
    }
}

Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

Cannot start MongoDB as a service

I had same issue on windows 8.1

The solution which worked for me is to specify config file path correctly

Going to HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > services > MongoDB > imagePath the value was like the following:

"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe" --config mongod.cfg --service

Then just I corrected config file path to match my actual path:

"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe" --config "d:\mongodb\mongod.cfg" --service

What's the difference between setWebViewClient vs. setWebChromeClient?

WebViewClient provides the following callback methods, with which you can interfere in how WebView makes a transition to the next content.

void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)

WebChromeClient provides the following callback methods, with which your Activity or Fragment can update the surroundings of WebView.

Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)

Eclipse JPA Project Change Event Handler (waiting)

Also, if you cannot find your eclipse dir. Because, I had such problem on mac we can remember that eclipse is using OSGi, so we can go to Target Platform and disable features/plugins that were described above: org.eclipse.jpt.* enter image description here

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader

Abstract Class:-Real Time Example

A good example of real time found from here:-

A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.

A business example:

I have a persistance engine that will work against any data sourcer (XML, ASCII (delimited and fixed-length), various JDBC sources (Oracle, SQL, ODBC, etc.) I created a base, abstract class to provide common functionality in this persistance, but instantiate the appropriate "Port" (subclass) when persisting my objects. (This makes development of new "Ports" much easier, since most of the work is done in the superclasses; especially the various JDBC ones; since I not only do persistance but other things [like table generation], I have to provide the various differences for each database.) The best business examples of Interfaces are the Collections. I can work with a java.util.List without caring how it is implemented; having the List as an abstract class does not make sense because there are fundamental differences in how anArrayList works as opposed to a LinkedList. Likewise, Map and Set. And if I am just working with a group of objects and don't care if it's a List, Map, or Set, I can just use the Collection interface.

Updating the list view when the adapter data changes

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

How do I pass multiple ints into a vector at once?

You can also use Boost.Assignment:

const list<int> primes = list_of(2)(3)(5)(7)(11);

vector<int> v; 
v += 1,2,3,4,5,6,7,8,9;

How to parse a CSV file using PHP

I love this

        $data = str_getcsv($CsvString, "\n"); //parse the rows
        foreach ($data as &$row) {
            $row = str_getcsv($row, "; or , or whatever you want"); //parse the items in rows 
            $this->debug($row);
        }

in my case I am going to get a csv through web services, so in this way I don't need to create the file. But if you need to parser with a file, it's only necessary to pass as string

Java String.split() Regex

str.split (" ") 
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)

How to programmatically set the Image source

{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

Select first and last row from grouped data

Another approach with lapply and a dplyr statement. We can apply an arbitrary number of whatever summary functions to the same statement:

lapply(c(first, last), 
       function(x) df %>% group_by(id) %>% summarize_all(funs(x))) %>% 
bind_rows()

You could for example be interested in rows with the max stopSequence value as well and do:

lapply(c(first, last, max("stopSequence")), 
       function(x) df %>% group_by(id) %>% summarize_all(funs(x))) %>%
bind_rows()

How do you overcome the svn 'out of date' error?

In my case only deleting of the local version and re checkout of fresh copy was a solution.

How to get all groups that a user is a member of?

Single line, no modules necessary, uses current logged user:

(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf

Kudos to this vbs/powershell article: http://technet.microsoft.com/en-us/library/ff730963.aspx

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I've run into this with a couple virtual environments.

pip uninstall MySQL-python
pip install -U MySQL-python

Worked both times.

How to use ng-repeat without an html element

If you use ng > 1.2, here is an example of using ng-repeat-start/end without generating unnecessary tags:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
    <script>_x000D_
      angular.module('mApp', []);_x000D_
    </script>_x000D_
  </head>_x000D_
  <body ng-app="mApp">_x000D_
    <table border="1" width="100%">_x000D_
      <tr ng-if="0" ng-repeat-start="elem in [{k: 'A', v: ['a1','a2']}, {k: 'B', v: ['b1']}, {k: 'C', v: ['c1','c2','c3']}]"></tr>_x000D_
_x000D_
      <tr>_x000D_
        <td rowspan="{{elem.v.length}}">{{elem.k}}</td>_x000D_
        <td>{{elem.v[0]}}</td>_x000D_
      </tr>_x000D_
      <tr ng-repeat="v in elem.v" ng-if="!$first">_x000D_
        <td>{{v}}</td>_x000D_
      </tr>_x000D_
_x000D_
      <tr ng-if="0" ng-repeat-end></tr>_x000D_
    </table>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The important point: for tags used for ng-repeat-start and ng-repeat-end set ng-if="0", to let not be inserted in the page. In this way the inner content will be handled exactly as it is in knockoutjs (using commands in <!--...-->), and there will be no garbage.

Convert String to java.util.Date

java.time

While in 2010, java.util.Date was the class we all used (toghether with DateFormat and Calendar), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss");

        String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14";
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter);
        System.out.println("output here: " + dateTime);

Output is:

output here: 2010-04-29T13:00:14

What went wrong in your code?

The combination of uppercase HH and aaa in your format pattern strings does not make much sense since HH is for hour of day, rendering the AM/PM marker from aaa superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat or the modern DateTimeFormatter:

'aaa' should not be used, if you use 'aaa' then specify 'hh'

Lowercase hh is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.

Other tips

  • In your database, since I understand that SQLite hasn’t got a built-in datetime type, use the standard ISO 8601 format and store time in UTC, for example 2010-04-29T07:30:14Z (the modern Instant class parses and formats such strings as its default, that is, without any explicit formatter).
  • Don’t use an offset such as GMT+05:30 for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.
  • If you wanted to use the outdated DateFormat, its parse method returns a Date, so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

What is simplest way to read a file into String?

Another alternative approach is:

How do I create a Java string from the contents of a file?

Other option is to use utilities provided open source libraries
http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html

Why java doesn't provide such a common util API ?
a) to keep the APIs generic so that encoding, buffering etc is handled by the programmer.
b) make programmers do some work and write/share opensource util libraries :D ;-)

Java String split removed empty values

String[] split = data.split("\\|",-1);

This is not the actual requirement in all the time. The Drawback of above is show below:

Scenerio 1:
When all data are present:
    String data = "5|6|7||8|9|10|";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 7
    System.out.println(splt.length); //output: 8

When data is missing:

Scenerio 2: Data Missing
    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output: 8

Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.

    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output:7

What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.