Programs & Examples On #Crystal reports

Crystal Reports is a report writer that operates as a stand-alone report designer, an integrated part of Visual Studio, or part of SAP's Business Objects Enterprise suite.

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

How to integrate SAP Crystal Reports in Visual Studio 2017

I had exactly the same problem with my VS 2013 solutions when I install VS 2017 and Crystal Reports SP21. In fact it's because VS does not necessarily convert the solution in the first launch.

Once you have installed Crystal Report SP 21, make sure that VS 2017 upgrade your solution : a window must appear "SAP Crystal Reports, version for Visual" with a radio button "Convert the solution".

Screenshot in french :

enter image description here

When I used the menu "File / Open / Project/Solution", the conversion was not done.

I have to do that :

  1. Add VS 2017 on the tasks bar
  2. Run VS 2017 and Open the solution with File menu
  3. Try to build the project, errors appear with Crystal Reports
  4. Close VS 2017
  5. Right click on VS 2017 shortcur in then tasks bar and open the solution directly
  6. The conversion run this time, you can open .rpt and the solution build without error.

How to calculate sum of a formula field in crystal Reports?

(Assuming you are looking at the reports in the Crystal Report Designer...)

Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:

  • Make a summary field: Right-click on the desired formula field in your detail section and choose "Insert Summary". Choose "sum" from the drop-down box and verify that the correct account grouping is selected, then click OK. You will then have a simple sum field in your group footer section.
  • Make a running total field: Click on the "Insert" menu and choose "Running Total Field..."*** Click on the New button and give your new running total field a name. Choose your formula field under "Field to summarize" and choose "sum" under "Type of Summary". Here you can also change when the total is evaluated and reset, leave these at their default if you're wanting a sum on each record. You can also use a formula to determine when a certain field should be counted in the total. (Evaluate: Use Formula)

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

This post is right from SAP on Sep 20, 2012.

In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.

If you want to download that version you can find it here.

Further, service packs etc. when released can be found here.


I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.

How to convert datetime format to date format in crystal report using C#?

Sometimes the field is not recognized by crystal reports as DATE, so you can add a formula with function: Date({YourField}), And add it to the report, now when you open the format object dialog you will find the date formatting options.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Edit Crystal report file without Crystal Report software

I wouldn't have thought so.

If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.

If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

I had the same error after moving to a new laptop (Windows 10). In addition to setting Copy Local to true as mentioned above, I had to install the Crystal Reports 32-bit runtime engine for .Net Framework, even though everything else is set to run in a 64-bit environment. Hope that helps.

Windows Control Panel - Programs and Features

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

Crystal Reports - Adding a parameter to a 'Command' query

When you are in the Command, click Create to create a new parameter; call it project_name. Once you've created it, double click its name to add it to the command's text. You query should resemble:

SELECT Projecttname, ReleaseDate, TaskName
FROM DB_Table
WHERE Project_Name LIKE {?project_name} + '*'
AND ReleaseDate >= getdate() --assumes sql server

If desired, link the main report to the subreport on this ({?project_name}) field. If you don't establish a link between the main and subreport, CR will prompt you for the subreport's parameter.

In versions prior to 2008, a command's parameter was only allowed to be a scalar value.

Crystal Reports 13 And Asp.Net 3.5

I have same problem. I solved install this setup. (I use vs 2015 (4.6))

Formula to check if string is empty in Crystal Reports

You can check for IsNull condition.

If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
  // do something

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

You simply need to install Crystal Report Report Run Time downloads on Deployment Server. If problem still appears, then place check asp_client folder in your project main folder.

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

If the error happens with error column "File" as SGEN, then the fix needs to be in a file sgen.exe.config, next to sgen.exe. For example, for VS 2015, create C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sgen.exe.config. Minimum file contents: <configuration><startup useLegacyV2RuntimeActivationPolicy="true"/></configuration>

Source: SGEN Mixed mode assembly

UPDATE and REPLACE part of a string

Try to remove % chars as below

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4

Polygon Drawing and Getting Coordinates with Google Map API v3

Well, unfortunately it seems that one cannot place custom markers and draw (and obtain coordinates) directly from maps.google.com if one is anonymous/not logged in (as it was possible some years ago, if I recall correctly). Still, thanks to the answers here, I managed to make a combination of examples that has both the Google Places search, and allows drawing via the drawing library, and dumps coordinates upon making a selection of any type of shape (including coordinates for polygon) that can be copypasted; the code is here:

This is how it looks like:

test.png

(The Places markers are handled separately, and can be deleted via the DEL "button" by the search input form element; "curpos" shows the current center [position] and zoom level of the map viewport).

Create a custom event in Java

There are 3 different ways you may wish to set this up:

  1. Thrower inside of Catcher
  2. Catcher inside of Thrower
  3. Thrower and Catcher inside of another class in this example Test

THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional" code block of the class you want to be main, and set that class as the ${Main-Class} variable in the build.xml file:

4 Things needed on throwing side code:

import java.util.*;//import of java.util.event

//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
    public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
    List<ThrowListener> listeners = new ArrayList<ThrowListener>();
    public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
    //Set of functions that Throw Events.
        public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
            System.out.println("Something thrown");
        }
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}

2 Things needed in a class file to receive events from a class

/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
    @Override public void Catch() {
        System.out.println("I caught something!!");
    }
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}

LaTeX: remove blank page after a \part or \chapter

Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.

Derived from book.cls

\def\@endpart{\vfil\newpage
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}

It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.

\makeatletter
\renewcommand\@endpart{\vfil
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}
\makeatother

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I got same error. Because i used v4 alpha class names like carousel-control-next When i changed with v3, problem solved.

What is the difference between Java RMI and RPC?

The only real difference between RPC and RMI is that there is objects involved in RMI: instead of invoking functions through a proxy function, we invoke methods through a proxy.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Not sure if this is the cause of the problem, but I got this issue only after installing JVM Monitor.

Uninstalling JVM Monitor solved the issue for me.

How to add System.Windows.Interactivity to project?

I have had the exact same problem with a solution, that System.Windows.Interactivity was required for one of the project in Visual Studio 2019, and I tried to install Blend for Visual Studio SDK for .NET from Visual Studio 2019 Individual components, but it did not exist in it.

The consequence of that, I was not able to build the project in my solution with repetitive of following similar error on different XAML parts of the project:

The tag 'Interaction.Behaviors' does not exist in XML namespace 'clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity'.

Image with all errors The above mentioned errors snapshot example

The solution, the way I solved it, is by installing Microsoft Expression Blend Software Development Kit (SDK) for .NET 4 from Microsoft.

Thanks to my colleague @felza, mentioned that System.Windows.Interactivity requires this sdk, that is suppose to be located in this folder:

C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0

In my case it was not installed. I have had this folder C:\Program Files (x86)\Microsoft SDKs with out Expression\Blend\.NETFramework\v4.0 folder inside it.

After installing it, all errors disappeared.

The controller for path was not found or does not implement IController

In my case, I was rendering another action method for my menu section in _layout.cshtml file using @Html.Action("Menu", "Menu") whereas I forgot to create Menu controller and as layout file was being used in my current controller action's view therefore I was getting this error in my current action render request. try to look in your layout and as well as view file if you did the same mistake

Parse strings to double with comma and point

To treat both , and . as decimal point you must not only replace one with the other, but also make sure the Culture used parsing interprets it as a decimal point.

text = text.Replace(',', '.');
return double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value);

og:type and valid values : constantly being parsed as og:type=website

I know this is an old one but it comes up top of Google and all the links provided now seem out of date.

This is the latest list of types Facebook accepts: https://developers.facebook.com/docs/reference/opengraph

If you don't use one of these then the type will default to 'website' which is best used for home pages/summarising a web site.

In answer to the OP you would now want to use a place which will allow you to add lat/long location details.

CryptographicException 'Keyset does not exist', but only through WCF

I have faced this issue, my certificates where having private key but i was getting this error("Keyset does not exist")

Cause: Your web site is running under "Network services" account or having less privileges.

Solution: Change Application pool identity to "Local System", reset IIS and check again. If it starts working it is permission/Less privilege issue, you can impersonate then using other accounts too.

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

How to convert TimeStamp to Date in Java?

String timestamp="";
Date temp=null;
try {
    temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDateCurrentTimeZone(Long.parseLong(timestamp)));
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
int dayMonth=temp.getDate();
int dayWeek=temp.getDay();
int hour=temp.getHours();
int minute=temp.getMinutes();
int month=temp.getMonth()+1;
int year=temp.getYear()+1900;

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

How do I output an ISO 8601 formatted string in JavaScript?

There is already a function called toISOString():

var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"

If, somehow, you're on a browser that doesn't support it, I've got you covered:

if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) {
      var r = String(number);
      if ( r.length === 1 ) {
        r = '0' + r;
      }
      return r;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear()
        + '-' + pad( this.getUTCMonth() + 1 )
        + '-' + pad( this.getUTCDate() )
        + 'T' + pad( this.getUTCHours() )
        + ':' + pad( this.getUTCMinutes() )
        + ':' + pad( this.getUTCSeconds() )
        + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
        + 'Z';
    };

  }() );
}

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

It depends. See the MySQL Performance Blog post on this subject: To SQL_CALC_FOUND_ROWS or not to SQL_CALC_FOUND_ROWS?

Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that SQL_CALC_FOUND_ROWS is almost always slower - sometimes up to 10x slower - than running two queries.

SQL (MySQL) vs NoSQL (CouchDB)

One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use

How to support placeholder attribute in IE8 and 9

I used the code of this link http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html

But in browser detection I used:

if (navigator.userAgent.indexOf('MSIE') > -1) {
 //Your placeholder support code here...
}

Iterate two Lists or Arrays with one ForEach statement in C#

You can use Union or Concat, the former removes duplicates, the later doesn't

foreach (var item in List1.Union(List1))
{
   //TODO: Real code goes here
}

foreach (var item in List1.Concat(List1))
{
   //TODO: Real code goes here
}

How can I check that two objects have the same set of property names?

Here is my attempt at validating JSON properties. I used @casey-foster 's approach, but added recursion for deeper validation. The third parameter in function is optional and only used for testing.

//compare json2 to json1
function isValidJson(json1, json2, showInConsole) {

    if (!showInConsole)
        showInConsole = false;

    var aKeys = Object.keys(json1).sort();
    var bKeys = Object.keys(json2).sort();

    for (var i = 0; i < aKeys.length; i++) {

        if (showInConsole)
            console.log("---------" + JSON.stringify(aKeys[i]) + "  " + JSON.stringify(bKeys[i]))

        if (JSON.stringify(aKeys[i]) === JSON.stringify(bKeys[i])) {

            if (typeof json1[aKeys[i]] === 'object'){ // contains another obj

                if (showInConsole)
                    console.log("Entering " + JSON.stringify(aKeys[i]))

                if (!isValidJson(json1[aKeys[i]], json2[bKeys[i]], showInConsole)) 
                    return false; // if recursive validation fails

                if (showInConsole)
                    console.log("Leaving " + JSON.stringify(aKeys[i]))

            }

        } else {

            console.warn("validation failed at " + aKeys[i]);
            return false; // if attribute names dont mactch

        }

    }

    return true;

}

File upload from <input type="file">

There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.

Here is an example based on the first answer:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #file (change)="onChange(file.files)"/>
    </div>
  `,
  providers: [ UploadService ]
})

export class AppComponent {
  onChange(files) {
    console.log(files);
  }
}

Here is an example app to demonstrate this in action.

Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

Force HTML5 youtube video

Inline tag is used to add another src of document to the current html element.

In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link

so add ?html=5 to the end of the link.. :)

ie8 var w= window.open() - "Message: Invalid argument."

Hi using the following code its working...

onclick="window.open('privacy_policy.php','','width=1200,height=800,scrollbars=yes');

Previously i Entered like

onclick="window.open('privacy_policy.php','Window title','width=1200,height=800,scrollbars=yes');

Means Microsoft does not allow you to enter window name it should be blank in window.open function...

Thanks, Nilesh Pangul

What are some uses of template template parameters?

Here is a simple example taken from 'Modern C++ Design - Generic Programming and Design Patterns Applied' by Andrei Alexandrescu:

He uses a classes with template template parameters in order to implement the policy pattern:

// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
   ...
};

He explains: Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.

The effect is that the client code can use 'WidgetManager' in a more elegant way:

typedef WidgetManager<MyCreationPolicy> MyWidgetMgr;

Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:

typedef WidgetManager< MyCreationPolicy<Widget> > MyWidgetMgr;

RandomForestClassfier.fit(): ValueError: could not convert string to float

Well, there are important differences between how OneHot Encoding and Label Encoding work :

  • Label Encoding will basically switch your String variables to int. In this case, the 1st class found will be coded as 1, the 2nd as 2, ... But this encoding creates an issue.

Let's take the example of a variable Animal = ["Dog", "Cat", "Turtle"].

If you use Label Encoder on it, Animal will be [1, 2, 3]. If you parse it to your machine learning model, it will interpret Dog is closer than Cat, and farther than Turtle (because distance between 1 and 2 is lower than distance between 1 and 3).

Label encoding is actually excellent when you have ordinal variable.

For example, if you have a value Age = ["Child", "Teenager", "Young Adult", "Adult", "Old"],

then using Label Encoding is perfect. Child is closer than Teenager than it is from Young Adult. You have a natural order on your variables

  • OneHot Encoding (also done by pd.get_dummies) is the best solution when you have no natural order between your variables.

Let's take back the previous example of Animal = ["Dog", "Cat", "Turtle"].

It will create as much variable as classes you encounter. In my example, it will create 3 binary variables : Dog, Cat and Turtle. Then if you have Animal = "Dog", encoding will make it Dog = 1, Cat = 0, Turtle = 0.

Then you can give this to your model, and he will never interpret that Dog is closer from Cat than from Turtle.

But there are also cons to OneHotEncoding. If you have a categorical variable encountering 50 kind of classes

eg : Dog, Cat, Turtle, Fish, Monkey, ...

then it will create 50 binary variables, which can cause complexity issues. In this case, you can create your own classes and manually change variable

eg : regroup Turtle, Fish, Dolphin, Shark in a same class called Sea Animals and then appy a OneHotEncoding.

Convert java.util.Date to String

public static String formateDate(String dateString) {
    Date date;
    String formattedDate = "";
    try {
        date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
        formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return formattedDate;
}

How to check the gradle version in Android Studio?

I'm not sure if this is what you ask, but you can check gradle version of your project here in android studio:

(left pane must be in project view, not android for this path) app->gradle->wrapper->gradle-wrapper.properties

it has a line like this, indicating the gradle version:

distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-all.zip

There is also a table at the end of this page that shows gradle and gradle plug-in versions supported by each android studio version. (you can check your android studio by checking help->about as you may already know)

Calculate average in java

Instead of:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
System.out.println(count);

 }

you can just

int count = args.length;

The average is the sum of your args divided by the number of your args.

int res = 0;
int count = args.lenght;

for (int a : args)
{
res += a;
}
res /= count;

you can make this code shorter too, i'll let you try and ask if you need help!

This is my first answerso tell me if something wrong!

Add IIS 7 AppPool Identities as SQL Server Logons

This may be what you are looking for...

http://technet.microsoft.com/en-us/library/cc730708%28WS.10%29.aspx

I would also advise longer term to consider a limited rights domain user, what you are trying works fine in a silo machine scenario but you are going to have to make changes if you move to another machine for the DB server.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I know this is old but this answer still applies to newer Core releases.

If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

Both -s and -p are optionals that default to the current folder.

Display Python datetime without time

To convert a string into a date, the easiest way AFAIK is the dateutil module:

import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")

It can also handle time zones:

print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())

If you have a datetime object, say:

import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)

and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:

date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)

It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).

Hidden Features of Xcode

Being able to quickly see all the methods that can be overriden from a super class. For example when extending UITableViewController I just type in my implementation:

- ta

and then I hit ESC to see all the methods from my superclass that begin with "ta" such as

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

This also works when adopting protocols.

How to change Status Bar text color in iOS

I'm using Xcode 6 beta 5 on a Swift project, for an iOS 7 app.

Here is what I did, and it works:

info.plist:

Enter image description here

How to use ng-if to test if a variable is defined

Try this:

item.shipping!==undefined

How to Logout of an Application Where I Used OAuth2 To Login With Google?

I hope we can achieve this by storing the token in session while logging in and access the token when he clicked on logout.

    String _accessToken=(String)session.getAttribute("ACCESS_TOKEN");
    if(_accessToken!=null)
    {
        StringBuffer path=httpRequest.getRequestURL();
        reDirectPage="https://www.google.com/accounts/Logout?
        continue=https://appengine.google.com/_ah/logout?
        continue="+path;
    }
    response.sendRedirect(reDirectPage);

How to print a string in C++

If you'd like to use printf(), you might want to also:

#include <stdio.h>

Jquery button click() function is not working

The click event is not bound to your new element, use a jQuery.on to handle the click.

Using 'make' on OS X

@Daniel's suggestion worked perfectly for me. To install

make
, open Xcode, go to Preferences -> Downloads -> Components -> Command Line Tools.You can then test with
gcc -v

Check if url contains string with JQuery

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf("?added-to-cart=555") > -1) {
    alert("found it");
}

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

Bruno's answer was the correct one in the end. This is most easily controlled by the https.protocols system property. This is how you are able to control what the factory method returns. Set to "TLSv1" for example.

How can I exclude directories from grep -R?

Very useful, especially for those dealing with Node.js where we want to avoid searching inside "node_modules":

find ./ -not -path "*/node_modules/*" -name "*.js" | xargs grep keyword

Deleting a local branch with Git

If you have created multiple worktrees with git worktree, you'll need to run git prune before you can delete the branch

Spring Boot Configure and Use Two DataSources

# Here '1stDB' is the database name
spring.datasource.url=jdbc:mysql://localhost/A
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


# Here '2ndDB' is the database name
spring.second-datasourcee.url=jdbc:mysql://localhost/B
spring.second-datasource.username=root
spring.second-datasource.password=root
spring.second-datasource.driver-class-name=com.mysql.jdbc.Driver


    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.second-datasource")
    public DataSource secondDataSource() {
       return DataSourceBuilder.create().build();
    }

Calling JavaScript Function From CodeBehind

ScriptManager.RegisterStartupScript(Page, GetType(), "JavaFunction", "AlertError();", true);

using your function is enough

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

Check if an apt-get package is installed and then install it if it's not on Linux

inspired by Chris above

#! /bin/bash

installed() {
    return $(dpkg-query -W -f '${Status}\n' "${1}" 2>&1|awk '/ok installed/{print 0;exit}{print 1}')
}

pkgs=(libgl1-mesa-dev xorg-dev vulkan-tools libvulkan-dev vulkan-validationlayers-dev spirv-tools)
missing_pkgs=""

for pkg in ${pkgs[@]}; do
    if ! $(installed $pkg) ; then
        missing_pkgs+=" $pkg"
    fi
done

if [ ! -z "$missing_pkgs" ]; then
    cmd="sudo apt install -y $missing_pkgs"
    echo $cmd
fi

Android: combining text & image on a Button or ImageButton

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/temp"
        />

Check play state of AVPlayer

rate is NOT the way to check whether a video is playing (it could stalled). From documentation of rate:

Indicates the desired rate of playback; 0.0 means "paused", 1.0 indicates a desire to play at the natural rate of the current item.

Key words "desire to play" - a rate of 1.0 does not mean the video is playing.

The solution since iOS 10.0 is to use AVPlayerTimeControlStatus which can be observed on AVPlayer timeControlStatus property.

The solution prior to iOS 10.0 (9.0, 8.0 etc.) is to roll your own solution. A rate of 0.0 means that the video is paused. When rate != 0.0 it means that the video is either playing or is stalled.

You can find out the difference by observing player time via: func addPeriodicTimeObserver(forInterval interval: CMTime, queue: DispatchQueue?, using block: @escaping (CMTime) -> Void) -> Any

The block returns the current player time in CMTime, so a comparison of lastTime (the time that was last received from the block) and currentTime (the time that the block just reported) will tell whether the player is playing or is stalled. For example, if lastTime == currentTime and rate != 0.0, then the player has stalled.

As noted by others, figuring out whether playback has finished is indicated by AVPlayerItemDidPlayToEndTimeNotification.

How to create folder with PHP code?

You can create a directory with PHP using the mkdir() function.

mkdir("/path/to/my/dir", 0700);

You can use fopen() to create a file inside that directory with the use of the mode w.

fopen('myfile.txt', 'w');

w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Equivalent of Oracle's RowID in SQL Server

I took this example from MS SQL example and you can see the @ID can be interchanged with integer or varchar or whatever. This was the same solution I was looking for, so I am sharing it. Enjoy!!

-- UPDATE statement with CTE references that are correctly matched.
DECLARE @x TABLE (ID int, Stad int, Value int, ison bit);
INSERT @x VALUES (1, 0, 10, 0), (2, 1, 20, 0), (6, 0, 40, 0), (4, 1, 50, 0), (5, 3, 60, 0), (9, 6, 20, 0), (7, 5, 10, 0), (8, 8, 220, 0);
DECLARE @Error int;
DECLARE @id int;

WITH cte AS (SELECT top 1 * FROM @x WHERE Stad=6)
UPDATE x -- cte is referenced by the alias.
SET ison=1, @id=x.ID
FROM cte AS x

SELECT *, @id as 'random' from @x
GO

Change navbar text color Bootstrap

For changing the text color in navbar you can use inline css as;

<a style="color: #3c6afc" href="#">

Div Scrollbar - Any way to style it?

Looking at the web I find some simple way to style scrollbars.

This is THE guy! http://almaer.com/blog/creating-custom-scrollbars-with-css-how-css-isnt-great-for-every-task

And here my implementation! https://dl.dropbox.com/u/1471066/cloudBI/cssScrollbars.png

/* Turn on a 13x13 scrollbar */
::-webkit-scrollbar {
    width: 10px;
    height: 13px;
}

::-webkit-scrollbar-button:vertical {
    background-color: silver;
    border: 1px solid gray;
}

/* Turn on single button up on top, and down on bottom */
::-webkit-scrollbar-button:start:decrement,
::-webkit-scrollbar-button:end:increment {
    display: block;
}

/* Turn off the down area up on top, and up area on bottom */
::-webkit-scrollbar-button:vertical:start:increment,
::-webkit-scrollbar-button:vertical:end:decrement {
    display: none;
}

/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:vertical:increment {
    display: none;
}

/* Place The scroll up button at the up */
::-webkit-scrollbar-button:vertical:decrement {
    display: none;
}

/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:horizontal:increment {
    display: none;
}

/* Place The scroll up button at the up */
::-webkit-scrollbar-button:horizontal:decrement {
    display: none;
}

::-webkit-scrollbar-track:vertical {
    background-color: blue;
    border: 1px dashed pink;
}

/* Top area above thumb and below up button */
::-webkit-scrollbar-track-piece:vertical:start {
    border: 0px;
}

/* Bottom area below thumb and down button */
::-webkit-scrollbar-track-piece:vertical:end {
    border: 0px;
}

/* Track below and above */
::-webkit-scrollbar-track-piece {
    background-color: silver;
}

/* The thumb itself */
::-webkit-scrollbar-thumb:vertical {
    height: 50px;
    background-color: gray;
}

/* The thumb itself */
::-webkit-scrollbar-thumb:horizontal {
    height: 50px;
    background-color: gray;
}

/* Corner */
::-webkit-scrollbar-corner:vertical {
    background-color: black;
}

/* Resizer */
::-webkit-scrollbar-resizer:vertical {
    background-color: gray;
}

How to make div follow scrolling smoothly with jQuery?

This one is same on facebook:

_x000D_
_x000D_
<script>_x000D_
var valX = $(window).scrollTop();_x000D_
function syncScroll(target){_x000D_
 var valY = $(window).scrollTop();_x000D_
 var difYX = valY - valX;_x000D_
 var targetX = $(target).scrollTop();_x000D_
 if(valY > valX){_x000D_
  $(target).scrollTop(difYX);_x000D_
 }_x000D_
 if(difYX <= 0){_x000D_
  $(target).scrollTop(-20);_x000D_
 }_x000D_
}_x000D_
_x000D_
$(window).scroll(function(){_x000D_
 syncScroll('#demo');_x000D_
})_x000D_
</script>
_x000D_
body{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
}_x000D_
#demo{_x000D_
  position:fixed;_x000D_
  height:100vh;_x000D_
  overflow:hidden;_x000D_
  width:40%;_x000D_
}_x000D_
#content{_x000D_
  position:relative;_x000D_
  float:right;_x000D_
  width:60%;_x000D_
  color:red; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <div id="demo">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
  </div>_x000D_
  <div id="content">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
   </div>   _x000D_
</body
_x000D_
_x000D_
_x000D_

How to select an element by classname using jqLite?

Essentially, and as-noted by @kevin-b:

// find('#id')
angular.element(document.querySelector('#id'))

//find('.classname'), assumes you already have the starting elem to search from
angular.element(elem.querySelector('.classname'))

Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the developers guide and refactor your presentation logic into appropriate directives (such as <a2b ...>).

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

What encoding/code page is cmd.exe using?

Command CHCP shows the current codepage. It has three digits: 8xx and is different from Windows 12xx. So typing a English-only text you wouldn't see any difference, but an extended codepage (like Cyrillic) will be printed wrongly.

Default value of 'boolean' and 'Boolean' in Java

boolean
Can be true or false.
Default value is false.

(Source: Java Primitive Variables)

Boolean
Can be a Boolean object representing true or false, or can be null.
Default value is null.

How to make this Header/Content/Footer layout using CSS?

After fiddling around a while I found a solution that works in >IE7, Chrome, Firefox:

http://jsfiddle.net/xfXaw/

* {
    margin:0;
    padding:0;
}

html, body {
    height:100%;
}

#wrap {
    min-height:100%;

}

#header {
    background: red;
}

#content {
    padding-bottom: 50px;
}

#footer {
    height:50px;
    margin-top:-50px;
    background: green;
}

HTML:

<div id="wrap">
    <div id="header">header</div>
    <div id="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. </div>
</div>
<div id="footer">footer</div>

Resource interpreted as Document but transferred with MIME type application/zip

I encountered this when I assigned src="image_url" in an iframe. It seems that iframe interprets it as a document but it is not. That's why it displays a warning.

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

Check your js files actually exist on the server. I had this problem and discovered the js files hadn't been uploaded to the server and the server was actually returning the html page instead - which was the default document configured on the server (eg default.html)

Create a Bitmap/Drawable from file path

you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.

declare a HashMap somewhere in your class:

private static HashMap<String, Integer> images = null;

//Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once
  }
}

Now for access -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

import React, { useRef, useState } from 'react'
...
const inputRef = useRef()
....
function chooseFile() {
  const { current } = inputRef
  (current || { click: () => {}}).click()
}
...
<input
   onChange={e => {
     setFile(e.target.files)
    }}
   id="select-file"
   type="file"
   ref={inputRef}
/>
<Button onClick={chooseFile} shadow icon="/upload.svg">
   Choose file
</Button>

the unique code that works to me using next.js enter image description here

SQL select statements with multiple tables

Select * from people p, address a where  p.id = a.person_id and a.zip='97229';

Or you must TRY using JOIN which is a more efficient and better way to do this as Gordon Linoff in the comments below also says that you need to learn this.

SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299';

Here p.* means it will show all the columns of PERSONS table.

MySQL SELECT DISTINCT multiple columns

This will give DISTINCT values across all the columns:

SELECT DISTINCT value
FROM (
    SELECT DISTINCT a AS value FROM my_table
    UNION SELECT DISTINCT b AS value FROM my_table
    UNION SELECT DISTINCT c AS value FROM my_table
) AS derived

How to auto adjust the div size for all mobile / tablet display formats?

I don't have much time and your jsfidle did not work right now.
But maybe this will help you getting started.

First of all you should avoid to put css in your html tags. Like align="center".
Put stuff like that in your css since it is much clearer and won't deprecate that fast.

If you want to design responsive layouts you should use media queries wich were introduced in css3 and are supported very well by now.

Example css:

@media screen and (min-width: 100px) and (max-width: 199px)
{
    .button
    {
        width: 25px;
    }
}

@media screen and (min-width: 200px) and (max-width: 299px)
{
    .button
    {
        width: 50px;
    }
}

You can use any css you want inside a media query.
http://www.w3.org/TR/css3-mediaqueries/

c#: getter/setter

In C# 6:

It is now possible to declare the auto-properties just as a field:

public string FirstName { get; set; } = "Ropert";

Read-Only Auto-Properties

public string FirstName { get;} = "Ropert";

When to throw an exception?

I'd say that generally every fundamentalism leads to hell.

You certainly wouldn't want to end up with exception driven flow, but avoiding exceptions altogether is also a bad idea. You have to find a balance between both approaches. What I would not do is to create an exception type for every exceptional situation. That is not productive.

What I generally prefer is to create two basic types of exceptions which are used throughout the system: LogicalException and TechnicalException. These can be further distinguished by subtypes if needed, but it is not generally not necessary.

The technical exception denotes the really unexpected exception like database server being down, the connection to the web service threw the IOException and so on.

On the other hand the logical exceptions are used to propagate the less severe erroneous situation to the upper layers (generally some validation result).

Please note that even the logical exception is not intended to be used on regular basis to control the program flow, but rather to highlight the situation when the flow should really end. When used in Java, both exception types are RuntimeException subclasses and error handling is highly aspect oriented.

So in the login example it might be wise to create something like AuthenticationException and distinguish the concrete situations by enum values like UsernameNotExisting, PasswordMismatch etc. Then you won't end up in having a huge exception hierarchy and can keep the catch blocks on maintainable level. You can also easily employ some generic exception handling mechanism since you have the exceptions categorized and know pretty well what to propagate up to the user and how.

Our typical usage is to throw the LogicalException during the Web Service call when the user's input was invalid. The Exception gets marshalled to the SOAPFault detail and then gets unmarshalled to the exception again on the client which is resulting in showing the validation error on one certain web page input field since the exception has proper mapping to that field.

This is certainly not the only situation: you don't need to hit web service to throw up the exception. You are free to do so in any exceptional situation (like in the case you need to fail-fast) - it is all at your discretion.

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

AngularJS - add HTML element to dom in directive without jQuery

You could use something like this

var el = document.createElement("svg");
el.style.width="600px";
el.style.height="100px";
....
iElement[0].appendChild(el)

What is the main difference between PATCH and PUT request?

PUT and PATCH methods are similar in nature, but there is a key difference.

PUT - in PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.

PATCH - in PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.

how to create virtual host on XAMPP

Apache Virtual Host documentation Setting up a virtual host (vhost) provides several benefits:

  • Virtual Hosts make URLs cleaner – localhost/mysite vs mysite.local.
  • Virtual Hosts make permissions easier – restrict access for a single vhost on a local network vs permitting access to all sites on your local network.
  • Some applications require a “.” in the URL (ahem Magento). While you can setup localhost.com/mysite by editing the Windows hosts file, creating a vhost is a better solution.

VirtualHost Directive Contains directives that apply only to a specific hostname or IP address

Location Directive Applies the enclosed directives only to matching URLs

Example changes over configuration file - D:\xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin localhost
    DocumentRoot "D:/xampp/htdocs"
    ServerName localhost
</VirtualHost>

<VirtualHost localhost:80>
  ServerAdmin [email protected]
  DocumentRoot "/www/docs/host.example.com"
  #DocumentRoot "D:\xampp\htdocs\phpPages"
  ServerName host.example.com
  ErrorLog "logs/host.example.com-error_log"
  TransferLog "logs/host.example.com-access_log"
</VirtualHost>

# To get view of PHP application in the Browser.
<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "D:\xampp\htdocs\app1"
    ServerName app1.yash.com
    ServerAlias app1.yash.com
    ErrorLog "logs/app1.yash.com-error.log"
    CustomLog "logs/app1.yash.com-access.log" combined
    
    # App1 communication proxy call to Java War applications from XAMP
    <Location /ServletApp1>
            ProxyPass  http://app1.yashJava.com:8080/ServletApp1
            ProxyPassReverse  http://app1.yashJava.com:8080/ServletApp1
            Order Allow,Deny
            Allow from all
    </Location>
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "D:\xampp\htdocs\app2"
    ServerName app2.yash.com
    ErrorLog "logs/app2.yash.com-error.log"
    CustomLog "logs/app2.yash.com-access.log" combined
    
    # App1 communication proxy call to Java War applications from XAMP
    <Location /ServletApp2>
            ProxyPass  http://app1.yashJava.com:8080/ServletApp2
            ProxyPassReverse  http://app1.yashJava.com:8080/ServletApp2
            Order Allow,Deny
            Allow from all
    </Location>
</VirtualHost>

Update Your Windows Hosts File « Open your Windows hosts file located in C:\Windows\System32\drivers\etc\hosts.

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

127.0.0.1       test.com
127.0.0.1       example.com
127.0.0.1       myssl.yash.com

D:\xampp\apache\conf\httpd.conf, [httpd-ssl.conf](http://httpd.apache.org/docs/2.2/mod/mod_ssl.html)

# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost> directive.
# Listen 0.0.0.0:80 | [::]:80
Listen 80

LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule speling_module modules/mod_speling.so

# ServerAdmin: Your address, where problems with the server should be e-mailed.
# This address appears on some server-generated pages, such as error documents.
#  e.g. [email protected]
ServerAdmin postmaster@localhost
ServerName localhost:80
DocumentRoot "D:/xampp/htdocs"

<Directory "D:/xampp/htdocs">
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Require all granted
</Directory>

# Virtual hosts
Include "conf/extra/httpd-vhosts.conf"

# ===== httpd-ssl.conf - SSL Virtual Host Context =====
# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
#       Listen directives: "Listen [::]:443" and "Listen 0.0.0.0:443"
Listen 443
## SSL Virtual Host Context
<VirtualHost _default_:443>
    DocumentRoot "D:\xampp\htdocs\projectFolderSSL"
    ServerName myssl.yash.com:443
    ServerAlias myssl.yash.com:443
        
    ServerAdmin webmaster@localhost
    ErrorLog "logs/error.log"
    <IfModule log_config_module>
        CustomLog "logs/access.log" combined
    </IfModule>
    
    ## Redirecting URL from Web server to Application server over different machine.
    # myssl.yash.com:443/ServletWebApp
    <Location /path>
        ProxyPass  http://java.yash2.com:8444/ServletWebApp
        ProxyPassReverse  http://java.yash2.com:8444/ServletWebApp
        Order Allow,Deny
        Allow from all
    </Location>
    
    #SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateFile "D:\SSL_Vendor\yash.crt"
    
    #SSLCertificateKeyFile "conf/ssl.key/server.key"
    SSLCertificateKeyFile "D:\SSL_Vendor\private-key.key"
    
    #SSLCertificateChainFile "conf/ssl.crt/server-ca.crt"
    SSLCertificateChainFile "D:\SSL_Vendor\intermediate.crt"
</VirtualHost>
# ===== httpd-ssl.conf - SSL Virtual Host Context =====

@see

CSS3 Box Shadow on Top, Left, and Right Only

It's better if you just cover the bottom part with another div and you will get consistent drop shadow across the board.

#servicesContainer {
  /*your css*/
  position: relative;
}

and it's fixed! like magic!

Passing arrays as url parameter

There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:

$data = array(
    1,
    4,
    'a' => 'b',
    'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));

will return

string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"

http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.

Best way to convert an ArrayList to a string

The below code may help you,

List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = list.toString();
System.out.println("Step-1 : " + str);
str = str.replaceAll("[\\[\\]]", "");
System.out.println("Step-2 : " + str);

Output:

Step-1 : [1, 2, 3]
Step-2 : 1, 2, 3

Customize the Authorization HTTP header

In the case of CROSS ORIGIN request read this:

I faced this situation and at first I chose to use the Authorization Header and later removed it after facing the following issue.

Authorization Header is considered a custom header. So if a cross-domain request is made with the Autorization Header set, the browser first sends a preflight request. A preflight request is an HTTP request by the OPTIONS method, this request strips all the parameters from the request. Your server needs to respond with Access-Control-Allow-Headers Header having the value of your custom header (Authorization header).

So for each request the client (browser) sends, an additional HTTP request(OPTIONS) was being sent by the browser. This deteriorated the performance of my API. You should check if adding this degrades your performance. As a workaround I am sending tokens in http parameters, which I know is not the best way of doing it but I couldn't compromise with the performance.

When to use async false and async true in ajax function in jquery

ShowPopUpForToDoList: function (id, apprId, tab) {
    var snapShot = "isFromAlert";
    if (tab != "Request")
        snapShot = "isFromTodoList";
    $.ajax({
        type: "GET",
        url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
        data: { id: id, tab: tab },
        async:false,
        success: function (data) {
            ActionForm.EditActionFormPopup(id, snapShot);
        }
    });
},

Here SetParamForToDoList will be excecuted first after the function ActionForm.EditActionFormPopup will fire.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

After changing permissions of folder in which I was cloning, it worked:

sudo chown -R ubuntu:ubuntu /var/projects

Groovy executing shell commands

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).

Removing duplicate values from a PowerShell array

If the list is sorted, you can use the Get-Unique cmdlet:

 $a | Get-Unique

MySQL - How to select rows where value is in array?

If you use the FIND_IN_SET function:

FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others

AND

FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others

So if record1 is (a,b,c) and record2 is (a)

FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

How to rename a directory/folder on GitHub website?

If you have GitHub Desktop, change the names of the directories on your computer and then push the update from your desktop to your github account and it changes them there. :)

Hope it helps!

How to display (print) vector in Matlab?

Here's another approach that takes advantage of Matlab's strjoin function. With strjoin it's easy to customize the delimiter between values.

x = [1, 2, 3];
fprintf('Answer: (%s)\n', strjoin(cellstr(num2str(x(:))),', '));

This results in: Answer: (1, 2, 3)

Quick easy way to migrate SQLite3 to MySQL?

I wrote this simple script in Python3. It can be used as an included class or standalone script invoked via a terminal shell. By default it imports all integers as int(11)and strings as varchar(300), but all that can be adjusted in the constructor or script arguments respectively.

NOTE: It requires MySQL Connector/Python 2.0.4 or higher

Here's a link to the source on GitHub if you find the code below hard to read: https://github.com/techouse/sqlite3-to-mysql

#!/usr/bin/env python3

__author__ = "Klemen Tušar"
__email__ = "[email protected]"
__copyright__ = "GPL"
__version__ = "1.0.1"
__date__ = "2015-09-12"
__status__ = "Production"

import os.path, sqlite3, mysql.connector
from mysql.connector import errorcode


class SQLite3toMySQL:
    """
    Use this class to transfer an SQLite 3 database to MySQL.

    NOTE: Requires MySQL Connector/Python 2.0.4 or higher (https://dev.mysql.com/downloads/connector/python/)
    """
    def __init__(self, **kwargs):
        self._properties = kwargs
        self._sqlite_file = self._properties.get('sqlite_file', None)
        if not os.path.isfile(self._sqlite_file):
            print('SQLite file does not exist!')
            exit(1)
        self._mysql_user = self._properties.get('mysql_user', None)
        if self._mysql_user is None:
            print('Please provide a MySQL user!')
            exit(1)
        self._mysql_password = self._properties.get('mysql_password', None)
        if self._mysql_password is None:
            print('Please provide a MySQL password')
            exit(1)
        self._mysql_database = self._properties.get('mysql_database', 'transfer')
        self._mysql_host = self._properties.get('mysql_host', 'localhost')

        self._mysql_integer_type = self._properties.get('mysql_integer_type', 'int(11)')
        self._mysql_string_type = self._properties.get('mysql_string_type', 'varchar(300)')

        self._sqlite = sqlite3.connect(self._sqlite_file)
        self._sqlite.row_factory = sqlite3.Row
        self._sqlite_cur = self._sqlite.cursor()

        self._mysql = mysql.connector.connect(
            user=self._mysql_user,
            password=self._mysql_password,
            host=self._mysql_host
        )
        self._mysql_cur = self._mysql.cursor(prepared=True)
        try:
            self._mysql.database = self._mysql_database
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_BAD_DB_ERROR:
                self._create_database()
            else:
                print(err)
                exit(1)

    def _create_database(self):
        try:
            self._mysql_cur.execute("CREATE DATABASE IF NOT EXISTS `{}` DEFAULT CHARACTER SET 'utf8'".format(self._mysql_database))
            self._mysql_cur.close()
            self._mysql.commit()
            self._mysql.database = self._mysql_database
            self._mysql_cur = self._mysql.cursor(prepared=True)
        except mysql.connector.Error as err:
            print('_create_database failed creating databse {}: {}'.format(self._mysql_database, err))
            exit(1)

    def _create_table(self, table_name):
        primary_key = ''
        sql = 'CREATE TABLE IF NOT EXISTS `{}` ( '.format(table_name)
        self._sqlite_cur.execute('PRAGMA table_info("{}")'.format(table_name))
        for row in self._sqlite_cur.fetchall():
            column = dict(row)
            sql += ' `{name}` {type} {notnull} {auto_increment}, '.format(
                name=column['name'],
                type=self._mysql_string_type if column['type'].upper() == 'TEXT' else self._mysql_integer_type,
                notnull='NOT NULL' if column['notnull'] else 'NULL',
                auto_increment='AUTO_INCREMENT' if column['pk'] else ''
            )
            if column['pk']:
                primary_key = column['name']
        sql += ' PRIMARY KEY (`{}`) ) ENGINE = InnoDB CHARACTER SET utf8'.format(primary_key)
        try:
            self._mysql_cur.execute(sql)
            self._mysql.commit()
        except mysql.connector.Error as err:
            print('_create_table failed creating table {}: {}'.format(table_name, err))
            exit(1)

    def transfer(self):
        self._sqlite_cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
        for row in self._sqlite_cur.fetchall():
            table = dict(row)
            # create the table
            self._create_table(table['name'])
            # populate it
            print('Transferring table {}'.format(table['name']))
            self._sqlite_cur.execute('SELECT * FROM "{}"'.format(table['name']))
            columns = [column[0] for column in self._sqlite_cur.description]
            try:
                self._mysql_cur.executemany("INSERT IGNORE INTO `{table}` ({fields}) VALUES ({placeholders})".format(
                    table=table['name'],
                    fields=('`{}`, ' * len(columns)).rstrip(' ,').format(*columns),
                    placeholders=('%s, ' * len(columns)).rstrip(' ,')
                ), (tuple(data) for data in self._sqlite_cur.fetchall()))
                self._mysql.commit()
            except mysql.connector.Error as err:
                print('_insert_table_data failed inserting data into table {}: {}'.format(table['name'], err))
                exit(1)
        print('Done!')


def main():
    """ For use in standalone terminal form """
    import sys, argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--sqlite-file', dest='sqlite_file', default=None, help='SQLite3 db file')
    parser.add_argument('--mysql-user', dest='mysql_user', default=None, help='MySQL user')
    parser.add_argument('--mysql-password', dest='mysql_password', default=None, help='MySQL password')
    parser.add_argument('--mysql-database', dest='mysql_database', default=None, help='MySQL host')
    parser.add_argument('--mysql-host', dest='mysql_host', default='localhost', help='MySQL host')
    parser.add_argument('--mysql-integer-type', dest='mysql_integer_type', default='int(11)', help='MySQL default integer field type')
    parser.add_argument('--mysql-string-type', dest='mysql_string_type', default='varchar(300)', help='MySQL default string field type')
    args = parser.parse_args()

    if len(sys.argv) == 1:
        parser.print_help()
        exit(1)

    converter = SQLite3toMySQL(
        sqlite_file=args.sqlite_file,
        mysql_user=args.mysql_user,
        mysql_password=args.mysql_password,
        mysql_database=args.mysql_database,
        mysql_host=args.mysql_host,
        mysql_integer_type=args.mysql_integer_type,
        mysql_string_type=args.mysql_string_type
    )
    converter.transfer()

if __name__ == '__main__':
    main()

No value accessor for form control

enter image description here

enter image description here

You can see formControlName in label , removing this solved my problem

how to remove key+value from hash in javascript

You're looking for delete:

delete myhash['key2']

See the Core Javascript Guide

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

Mockito - NullpointerException when stubbing Method

The default return value of methods you haven't stubbed yet is false for boolean methods, an empty collection or map for methods returning collections or maps and null otherwise.

This also applies to method calls within when(...). In you're example when(myService.getListWithData(inputData).get()) will cause a NullPointerException because myService.getListWithData(inputData) is null - it has not been stubbed before.

One option is create mocks for all intermediate return values and stub them before use. For example:

ListWithData listWithData = mock(ListWithData.class);
when(listWithData.get()).thenReturn(item1);
when(myService.getListWithData()).thenReturn(listWithData);

Or alternatively, you can specify a different default answer when creating a mock, to make methods return a new mock instead of null: RETURNS_DEEP_STUBS

SomeService myService = mock(SomeService.class, Mockito.RETURNS_DEEP_STUBS);
when(myService.getListWithData().get()).thenReturn(item1);

You should read the Javadoc of Mockito.RETURNS_DEEP_STUBS which explains this in more detail and also has some warnings about its usage.

I hope this helps. Just note that your example code seems to have more issues, such as missing assert or verify statements and calling setters on mocks (which does not have any effect).

MySQL root access from all hosts

Run the following query:

use mysql;
update user set host='%' where host='localhost'

NOTE: Not recommended for production use.

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Where is this year() function from?

You could also use the reshape2 package for this task:

require(reshape2)
df_melt <- melt(df1, id = c("date", "year", "month"))
dcast(df_melt, year + month ~ variable, sum)
#  year month         x1           x2
1  2000     1  -80.83405 -224.9540159
2  2000     2 -223.76331 -288.2418017
3  2000     3 -188.83930 -481.5601913
4  2000     4 -197.47797 -473.7137420
5  2000     5 -259.07928 -372.4563522

Escape sequence \f - form feed - what exactly is it?

If you were programming for a 1980s-style printer, it would eject the paper and start a new page. You are virtually certain to never need it.

http://en.wikipedia.org/wiki/Form_feed

Pandas DataFrame column to list

I'd like to clarify a few things:

  1. As other answers have pointed out, the simplest thing to do is use pandas.Series.tolist(). I'm not sure why the top voted answer leads off with using pandas.Series.values.tolist() since as far as I can tell, it adds syntax/confusion with no added benefit.
  2. tst[lookupValue][['SomeCol']] is a dataframe (as stated in the question), not a series (as stated in a comment to the question). This is because tst[lookupValue] is a dataframe, and slicing it with [['SomeCol']] asks for a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you remove the extra set of brackets, as in tst[lookupValue]['SomeCol'], then you are asking for just that one column rather than a list of columns, and thus you get a series back.
  3. You need a series to use pandas.Series.tolist(), so you should definitely skip the second set of brackets in this case. FYI, if you ever end up with a one-column dataframe that isn't easily avoidable like this, you can use pandas.DataFrame.squeeze() to convert it to a series.
  4. tst[lookupValue]['SomeCol'] is getting a subset of a particular column via chained slicing. It slices once to get a dataframe with only certain rows left, and then it slices again to get a certain column. You can get away with it here since you are just reading, not writing, but the proper way to do it is tst.loc[lookupValue, 'SomeCol'] (which returns a series).
  5. Using the syntax from #4, you could reasonably do everything in one line: ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()

Demo Code:

import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
                   'colB':[4,5,6]})
filter_value = 1

print "df"
print df
print type(df)

rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)

result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)

result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)

result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)

result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)

result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)

ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)

ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)

Result:

df
   colA  colB
0     1     4
1     2     5
2     1     6
<class 'pandas.core.frame.DataFrame'>

df['colA'] == filter_value
0     True
1    False
2     True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>

df[rows_to_keep]['colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df[rows_to_keep][['colB']]
   colB
0     4
2     6
<class 'pandas.core.frame.DataFrame'>

df[rows_to_keep][['colB']].squeeze()
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[df['colA'] == filter_value, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>

df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>

HTML/Javascript Button Click Counter

Use var instead of int for your clicks variable generation and onClick instead of click as your function name:

_x000D_
_x000D_
var clicks = 0;

function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
_x000D_
_x000D_

In JavaScript variables are declared with the var keyword. There are no tags like int, bool, string... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.

And the name 'click' is reserved by JavaScript for function names so you have to use something else.

Big O, how do you calculate/approximate it?

Less useful generally, I think, but for the sake of completeness there is also a Big Omega O, which defines a lower-bound on an algorithm's complexity, and a Big Theta T, which defines both an upper and lower bound.

How to find my realm file?

I found my realm file by issuing this command in Terminal: sudo find / -name "*.realm".

Hope this helps!

Understanding __getitem__ method

Cong Ma does a good job of explaining what __getitem__ is used for - but I want to give you an example which might be useful. Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :

Without using __getitem__ we would have a class like this :

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def occupy(self, floor_number, data):
          self._floors[floor_number] = data
     def get_floor_data(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )

We could however use __getitem__ (and its counterpart __setitem__) to make the usage of the Building class 'nicer'.

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def __setitem__(self, floor_number, data):
          self._floors[floor_number] = data
     def __getitem__(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )

Whether you use __setitem__ like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.

Is this how you define a function in jQuery?

No.

You define the functions exactly the same way you would in regular javascript.

//document ready
$(function(){
    myBlah();
})

var myBlah = function(blah){
    alert(blah);
}

Also: There is no need for the $

How to overwrite the previous print to stdout in python?

I had the same question before visiting this thread. For me the sys.stdout.write worked only if I properly flush the buffer i.e.

for x in range(10):
    sys.stdout.write('\r'+str(x))
    sys.stdout.flush()

Without flushing, the result is printed only at the end out the script

Have a fixed position div that needs to scroll if content overflows

The problem with using height:100% is that it will be 100% of the page instead of 100% of the window (as you would probably expect it to be). This will cause the problem that you're seeing, because the non-fixed content is long enough to include the fixed content with 100% height without requiring a scroll bar. The browser doesn't know/care that you can't actually scroll that bar down to see it

You can use fixed to accomplish what you're trying to do.

.fixed-content {
    top: 0;
    bottom:0;
    position:fixed;
    overflow-y:scroll;
    overflow-x:hidden;
}

This fork of your fiddle shows my fix: http://jsfiddle.net/strider820/84AsW/1/

How to add minutes to current time in swift

Save this little extension:

extension Int {

 var seconds: Int {
    return self
 }

 var minutes: Int {
    return self.seconds * 60
 }

 var hours: Int {
    return self.minutes * 60
 }

 var days: Int {
    return self.hours * 24
 }

 var weeks: Int {
    return self.days * 7
 }

 var months: Int {
    return self.weeks * 4
 }

 var years: Int {
    return self.months * 12
 }
}

Then use it intuitively like:

let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)

how to use a like with a join in sql?

Using conditional criteria in a join is definitely different than the Where clause. The cardinality between the tables can create differences between Joins and Where clauses.

For example, using a Like condition in an Outer Join will keep all records in the first table listed in the join. Using the same condition in the Where clause will implicitly change the join to an Inner join. The record has to generally be present in both tables to accomplish the conditional comparison in the Where clause.

I generally use the style given in one of the prior answers.

tbl_A as ta
    LEFT OUTER JOIN tbl_B AS tb
            ON ta.[Desc] LIKE '%' + tb.[Desc] + '%'

This way I can control the join type.

When can I use a forward declaration?

As, Luc Touraille has already explained it very well where to use and not use forward declaration of the class.

I will just add to that why we need to use it.

We should be using Forward declaration wherever possible to avoid the unwanted dependency injection.

As #include header files are added on multiple files therefore, if we add a header into another header file it will add unwanted dependency injection in various parts of source code which can be avoided by adding #include header into .cpp files wherever possible rather than adding to another header file and use class forward declaration wherever possible in header .h files.

HQL "is null" And "!= null" on an Oracle column

No. You have to use is null and is not null in HQL.

Resize svg when window is resized in d3.js

For those using force directed graphs in D3 v4/v5, the size method doesn't exist any more. Something like the following worked for me (based on this github issue):

simulation
    .force("center", d3.forceCenter(width / 2, height / 2))
    .force("x", d3.forceX(width / 2))
    .force("y", d3.forceY(height / 2))
    .alpha(0.1).restart();

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Edit the configuration and then in the box: Script path, select your .py file!

Android BroadcastReceiver within Activity

You need to define the receiver as a class in the manifest and it will receive the intent:

<application
  ....
  <receiver android:name=".ToastReceiver">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

And you don't need to create the class manually inside ToastDisplay.

In the code you provided, you must be inside ToastDisplay activity to actually receive the Intent.

Makefile, header dependencies

If you are using a GNU compiler, the compiler can assemble a list of dependencies for you. Makefile fragment:

depend: .depend

.depend: $(SRCS)
        rm -f "$@"
        $(CC) $(CFLAGS) -MM $^ -MF "$@"

include .depend

or

depend: .depend

.depend: $(SRCS)
        rm -f "$@"
        $(CC) $(CFLAGS) -MM $^ > "$@"

include .depend

where SRCS is a variable pointing to your entire list of source files.

There is also the tool makedepend, but I never liked it as much as gcc -MM

MSSQL Select statement with incremental integer column... not from a table

You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:

select @StartChequeNumber = 3446;
SELECT 
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable

will give the correct cheque number for each row.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')

Store boolean value in SQLite

There is no native boolean data type for SQLite. Per the Datatypes doc:

SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

What's alternative to angular.copy in Angular

As others have already pointed out, using lodash or underscore is probably the best solution. But if you do not need those libraries for anything else, you can probably use something like this:

  function deepClone(obj) {

    // return value is input is not an Object or Array.
    if (typeof(obj) !== 'object' || obj === null) {
      return obj;    
    }

    let clone;

    if(Array.isArray(obj)) {
      clone = obj.slice();  // unlink Array reference.
    } else {
      clone = Object.assign({}, obj); // Unlink Object reference.
    }

    let keys = Object.keys(clone);

    for (let i=0; i<keys.length; i++) {
      clone[keys[i]] = deepClone(clone[keys[i]]); // recursively unlink reference to nested objects.
    }

    return clone; // return unlinked clone.

  }

That's what we decided to do.

Postgresql 9.2 pg_dump version mismatch

I had same error and this is how I solved it in my case. This means your postgresql version is 9.2.1 but you have started postgresql service of 9.1.6.

If you run psql postgres you will see:

psql (9.2.1, server 9.1.6)

What I did to solve this problem is:

  1. brew services stop [email protected]
  2. brew services restart [email protected]

Now run psql postgres and you should have: psql (9.2.1)

You can also run brew services list to see the status of your postgres.

Subset a dataframe by multiple factor levels

Here's another:

data[data$Code == "A" | data$Code == "B", ]

It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,

data[Code == "A" | Code == "B", ]

also works, which is one of the really useful things about R.

Running vbscript from batch file

Just try this code:

start "" "C:\Users\DiPesh\Desktop\vbscript\welcome.vbs"

and save as .bat, it works for me

Setting up connection string in ASP.NET to SQL SERVER

You can also use external configuration file to specify connection strings section, and refer that file in application configuration file like in web.config

Like the in web.config file:

<configuration>  
    <connectionStrings configSource="connections.config"/>  
</configuration>  

The external configuration connections.config file will contains connections section

<connectionStrings>  
  <add name="Name"   
   providerName="System.Data.ProviderName"   
   connectionString="Valid Connection String;" />  

</connectionStrings>  

Modifying contents of external configuration file will not restart the application (as ASP.net does by default with any change in application configuration files)

Angular 2 - NgFor using numbers instead collections

A simplest way that i have tried

You can also create an array in your component file and you can call it with *ngFor directive by returning as an array .

Something like this ....

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-morning',
  templateUrl: './morning.component.html',
  styleUrls: ['./morning.component.css']
})
export class MorningComponent implements OnInit {

  arr = [];
  i: number = 0;
  arra() {
    for (this.i = 0; this.i < 20; this.i++) {
      this.arr[this.i]=this.i;
    }
    return this.arr;
  }

  constructor() { }

  ngOnInit() {
  }

}

And this function can be used in your html template file

<p *ngFor="let a of arra(); let i= index">
value:{{a}} position:{{i}}
</p>

How do I jump to a closing bracket in Visual Studio Code?

i use End key, but. as you said you found a way to solve this problem in sublime text... right????

i will suggest you to install keymap of sublime text .. here and use that sortcut key to solve your same problem in vscode.

how to install
press -> ctrl + k then ctrl + M

or watch the bottom left corner there is a gear called setting click on theat you will found keymaps you will redirected to the extentions were you will have to choose your ex-editor..

How to resize an image to a specific size in OpenCV?

You can use cvResize. Or better use c++ interface (eg cv::Mat instead of IplImage and cv::imread instead of cvLoadImage) and then use cv::resize which handles memory allocation and deallocation itself.

Can an Android App connect directly to an online mysql database

It is actually very easy. But there is no way you can achieve it directly. You need to select a service side technology. You can use anything for this part. And this is what we call a RESTful API or a SOAP API. It depends on you what to select. I have done many project with both. I would prefer REST. So what will happen you will have some scripts in your web server, and you know the URLs. For example we need to make a user registration. And for this we have

mydomain.com/v1/userregister.php

Now from the android side you will send an HTTP request to the above URL. And the above URL will handle the User Registration and will give you a response that whether the operation succeed or not.

For a complete detailed explanation of the above concept. You can visit the following link.

**Android MySQL Tutorial to Perform CRUD Operation**

How to fix Cannot find module 'typescript' in Angular 4?

If you don't have particular needs, I suggest to install Typescript locally.

NPM Installation Method

npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation

Yarn Installation Method

yarn global add typescript # Global installation
yarn add --dev typescript # Local installation

When should I use git pull --rebase?

You should use git pull --rebase when

  • your changes do not deserve a separate branch

Indeed -- why not then? It's more clear, and doesn't impose a logical grouping on your commits.


Ok, I suppose it needs some clarification. In Git, as you probably know, you're encouraged to branch and merge. Your local branch, into which you pull changes, and remote branch are, actually, different branches, and git pull is about merging them. It's reasonable, since you push not very often and usually accumulate a number of changes before they constitute a completed feature.

However, sometimes--by whatever reason--you think that it would actually be better if these two--remote and local--were one branch. Like in SVN. It is here where git pull --rebase comes into play. You no longer merge--you actually commit on top of the remote branch. That's what it actually is about.

Whether it's dangerous or not is the question of whether you are treating local and remote branch as one inseparable thing. Sometimes it's reasonable (when your changes are small, or if you're at the beginning of a robust development, when important changes are brought in by small commits). Sometimes it's not (when you'd normally create another branch, but you were too lazy to do that). But that's a different question.

Plot 3D data in R

Adding to the solutions of others, I'd like to suggest using the plotly package for R, as this has worked well for me.

Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")

enter image description here

The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.

You can also try it with the built-in volcano dataset from R:

plot_ly(z=volcano, type="surface")

enter image description here

Simple Deadlock Examples

package ForkBlur;

public class DeadLockTest {
  public static void main(String args[]) {

    final DeadLockTest t1 = new DeadLockTest();
    final DeadLockTest t2 = new DeadLockTest();

    Runnable r1 = new Runnable() {

        @Override
        public void run() {
            try {

                synchronized (t1) {
                    System.out
                            .println("r1 has locked t1, now going to sleep");
                    Thread.sleep(100);
                    System.out
                            .println("r1 has awake , now going to aquire lock for t2");
                    synchronized (t2) {
                        Thread.sleep(100);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    Runnable r2 = new Runnable() {

        @Override
        public void run() {
            try {

                synchronized (t2) {
                    System.out
                            .println("r2 has aquire the lock of t2 now going to sleep");
                    Thread.sleep(100);
                    System.out
                            .println("r2 is awake , now going to aquire the lock from t1");
                    synchronized (t1) {
                        Thread.sleep(100);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    new Thread(r1).start();
    new Thread(r2).start();
  }
}

How can I parse String to Int in an Angular expression?

Besides {{ 1 * num_str + 1}} You can also try like this(minus first):

{{ num_str - 0 + 1}}

But the it's very fragile, if num_str contains letters, then it will fail. So better should try writing a filter as @hassassin said, or preprocess the data right after initiating it.

How to test my servlet using JUnit

EDIT: Cactus is now a dead project: http://attic.apache.org/projects/jakarta-cactus.html


You may want to look at cactus.

http://jakarta.apache.org/cactus/

Project Description

Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters, ...).

The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it.

Cactus implements an in-container strategy, meaning that tests are executed inside the container.

Read file line by line using ifstream in C++

Use ifstream to read data from a file:

std::ifstream input( "filename.ext" );

If you really need to read line by line, then do this:

for( std::string line; getline( input, line ); )
{
    ...for each line in input...
}

But you probably just need to extract coordinate pairs:

int x, y;
input >> x >> y;

Update:

In your code you use ofstream myfile;, however the o in ofstream stands for output. If you want to read from the file (input) use ifstream. If you want to both read and write use fstream.

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

I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.

How to check whether particular port is open or closed on UNIX?

Try (maybe as root)

lsof -i -P

and grep the output for the port you are looking for.

For example to check for port 80 do

lsof -i -P | grep :80

Why do some functions have underscores "__" before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

Convert string to Date in java

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

How to use filter, map, and reduce in Python 3

Lambda

Try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value:

# Python code to illustrate cube of a number 
# showing difference between def() and lambda(). 
def cube(y): 
    return y*y*y 
  
lambda_cube = lambda y: y*y*y 
  
# using the normally 
# defined function 
print(cube(5)) 
  
# using the lamda function 
print(lambda_cube(5)) 

output:

125
125

Without using Lambda:

  • Here, both of them return the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.

Using Lambda:

  • Lambda definition does not include a “return” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.

Lambda functions can be used along with built-in functions like filter(), map() and reduce().

lambda() with filter()

The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True.

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)


ages = [13, 90, 17, 59, 21, 60, 5]

adults = list(filter(lambda age: age>18, ages)) 
  
print(adults) # above 18 yrs 

output:

[4, 6, 8, 12]
[90, 59, 21, 60]

lambda() with map()

The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

print(new_list)


cities = ['novi sad', 'ljubljana', 'london', 'new york', 'paris'] 
  
# change all city names 
# to upper case and return the same 
uppered_cities = list(map(lambda city: str.upper(city), cities)) 
  
print(uppered_cities)

output:

[2, 10, 8, 12, 16, 22, 6, 24]
['NOVI SAD', 'LJUBLJANA', 'LONDON', 'NEW YORK', 'PARIS']

reduce

reduce() works differently than map() and filter(). It does not return a new list based on the function and iterable we've passed. Instead, it returns a single value.

Also, in Python 3 reduce() isn't a built-in function anymore, and it can be found in the functools module.

The syntax is:

reduce(function, sequence[, initial])

reduce() works by calling the function we passed for the first two items in the sequence. The result returned by the function is used in another call to function alongside with the next (third in this case), element.

The optional argument initial is used, when present, at the beginning of this "loop" with the first element in the first call to function. In a way, the initial element is the 0th element, before the first one, when provided.

lambda() with reduce()

The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable.

from functools import reduce

my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34] 

sum = reduce((lambda x, y: x + y), my_list) 

print(sum) # sum of a list
print("With an initial value: " + str(reduce(lambda x, y: x + y, my_list, 100)))
88
With an initial value: 188

These functions are convenience functions. They are there so you can avoid writing more cumbersome code, but avoid using both them and lambda expressions too much, because "you can", as it can often lead to illegible code that's hard to maintain. Use them only when it's absolutely clear what's going on as soon as you look at the function or lambda expression.

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Use IGNORE_DUP_KEY = OFF during primary key definition to ignore the duplicates while insert. for example

create table X( col1.....)

CONSTRAINT [pk_X] PRIMARY KEY CLUSTERED 
(
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 70) ON [PRIMARY]
) ON [PRIMARY]

Adding space/padding to a UILabel

Swift 3

import UIKit

class PaddingLabel: UILabel {

   @IBInspectable var topInset: CGFloat = 5.0
   @IBInspectable var bottomInset: CGFloat = 5.0
   @IBInspectable var leftInset: CGFloat = 5.0
   @IBInspectable var rightInset: CGFloat = 5.0

   override func drawText(in rect: CGRect) {
      let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
      super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
   }

   override var intrinsicContentSize: CGSize {
      get {
         var contentSize = super.intrinsicContentSize
         contentSize.height += topInset + bottomInset
         contentSize.width += leftInset + rightInset
         return contentSize
      }
   }
}

Checking Value of Radio Button Group via JavaScript?

If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.

<form name="myForm">
    <input type="radio" id="genderm" name="gender" value="male" />
    <label for="genderm">Male</label>
    <input type="radio" id="genderf" name="gender" value="female" />
    <label for="genderf">Female</label>
</form>

<script>
    var selected = document.forms.myForm.gender.value;
</script>

How to install gem from GitHub source?

On a fresh Linux machine you also need to install git. Bundle uses it behind the scenes.

The thread has exited with code 0 (0x0) with no unhandled exception

Executing Linq queries can generate extra threads. When I try to execute code that uses Linq query collection in the immediate window it often refuses to run because not enough threads are available to the debugger.

As others have said, for threads to exit when they are finished is perfectly normal.

Generating statistics from Git repository

If your project is on GitHub, you now (April 2013) have Pulse (see "Get up to speed with Pulse"):

It is more limited, and won't display all the stats you might need, but is readily available for any GitHub project.

Pulse is a great way to discover recent activity on projects.
Pulse will show you who has been actively committing and what has changed in a project's default branch:

Pulse

You can find the link to the left of the nav bar.

Link

Note that there isn't (yet) an API to extract that information.

Creating a new user and password with Ansible

How to create encrypted password for passing to password var to Ansible user task (from @Brendan Wood's comment):

openssl passwd -salt 'some_plain_salt' -1 'some_plain_pass'

The result will look like:

$1$some_pla$lmVKJwdV3Baf.o.F0OOy71

Example of user task:

- name: Create user
  user: name="my_user" password="$1$some_pla$lmVKJwdV3Baf.o.F0OOy71"

UPD: crypt using SHA-512 see here and here:

Python

$ python -c "import crypt, getpass, pwd; print crypt.crypt('password', '\$6\$saltsalt\$')"

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

Perl

$ perl -e 'print crypt("password","\$6\$saltsalt\$") . "\n"'

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

Ruby

$ ruby -e 'puts "password".crypt("$6$saltsalt$")'

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

What do the different readystates in XMLHttpRequest mean, and how can I use them?

  • 0 : UNSENT Client has been created. open() not called yet.
  • 1 : OPENED open() has been called.
  • 2 : HEADERS_RECEIVED send() has been called, and headers and status are available.
  • 3 : LOADING Downloading; responseText holds partial data.
  • 4 : DONE The operation is complete.

(From https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState)

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Have you tried @Lazy loading the datasource? Because you're initialising your embedded Tomcat container within the Spring context, you have to delay the initialisation of your DataSource (until the JNDI vars have been setup).

N.B. I haven't had a chance to test this code yet!

@Lazy
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    //bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

You may also need to add the @Lazy annotation wherever the DataSource is being used. e.g.

@Lazy
@Autowired
private DataSource dataSource;

Java: How to convert List to Map

like already said, in java-8 we have the concise solution by Collectors:

  list.stream().collect(
         groupingBy(Item::getKey)
        )

and also, you can nest multiple group passing an other groupingBy method as second parameter:

  list.stream().collect(
         groupingBy(Item::getKey, groupingBy(Item::getOtherKey))
        )

In this way, we'll have multi level map, like this: Map<key, Map<key, List<Item>>>

What is the difference between $routeProvider and $stateProvider?

$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.

When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.

<div ng-view></div>
    $routeProvider
        .when('/contact/', {
            templateUrl: 'app/views/core/contact/contact.html',
            controller: 'ContactCtrl'
        });


<div ui-view>
    <div ui-view='abc'></div>
    <div ui-view='abc'></div>
   </div>
    $stateProvider
        .state("contact", {
            url: "/contact/",
            templateUrl: '/app/Aisel/Contact/views/contact.html',
            controller: 'ContactCtrl'
        });

String formatting in Python 3

I like this approach

my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)

Note the appended d and s to the brackets respectively.

output will be:

I scored 3 goals and took 5 penalties

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Gradle version 2.2 is required. Current version is 2.10

Here's what I did to fix this:

1) Create a new project

2) open the gradle-wrapper.properties file and copy the distributionUrl to your project e.g.:

distributionUrl=https\://services.gradle.org/distributions/gradle-3.2-all.zip

3) open the build.gradle (Project) and copy the gradle dependency to your project e.g.:

classpath 'com.android.tools.build:gradle:2.3.0-beta1'

4) File --> Invalidate Caches / Restart (I think a re-sync may have sufficed, but didn't try it)

5) Delete that project you made (optional)

Look, this is a silly way to do things, but Android Studio is free so who am I to complain...

ReactJS SyntheticEvent stopPropagation() only works with React events?

I was able to resolve this by adding the following to my component:

componentDidMount() {
  ReactDOM.findDOMNode(this).addEventListener('click', (event) => {
    event.stopPropagation();
  }, false);
}

How do I get rid of the b-prefix in a string in python?

you need to decode the bytes of you want a string:

b = b'1234'
print(b.decode('utf-8'))  # '1234'

Capturing a single image from my webcam in Java or Python

@thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.

using SimpleCV (not supported in python3.x):

from SimpleCV import Image, Camera

cam = Camera()
img = cam.getImage()
img.save("filename.jpg")

using OpenCV:

from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
    imshow("cam-test",img)
    waitKey(0)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image

using pygame:

import pygame
import pygame.camera

pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")

Install OpenCV:

install python-opencv bindings, numpy

Install SimpleCV:

install python-opencv, pygame, numpy, scipy, simplecv

get latest version of SimpleCV

Install pygame:

install pygame

How to replace (null) values with 0 output in PIVOT

Sometimes it's better to think like a parser, like T-SQL parser. While executing the statement, parser does not have any value in Pivot section and you can't have any check expression in that section. By the way, you can simply use this:

SELECT  CLASS
,   IsNull([AZ], 0)
,   IsNull([CA], 0)
,   IsNull([TX], 0)
    FROM #TEMP
    PIVOT (
        SUM(DATA)
        FOR STATE IN (
            [AZ]
        ,   [CA]
        ,   [TX]
        )
    )   AS  PVT
    ORDER   BY  CLASS

How do you get the path to the Laravel Storage folder?

For Laravel version >=5.1

storage_path()

The storage_path function returns the fully qualified path to the storage directory:

$path = storage_path();

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');

Source: Laravel Doc

How to replace a character from a String in SQL?

This will replace all ? with ':

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
WHERE city LIKE '%?%'

If you need to update more than one column, you can either change city each time you execute to a different column name, or list the columns like so:

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
      ,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'

How to get String Array from arrays.xml file

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

What is the difference between MacVim and regular Vim?

It's all about the key bindings which one can simply achieve from .vimrc configurations. As far as clipboard is concerned you can use :set clipboard unnamed and the yank from vim will go to system clipboard. Anyways, whichever one you end up using I suggest using this vimrc config , it contains a whole lot of plugins and bindings which will make your experience smooth.

Convert digits into words with JavaScript

var inWords = function(totalRent){
//console.log(totalRent);
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
var number = parseFloat(totalRent).toFixed(2).split(".");
var num = parseInt(number[0]);
var digit = parseInt(number[1]);
//console.log(num);
if ((num.toString()).length > 9)  return 'overflow';
var n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
var d = ('00' + digit).substr(-2).match(/^(\d{2})$/);;
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'Rupee ' : '';
str += (d[1] != 0) ? ((str != '' ) ? "and " : '') + (a[Number(d[1])] || b[d[1][0]] + ' ' + a[d[1][1]]) + 'Paise ' : 'Only!';
console.log(str);
return str;
}

This is modified code supports for Indian Rupee with 2 decimal place.

Hibernate Union alternatives

I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.

The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.

The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.

What is the opposite of :hover (on mouse leave)?

Just add a transition and the name of the animation on the class inicial, in your case, ul li a, just add a "transition" property and that is all you need

_x000D_
_x000D_
ul li {_x000D_
    display: inline;_x000D_
    margin-left: 20px;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
    color: #999;_x000D_
    transition: 1s;_x000D_
    -webkit-animation: item-hover-off 1s;_x000D_
    -moz-animation: item-hover-off 1s;_x000D_
    animation: item-hover-off 1s;_x000D_
}_x000D_
_x000D_
ul li a:hover {_x000D_
    color: black;_x000D_
    cursor: pointer;_x000D_
    -webkit-animation: item-hover 1s;_x000D_
    -moz-animation: item-hover 1s;_x000D_
    animation: item-hover 1s;_x000D_
}_x000D_
_x000D_
@keyframes item-hover {_x000D_
    from {_x000D_
      color: #999;_x000D_
      }_x000D_
    to {_x000D_
      color: black;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-moz-keyframes item-hover {_x000D_
    from {_x000D_
        color: #999;_x000D_
      }_x000D_
    to {_x000D_
        color: black;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-webkit-keyframes item-hover {_x000D_
    from {_x000D_
        color: #999;_x000D_
      }_x000D_
    to {_x000D_
        color: black;_x000D_
      }_x000D_
}_x000D_
_x000D_
@keyframes item-hover-off {_x000D_
    from {_x000D_
      color: black;_x000D_
      }_x000D_
    to {_x000D_
      color: #999;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-moz-keyframes item-hover-off {_x000D_
    from {_x000D_
        color: black;_x000D_
      }_x000D_
    to {_x000D_
        color: #999;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-webkit-keyframes item-hover-off {_x000D_
    from {_x000D_
        color: black;_x000D_
      }_x000D_
    to {_x000D_
        color: #999;_x000D_
      }_x000D_
}
_x000D_
<ul>_x000D_
    <li><a>Home</a></li>_x000D_
    <li><a>About</a></li>_x000D_
    <li><a>Contacts</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to load npm modules in AWS Lambda?

npm module has to be bundeled inside your nodejs package and upload to AWS Lambda Layers as zip, then you would need to refer to your module/js as below and use available methods from it. const mymodule = require('/opt/nodejs/MyLogger');

Switch case with conditions

This should work with this :

var cnt = $("#div1 p").length;

            switch (true) {
                case (cnt >= 10 && cnt <= 20):
                    alert('10');
                    break;
                case (cnt >= 21 && cnt <= 30):
                   alert('21');
                    break;
                case (cnt >= 31 && cnt <= 40):
                    break;
                default:
                    alert('>41');
            }

JavaScript: What are .extend and .prototype used for?

The extend method for example in jQuery or PrototypeJS, copies all properties from the source to the destination object.

Now about the prototype property, it is a member of function objects, it is part of the language core.

Any function can be used as a constructor, to create new object instances. All functions have this prototype property.

When you use the new operator with on a function object, a new object will be created, and it will inherit from its constructor prototype.

For example:

function Foo () {
}
Foo.prototype.bar = true;

var foo = new Foo();

foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true

How can I plot data with confidence intervals?

Here is a solution using functions plot(), polygon() and lines().

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


 plot(df$x, df$F, ylim = c(0,4), type = "l")
 #make polygon where coordinates start with lower limit and 
 # then upper limit in reverse order
 polygon(c(df$x,rev(df$x)),c(df$L,rev(df$U)),col = "grey75", border = FALSE)
 lines(df$x, df$F, lwd = 2)
 #add red lines on borders of polygon
 lines(df$x, df$U, col="red",lty=2)
 lines(df$x, df$L, col="red",lty=2)

enter image description here

Now use example data provided by OP in another question:

   Lower <- c(0.418116841, 0.391011834, 0.393297710,
        0.366144073,0.569956636,0.224775521,0.599166016,0.512269587,
        0.531378573, 0.311448219, 0.392045751,0.153614913, 0.366684097,
        0.161100849,0.700274810,0.629714150, 0.661641288, 0.533404093,
        0.412427559, 0.432905333, 0.525306427,0.224292061,
        0.28893064,0.099543648, 0.342995605,0.086973739,0.289030388,
        0.081230826,0.164505624, -0.031290586,0.148383474,0.070517523,0.009686605,
        -0.052703529,0.475924192,0.253382210, 0.354011010,0.130295355,0.102253218,
        0.446598823,0.548330752,0.393985810,0.481691632,0.111811248,0.339626541,
        0.267831909,0.133460254,0.347996621,0.412472322,0.133671128,0.178969601,0.484070587,
        0.335833224,0.037258467, 0.141312363,0.361392799,0.129791998,
        0.283759439,0.333893418,0.569533076,0.385258093,0.356201955,0.481816148,
        0.531282473,0.273126565,0.267815691,0.138127486,0.008865700,0.018118398,0.080143484,
        0.117861634,0.073697418,0.230002398,0.105855042,0.262367348,0.217799352,0.289108011,
        0.161271889,0.219663224,0.306117717,0.538088622,0.320711912,0.264395149,0.396061543,
        0.397350946,0.151726970,0.048650180,0.131914718,0.076629840,0.425849394,
        0.068692279,0.155144797,0.137939059,0.301912657,-0.071415593,-0.030141781,0.119450922,
        0.312927614,0.231345972)

 Upper.limit <- c(0.6446223,0.6177311, 0.6034427, 0.5726503,
      0.7644718, 0.4585430, 0.8205418, 0.7154043,0.7370033,
      0.5285199, 0.5973728, 0.3764209, 0.5818298,
      0.3960867,0.8972357, 0.8370151, 0.8359921, 0.7449118,
      0.6152879, 0.6200704, 0.7041068, 0.4541011, 0.5222653,
      0.3472364, 0.5956551, 0.3068065, 0.5112895, 0.3081448,
      0.3745473, 0.1931089, 0.3890704, 0.3031025, 0.2472591,
      0.1976092, 0.6906118, 0.4736644, 0.5770463, 0.3528607,
      0.3307651, 0.6681629, 0.7476231, 0.5959025, 0.7128883,
      0.3451623, 0.5609742, 0.4739216, 0.3694883, 0.5609220,
      0.6343219, 0.3647751, 0.4247147, 0.6996334, 0.5562876,
      0.2586490, 0.3750040, 0.5922248, 0.3626322, 0.5243285,
      0.5548211, 0.7409648, 0.5820070, 0.5530232, 0.6863703,
      0.7206998, 0.4952387, 0.4993264, 0.3527727, 0.2203694,
      0.2583149, 0.3035342, 0.3462009, 0.3003602, 0.4506054,
      0.3359478, 0.4834151, 0.4391330, 0.5273411, 0.3947622,
      0.4133769, 0.5288060, 0.7492071, 0.5381701, 0.4825456,
      0.6121942, 0.6192227, 0.3784870, 0.2574025, 0.3704140,
      0.2945623, 0.6532694, 0.2697202, 0.3652230, 0.3696383,
      0.5268808, 0.1545602, 0.2221450, 0.3553377, 0.5204076,
      0.3550094)

  Fitted.values<- c(0.53136955, 0.50437146, 0.49837019,
  0.46939721, 0.66721423, 0.34165926, 0.70985388, 0.61383696,
  0.63419092, 0.41998407, 0.49470927, 0.26501789, 0.47425695,
  0.27859380, 0.79875525, 0.73336461, 0.74881668, 0.63915795,
  0.51385774, 0.52648789, 0.61470661, 0.33919656, 0.40559797,
  0.22339000, 0.46932536, 0.19689011, 0.40015996, 0.19468781,
  0.26952645, 0.08090917, 0.26872696, 0.18680999, 0.12847285,
  0.07245286, 0.58326799, 0.36352329, 0.46552867, 0.24157804,
  0.21650915, 0.55738088, 0.64797691, 0.49494416, 0.59728999,
  0.22848680, 0.45030036, 0.37087676, 0.25147426, 0.45445930,
  0.52339711, 0.24922310, 0.30184215, 0.59185198, 0.44606040,
  0.14795374, 0.25815819, 0.47680880, 0.24621212, 0.40404398,
  0.44435727, 0.65524894, 0.48363255, 0.45461258, 0.58409323,
  0.62599114, 0.38418264, 0.38357103, 0.24545011, 0.11461756,
  0.13821664, 0.19183886, 0.23203127, 0.18702881, 0.34030391,
  0.22090140, 0.37289121, 0.32846615, 0.40822456, 0.27801706,
  0.31652008, 0.41746184, 0.64364785, 0.42944100, 0.37347037,
  0.50412786, 0.50828681, 0.26510696, 0.15302635, 0.25116438,
  0.18559609, 0.53955941, 0.16920626, 0.26018389, 0.25378867,
  0.41439675, 0.04157232, 0.09600163, 0.23739430, 0.41666762,
  0.29317767)

Assemble into a data frame (no x provided, so using indices)

 df2 <- data.frame(x=seq(length(Fitted.values)),
                    fit=Fitted.values,lwr=Lower,upr=Upper.limit)
 plot(fit~x,data=df2,ylim=range(c(df2$lwr,df2$upr)))
 #make polygon where coordinates start with lower limit and then upper limit in reverse order
 with(df2,polygon(c(x,rev(x)),c(lwr,rev(upr)),col = "grey75", border = FALSE))
 matlines(df2[,1],df2[,-1],
          lwd=c(2,1,1),
          lty=1,
          col=c("black","red","red"))

enter image description here

How to compile Tensorflow with SSE4.2 and AVX instructions?

2.0 COMPATIBLE SOLUTION:

Execute the below commands in Terminal (Linux/MacOS) or in Command Prompt (Windows) to install Tensorflow 2.0 using Bazel:

git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow

#The repo defaults to the master development branch. You can also checkout a release branch to build:
git checkout r2.0

#Configure the Build => Use the Below line for Windows Machine
python ./configure.py 

#Configure the Build => Use the Below line for Linux/MacOS Machine
./configure
#This script prompts you for the location of TensorFlow dependencies and asks for additional build configuration options. 

#Build Tensorflow package

#CPU support
bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package 

#GPU support
bazel build --config=opt --config=cuda --define=no_tensorflow_py_deps=true //tensorflow/tools/pip_package:build_pip_package

How should I validate an e-mail address?

Note that most of the regular expressions are not valid for international domain names (IDN) and new top level domains like .mobi or .info (if you check for country codes or .org, .com, .gov and so on).

A valid check should separate the local part (before the at-sign) and the domain part. You should also consider the max length of the local part and domain (in sum 255 chars including the at-sign).

The best approach is to transform the address in an IDN compatible format (if required), validate the local part (RFC), check the length of the address and the check the availability of the domain (DNS MX lookup) or simply send an email.

Populating VBA dynamic arrays

In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are

  1. Creating an array big enough to handle anything you think will be thrown at it
  2. Sensible use of Redim Preserve

The code below provides an example of a routine that will dimension myArray in line with the lngSize variable, then add additional elements (equal to the initial array size) by use of a Mod test whenever the upper bound is about to be exceeded

Option Base 1

Sub ArraySample()
    Dim myArray() As String
    Dim lngCnt As Long
    Dim lngSize As Long

    lngSize = 10
    ReDim myArray(1 To lngSize)

    For lngCnt = 1 To lngSize*5
        If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
        myArray(lngCnt) = "I am record number " & lngCnt
    Next
End Sub

SQL Add foreign key to existing column

Maybe you got your columns backwards??

ALTER TABLE Employees
ADD FOREIGN KEY (UserID)           <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id)   <-- this needs to be a column of the ActiveDirectories table

Could it be that the column is called ID in the Employees table, and UserID in the ActiveDirectories table?

Then your command should be:

ALTER TABLE Employees
ADD FOREIGN KEY (ID)                   <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID)   <-- column in table "ActiveDirectories" 

Angular.js: set element height on page load

A slight improvement to Bizzard's excellent answer. Supports width-offset and/or height-offset on the element, to determine how much will be subtracted from the width/height, and prevents negative dimensions.

 <div resize height-offset="260" width-offset="100">

directive:

app.directive('resize', ['$window', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        var heightOffset = parseInt(element.attr('height-offset'));
        var widthOffset = parseInt(element.attr('width-offset'));
        var changeHeight = function () {
            if (!isNaN(heightOffset) && w.height() - heightOffset > 0)
                element.css('height', (w.height() - heightOffset) + 'px');
            if (!isNaN(widthOffset) && w.width() - widthOffset > 0)
                element.css('width', (w.width() - widthOffset) + 'px');
        };
        w.bind('resize', function () {
            changeHeight();
        });
        changeHeight();
    }
}]);

Edit This is actually a silly way of doing it in modern browsers. CSS3 has calc, which allows the calculation to be specified in CSS, like this:

#myDiv {
 width: calc(100% - 200px);
 height: calc(100% - 120px);
}

http://caniuse.com/#search=calc

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

Defining constant string in Java?

Typically you'd define this toward the top of a class:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";

Of course, use the appropriate member visibility (public/private/protected) based on where you use this constant.

What's the function like sum() but for multiplication? product()?

There isn't one built in, but it's simple to roll your own, as demonstrated here:

import operator
def prod(factors):
    return reduce(operator.mul, factors, 1)

See answers to this question:

Which Python module is suitable for data manipulation in a list?

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

How do I execute a Shell built-in command with a C function?

You should execute sh -c echo $PWD; generally sh -c will execute shell commands.

(In fact, system(foo) is defined as execl("sh", "sh", "-c", foo, NULL) and thus works for shell built-ins.)

If you just want the value of PWD, use getenv, though.

What does "collect2: error: ld returned 1 exit status" mean?

In your situation you got a reference to the missing symbols. But in some situations, ld will not provide error information.

If you want to expand the information provided by ld, just add the following parameters to your $(LDFLAGS)

-Wl,-V

How to get the name of the current method from code

I think the best way to get the full name is:

 this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

or try this

string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);   

SQL Server Group By Month

I prefer combining DATEADD and DATEDIFF functions like this:

GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0)

Together, these two functions zero-out the date component smaller than the specified datepart (i.e. MONTH in this example).

You can change the datepart bit to YEAR, WEEK, DAY, etc... which is super handy.

Your original SQL query would then look something like this (I can't test it as I don't have your data set, but it should put you on the right track).

DECLARE @start [datetime] = '2010-04-01';

SELECT
    ItemID,
    UserID,
    DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0) [Month],
    IsPaid,
    SUM(Amount)
FROM LIVE L
INNER JOIN Payments I ON I.LiveID = L.RECORD_KEY
WHERE UserID = 16178
AND PaymentDate > @start

One more thing: the Month column is typed as a DateTime which is also a nice advantage if you need to further process that data or map it .NET object for example.

How can I create a border around an Android LinearLayout?

Creat XML called border.xml in drawable folder as below :

<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item> 
    <shape android:shape="rectangle">
      <solid android:color="#FF0000" /> 
    </shape>
  </item>   
    <item android:left="5dp" android:right="5dp"  android:top="5dp" >  
     <shape android:shape="rectangle"> 
      <solid android:color="#000000" />
    </shape>
   </item>    
 </layer-list>

then add this to linear layout as backgound as this:

     android:background="@drawable/border"

How can I call a WordPress shortcode within a template?

Make sure to enable the use of shortcodes in text widgets.

// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );

// and then you can use it in any PHP file:  
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>

Check the documentation for more.

How to add "Maven Managed Dependencies" library in build path eclipse?

I could figure out the problem. I was getting following warning on startup of eclipse.

The Maven Integration requires that Eclipse be running in a JDK, because a number of Maven core plugins are using jars from the JDk.

Please make sure the -vm option in eclipse.ini is pointing to a JDK and verify that
Installed JRE's are also using JDK installs

I changed eclipse.ini file and added following and restarted eclipse

-vm
C:/Program Files/java/jdk1.6.0_21/bin/javaw.exe

Now I can see "Maven Dependency" library included automatically in java build path.

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

DropDownList1.Items.FindByValue(stringValue).Selected = true; 

should work.

How do I get extra data from intent on Android?

Pass the intent with value on First Activity:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

Receive intent on second Activity;-

Intent intent = getIntent();
String user = intent.getStringExtra("uid");
String pass = intent.getStringExtra("pwd");

We use generally two method in intent to send the value and to get the value. For sending the value we will use intent.putExtra("key", Value); and during receive intent on another activity we will use intent.getStringExtra("key"); to get the intent data as String or use some other available method to get other types of data (Integer, Boolean, etc.). The key may be any keyword to identify the value means that what value you are sharing. Hope it will work for you.

m2eclipse not finding maven dependencies, artifacts not found

This could be a problem if you are using a custom 'Settings.xml', with a different <localRepository> configured in it.

Eclipse will be using the default installation of MAVEN, and will be using the default location for the User to look for the local Maven repository, which on Linux systems would be '/home/${USER}/.m2/'

Eclipse can be easily configured to use the customized 'Settings.xml', by doing the following: Goto -> Window -> Preferences -> Select 'Maven' -> Select 'User Settings'

  1. Under 'User Settings', select the custom 'Settings.xml' file, for 'User Settings' by clicking 'Browse' and selecting the customized 'Settings.xml'.
  2. Click on 'Update Settings', if the 'Local Repository' Textbox does not show the custom location from the file above, just key in the location and click 'Reindex'.
  3. Click 'OK'

After this, you could proceed to select your project from the 'Project Explorer', right click, Select 'Maven' > 'Update Project'. Make sure that your project is selected (ticked) in the Window, and click 'OK'.

This should help to resolve the issue, if using custom 'Settings.xml' for Maven.

Hope it helps.

How to include a class in PHP

You can use either of the following:

include "class.twitter.php";

or

require "class.twitter.php";

Using require (or require_once if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include will only raise a warning. See http://php.net/require and http://php.net/include for more details

JQuery .hasClass for multiple values in an if statement

var classes = $('html')[0].className;

if (classes.indexOf('m320') != -1 || classes.indexOf('m768') != -1) {
    //do something
}

Using $_POST to get select option value from HTML

Use this way:

$selectOption = $_POST['taskOption'];

But it is always better to give values to your <option> tags.

<select name="taskOption">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
</select>

Writing to a file in a for loop

It's preferable to use context managers to close the files automatically

with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
    for line in textfile:
        var1, var2 = line.split(",");
        myfile.writelines(var1)

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

I run selenium tests with Jenkins running on an Ubuntu 18 LTS linux. I had this error until I added the argument 'headless' like this (and some other arguments):

ChromeOptions options = new ChromeOptions();
options.addArguments("headless"); // headless -> no browser window. needed for jenkins
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
ChromeDriver driver = new ChromeDriver(options);

driver.get("www.google.com");

How to start new line with space for next line in Html.fromHtml for text view in android

use <br/> tag

Example:

<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>

How to use addTarget method in swift 3

Try this

button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside). 

Just add parenthesis with name of method.

Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'

Using Server.MapPath in external C# Classes in ASP.NET

The ServerUtility class is available as an instance in your HttpContext. If you're in an environment where you know it'll be executed inside the ASP.Net pipeline, you can use

HttpContext.Current.Server.MapPath()

You'll have to import System.Web though.

How to get the previous URL in JavaScript?

If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:

window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")

Then, in your new route, you can do the following to retrieve the previous URL:

window.history.state.prevUrl // your previous url

JavaScript push to array

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push (  {"cool":"34.39","also cool":"45459"} );

Your variable is a javascript object {} not an array [].

You could do:

var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";

and

var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };

Later, you add those objects to your array: array.push (o, o2);

Also JSON is simply a string representation of a javascript object, thus:

var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again

How to reference a file for variables using Bash?

even shorter using the dot:

#!/bin/bash
. CONFIG_FILE

sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

From http://docs.python.org/library/csv.html#csv.writer:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with statement to close the file when you're done writing to it.
Tested example below:

from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
    output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
    output.writerow(dict((fn,fn) for fn in headers))
    output.writerows(rows)

Incrementing a date in JavaScript

Incrementing date's year with vanilla js:

start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020

Just in case someone wants to increment other value than the date (day)

How to change Label Value using javascript

This will work in Chrome

// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'

But after looking, labels doesn't seem to be widely supported..


You can use querySelector

// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

JUnit Eclipse Plugin?

It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").

How to grep (search) committed code in the Git history

Search in any revision, any file (unix/linux):

git rev-list --all | xargs git grep <regexp>

Search only in some given files, for example XML files:

git rev-list --all | xargs -I{} git grep <regexp> {} -- "*.xml"

The result lines should look like this: 6988bec26b1503d45eb0b2e8a4364afb87dde7af:bla.xml: text of the line it found...

You can then get more information like author, date, and diff using git show:

git show 6988bec26b1503d45eb0b2e8a4364afb87dde7af

How to return a PNG image from Jersey REST service method to the browser

I built a general method for that with following features:

  • returning "not modified" if the file hasn't been modified locally, a Status.NOT_MODIFIED is sent to the caller. Uses Apache Commons Lang
  • using a file stream object instead of reading the file itself

Here the code:

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger logger = LoggerFactory.getLogger(Utils.class);

@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
    File repositoryFile = new File("c:/temp/myfile.png");
    return returnFile(repositoryFile, modified);
}

/**
 * 
 * Sends the file if modified and "not modified" if not modified
 * future work may put each file with a unique id in a separate folder in tomcat
 *   * use that static URL for each file
 *   * if file is modified, URL of file changes
 *   * -> client always fetches correct file 
 * 
 *     method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
 * 
 * @param file to send
 * @param modified - HeaderField "If-Modified-Since" - may be "null"
 * @return Response to be sent to the client
 */
public static Response returnFile(File file, String modified) {
    if (!file.exists()) {
        return Response.status(Status.NOT_FOUND).build();
    }

    // do we really need to send the file or can send "not modified"?
    if (modified != null) {
        Date modifiedDate = null;

        // we have to switch the locale to ENGLISH as parseDate parses in the default locale
        Locale old = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);
        try {
            modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        Locale.setDefault(old);

        if (modifiedDate != null) {
            // modifiedDate does not carry milliseconds, but fileDate does
            // therefore we have to do a range-based comparison
            // 1000 milliseconds = 1 second
            if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
                return Response.status(Status.NOT_MODIFIED).build();
            }
        }
    }        
    // we really need to send the file

    try {
        Date fileDate = new Date(file.lastModified());
        return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
    } catch (FileNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}

/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/

/**
 * Date format pattern used to parse HTTP date headers in RFC 1123 format.
 */
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in RFC 1036 format.
 */
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in ANSI C
 * <code>asctime()</code> format.
 */
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";

public static final String[] DEFAULT_PATTERNS = new String[] {
    PATTERN_RFC1036,
    PATTERN_RFC1123,
    PATTERN_ASCTIME
};

Note that the Locale switching does not seem to be thread-safe. I think, it's better to switch the locale globally. I am not sure about the side-effects though...