Programs & Examples On #Failed to load viewstate

The failed to load viewstate error is a frequent problem encountered when creating dynamic asp.net pages when you fail to create the controls exactly the same way each postback.

MySQL ORDER BY rand(), name ASC

Use a subquery:

SELECT * FROM (
    SELECT * FROM users ORDER BY RAND() LIMIT 20
) u
ORDER BY name

or a join to itself:

SELECT * FROM users u1
INNER JOIN (
    SELECT id FROM users ORDER BY RAND() LIMIT 20
) u2 USING(id)
ORDER BY u1.name

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

How to install maven on redhat linux

Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file

Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:

wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz

And then proceed to install it.

UPDATE: Adding complete instructions (copied from the comment below)

  1. Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  2. run the following to extract the tar:

    tar xvf apache-maven-3.2.1-bin.tar.gz
    
  3. Next add the env varibles such as

    export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1

    export M2=$M2_HOME/bin

    export PATH=$M2:$PATH

  4. Verify

    mvn -version
    

Deleting an element from an array in PHP

You can simply use unset() to delete an array.

Remember that an array must be unset after the foreach function.

How to export data with Oracle SQL Developer?

To export data you need to right click on your results and select export data, after which you will be asked for a specific file format such as insert, loader, or text etc. After selecting this browse your directory and select the export destination.

Must issue a STARTTLS command first

You are probably attempting to use Gmail's servers on port 25 to deliver mail to a third party over an unauthenticated connection. Gmail doesn't let you do this, because then anybody could use Gmail's servers to send mail to anybody else. This is called an open relay and was a common enabler of spam in the early days. Open relays are no longer acceptable on the Internet.

You will need to ask your SMTP client to connect to Gmail using an authenticated connection, probably on port 587.

How to allow users to check for the latest app version from inside the app?

Google updated play store two months before. This is the solution working right now for me..

class GetVersionCode extends AsyncTask<Void, String, String> {

    @Override

    protected String doInBackground(Void... voids) {

        String newVersion = null;

        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName()  + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get();
            if (document != null) {
                Elements element = document.getElementsContainingOwnText("Current Version");
                for (Element ele : element) {
                    if (ele.siblingElements() != null) {
                        Elements sibElemets = ele.siblingElements();
                        for (Element sibElemet : sibElemets) {
                            newVersion = sibElemet.text();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newVersion;

    }


    @Override

    protected void onPostExecute(String onlineVersion) {

        super.onPostExecute(onlineVersion);

        if (onlineVersion != null && !onlineVersion.isEmpty()) {

            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show anything
            }

        }

        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);

    }
}

and don't forget to add JSoup library

dependencies {
compile 'org.jsoup:jsoup:1.8.3'}

and on Oncreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String currentVersion;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    new GetVersionCode().execute();

}

that's it.. Thanks to this link

Find the location of a character in string

Here's another straightforward alternative.

> which(strsplit(string, "")[[1]]=="2")
[1]  4 24

What does 'low in coupling and high in cohesion' mean

I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video, https://youtu.be/HpJTGW9AwX0 It's just reference to get more info about polymorphism... Hope you get better understanding with this

Extracting .jar file with command line

jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)

How do I wait until Task is finished in C#?

async Task<int> AccessTheWebAsync()  
{   
    // You need to add a reference to System.Net.Http to declare client.  
    HttpClient client = new HttpClient();  

    // GetStringAsync returns a Task<string>. That means that when you await the  
    // task you'll get a string (urlContents).  
    Task<string> getStringTask = 

    client.GetStringAsync("http://msdn.microsoft.com");  

    // You can do work here that doesn't rely on the string from GetStringAsync.  
    DoIndependentWork();  

    // The await operator suspends AccessTheWebAsync.  
    //  - AccessTheWebAsync can't continue until getStringTask is complete.  
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.  
    //  - Control resumes here when getStringTask is complete.   
    //  - The await operator then retrieves the string result from 
    getStringTask.  
    string urlContents = await getStringTask;  

    // The return statement specifies an integer result.  
    // Any methods that are awaiting AccessTheWebenter code hereAsync retrieve the length 
    value.  
    return urlContents.Length;  
}  

How to get cookie's expire time

It seems there's a list of all cookies sent to browser in array returned by php's headers_list() which among other data returns "Set-Cookie" elements as follows:

Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain

This way you can also get deleted ones since their value is deleted:

Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain

From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie() has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.

This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.

For more info see:

https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php

How do you force a makefile to rebuild a target

As abernier pointed out, there is a recommended solution in the GNU make manual, which uses a 'fake' target to force rebuilding of a target:

clean: FORCE
        rm $(objects)
FORCE: ; 

This will run clean, regardless of any other dependencies.

I added the semicolon to the solution from the manual, otherwise an empty line is required.

Android findViewById() in Custom View

If it's fixed layout you can do like that:

public void onClick(View v) {
   ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
   EditText firstName = (EditText) parent.findViewById(R.id.display_name);
   firstName.setText("Some Text");
}

If you want find the EditText in flexible layout, I will help you later. Hope this help.

Using Regular Expressions to Extract a Value in Java

Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)");
Matcher m = p.matcher("this is your number:1234 thank you");
if (m.find()) {
    String someNumberStr = m.group(2);
    int someNumberInt = Integer.parseInt(someNumberStr);
}

Querying DynamoDB by date

You could make the Hash key something along the lines of a 'product category' id, then the range key as a combination of a timestamp with a unique id appended on the end. That way you know the hash key and can still query the date with greater than.

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 
ADD NewId INT IDENTITY (1, 1);

Update:

OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

Convert int to char in java

Nobody has answered the real "question" here: you ARE converting int to char correctly; in the ASCII table a decimal value of 01 is "start of heading", a non-printing character. Try looking up an ASCII table and converting an int value between 33 and 7E; that will give you characters to look at.

How to import existing Android project into Eclipse?

You can also use Make new > General > Project, then import the project to that project directory

Compile Views in ASP.NET MVC

I frankly would recommend the RazorGenerator nuget package. That way your views have a .designer.cs file generated when you save them and on top of getting compile time errors for you views, they are also precompiled into the assembly (= faster warmup) and Resharper provides some additional help as well.

To use this include the RazorGenerator nuget package in you ASP.NET MVC project and install the "Razor Generator" extension under item under Tools ? Extensions and Updates.

We use this and the overhead per compile with this approach is much less. On top of this I would probably recommend .NET Demon by RedGate which further reduces compile time impact substantially.

Hope this helps.

Android Layout Right Align

You can do all that by using just one RelativeLayout (which, btw, don't need android:orientation parameter). So, instead of having a LinearLayout, containing a bunch of stuff, you can do something like:

<RelativeLayout>
    <ImageButton
        android:layout_width="wrap_content"
        android:id="@+id/the_first_one"
        android:layout_alignParentLeft="true"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_toRightOf="@+id/the_first_one"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

As you noticed, there are some XML parameters missing. I was just showing the basic parameters you had to put. You can complete the rest.

RuntimeError on windows trying python multiprocessing

In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.

TypeScript and field initializers

Here's a solution that:

  • doesn't force you to make all fields optional (unlike Partial<...>)
  • differentiates between class methods and fields of function type (unlike the OnlyData<...> solution)
  • provides a nice structure by defining a Params interface
  • doesn't need to repeat variable names & types more than once

The only drawback is that it looks more complicated at first.


// Define all fields here
interface PersonParams {
  id: string
  name?: string
  coolCallback: () => string
}

// extend the params interface with an interface that has
// the same class name as the target class
// (if you omit the Params interface, you will have to redeclare
// all variables in the Person class)
interface Person extends PersonParams { }

// merge the Person interface with Person class (no need to repeat params)
// person will have all fields of PersonParams
// (yes, this is valid TS)
class Person {
  constructor(params: PersonParams) {
    // could also do Object.assign(this, params);

    this.id = params.id;
    this.name = params.name;

    // intellisence will expect params
    // to have `coolCallback` but not `sayHello`
    this.coolCallback = params.coolCallback;
  }

  // compatible with functions
  sayHello() {
    console.log(`Hi ${this.name}!`);
  }
}

// you can only export on another line (not `export default class...`)
export default Person;

how to get current datetime in SQL?

SYSDATETIME() 2007-04-30 13:10:02.0474381
SYSDATETIMEOFFSET()2007-04-30 13:10:02.0474381 -07:00
SYSUTCDATETIME() 2007-04-30 20:10:02.0474381
CURRENT_TIMESTAMP 2007-04-30 13:10:02.047 +
GETDATE() 2007-04-30 13:10:02.047 
GETUTCDATE() 2007-04-30 20:10:02.047

I guess NOW() doesn't work sometime and gives error 'NOW' is not a recognized built-in function name.

Hope it helps!!! Thank You. https://docs.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

Why is lock(this) {...} bad?

Because if people can get at your object instance (ie: your this) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on this internally, so this may cause problems (possibly a deadlock)

In addition to this, it's also bad practice, because it's locking "too much"

For example, you might have a member variable of List<int>, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.

Generate random numbers uniformly over an entire range

If you are concerned about randomness and not about speed, you should use a secure random number generation method. There are several ways to do this... The easiest one being to use OpenSSL's Random Number Generator.

You can also write your own using an encryption algorithm (like AES). By picking a seed and an IV and then continuously re-encrypting the output of the encryption function. Using OpenSSL is easier, but less manly.

Return multiple values to a method caller

In C#7 There is a new Tuple syntax:

static (string foo, int bar) GetTuple()
{
    return ("hello", 5);
}

You can return this as a record:

var result = GetTuple();
var foo = result.foo
// foo == "hello"

You can also use the new deconstructor syntax:

(string foo) = GetTuple();
// foo == "hello"

Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a Tuple<string, int> (as per the accepted answer) with Item1 and Item2 instead of foo and bar. That means that serialisation (or deserialisation) will use those property names instead.

So, for serialisation declare a record class and return that instead.

Also new in C#7 is an improved syntax for out parameters. You can now declare the out inline, which is better suited in some contexts:

if(int.TryParse("123", out int result)) {
    // Do something with result
}

However, mostly you'll use this in .NET's own libraries, rather than in you own functions.

Mocking methods of local scope objects with Mockito

If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).

With this, amongst many other things, you can mock the construction of new objects in a very easy way.

Problems installing the devtools package

Centos 6.8

this work like charm for me

  1. install libcurl $yum -y install libcurl libcurl-devel
  2. restart R Software $rstudio-server verify-installation

Why an interface can not implement another interface?

However, interface is 100% abstract class and abstract class can implements interface(100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?

This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.

In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.

As others state, there are good reasons for choosing "extends" over "implements."

JavaScript Chart.js - Custom data formatting to display on tooltip

In chart.js 2.1.6, I did something like this (in typescript):

  let that = this;
  options = {
    legend: {
      display: false,
      responsive: false
    },
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          let account: Account = that.accounts[tooltipItem.index];
          return account.accountNumber+":"+account.balance+"€";
        }
      }
    }
  }

How to list all `env` properties within jenkins pipeline job?

You can get all variables from your jenkins instance. Just visit:

  • ${jenkins_host}/env-vars.html
  • ${jenkins_host}/pipeline-syntax/globals

Access IP Camera in Python OpenCV

You can access most IP cameras using the method below.

import cv2 

# insert the HTTP(S)/RSTP feed from the camera
url = "http://username:password@your_ip:your_port/tmpfs/auto.jpg"

# open the feed
cap = cv2.VideoCapture(url)

while True:
    # read next frame
     ret, frame = cap.read()
    
    # show frame to user
     cv2.imshow('frame', frame)
    
    # if user presses q quit program
     if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# close the connection and close all windows
cap.release()
cv2.destroyAllWindows()

Passing arguments to angularjs filters

Actually there is another (maybe better solution) where you can use the angular's native 'filter' filter and still pass arguments to your custom filter.

Consider the following code:

<div ng-repeat="group in groups">
    <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
        <span>{{friend.name}}</span>
    <li>
</div>

To make this work you just define your filter as the following:

$scope.weDontLike = function(name) {
    return function(friend) {
        return friend.name != name;
    }
}

As you can see here, weDontLike actually returns another function which has your parameter in its scope as well as the original item coming from the filter.

It took me 2 days to realise you can do this, haven't seen this solution anywhere yet.

Checkout Reverse polarity of an angular.js filter to see how you can use this for other useful operations with filter.

Why must wait() always be in synchronized block

directly from this java oracle tutorial:

When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

How to get a Static property with Reflection

Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo - where BindingFlags is not available reliably (depending on target framework).

In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:

IEnumerable<PropertyInfo> props = 
  type.GetTypeInfo().DeclaredProperties.Where(p => 
    (p.GetMethod != null && p.GetMethod.IsStatic) ||
    (p.SetMethod != null && p.SetMethod.IsStatic));

Caters for both read-only or write-only properties (despite write-only being a terrible idea).

The DeclaredProperties member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:

var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);

There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

I resolved my problem with this one liner

npm cache clean --force

It works like a charm all the time. I love one liners. Note: since its a clean install, I had no concerns emptying npm cache.

How to escape the % (percent) sign in C's printf?

Like this:

printf("hello%%");
//-----------^^ inside printf, use two percent signs together

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

Change UITextField and UITextView Cursor / Caret Color

Note: This answer is out of date and should be used for pre-iOS 7 development only. See other answers for a 1 line solution using the appearance proxy in iOS 7.

I arrived at this question after I faced the same problem in a project I was working on.

I managed to create a solution that will be accepted by the AppStore review team as it does not use any existing Private APIs.

I have created a control called DGTextField that extends UITextField.

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

Use:

  • System.setProperty("jsse.enableSNIExtension", "false");
  • Restart your Tomcat (important)

How to get next/previous record in MySQL?

There's another trick you can use to show columns from previous rows, using any ordering you want, using a variable similar to the @row trick:

SELECT @prev_col_a, @prev_col_b, @prev_col_c,
   @prev_col_a := col_a AS col_a,
   @prev_col_b := col_b AS col_b,
   @prev_col_c := col_c AS col_c
FROM table, (SELECT @prev_col_a := NULL, @prev_col_b := NULL, @prev_col_c := NULL) prv
ORDER BY whatever

Apparently, the select columns are evaluated in order, so this will first select the saved variables, and then update the variables to the new row (selecting them in the process).

NB: I'm not sure that this is defined behaviour, but I've used it and it works.

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

Add "barryvdh/laravel-cors": "^0.7.3" at the end of require array inside composer.json

Save composer.json and run composer update

You are done !

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.

In short, you need to install the prerequisites of KB2999226.

In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:

Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.

After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.

Pointer arithmetic for void pointer in C

The C standard does not allow void pointer arithmetic. However, GNU C is allowed by considering the size of void is 1.

C11 standard §6.2.5

Paragraph - 19

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

Following program is working fine in GCC compiler.

#include<stdio.h>

int main()
{
    int arr[2] = {1, 2};
    void *ptr = &arr;
    ptr = ptr + sizeof(int);
    printf("%d\n", *(int *)ptr);
    return 0;
}

May be other compilers generate an error.

Accessing Google Spreadsheets with C# using Google Data API

According to the .NET user guide:

Download the .NET client library:

Add these using statements:

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;

Authenticate:

SpreadsheetsService myService = new SpreadsheetsService("exampleCo-exampleApp-1");
myService.setUserCredentials("[email protected]", "mypassword");

Get a list of spreadsheets:

SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = myService.Query(query);

Console.WriteLine("Your spreadsheets: ");
foreach (SpreadsheetEntry entry in feed.Entries)
{
    Console.WriteLine(entry.Title.Text);
}

Given a SpreadsheetEntry you've already retrieved, you can get a list of all worksheets in this spreadsheet as follows:

AtomLink link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);

WorksheetQuery query = new WorksheetQuery(link.HRef.ToString());
WorksheetFeed feed = service.Query(query);

foreach (WorksheetEntry worksheet in feed.Entries)
{
    Console.WriteLine(worksheet.Title.Text);
}

And get a cell based feed:

AtomLink cellFeedLink = worksheetentry.Links.FindService(GDataSpreadsheetsNameTable.CellRel, null);

CellQuery query = new CellQuery(cellFeedLink.HRef.ToString());
CellFeed feed = service.Query(query);

Console.WriteLine("Cells in this worksheet:");
foreach (CellEntry curCell in feed.Entries)
{
    Console.WriteLine("Row {0}, column {1}: {2}", curCell.Cell.Row,
        curCell.Cell.Column, curCell.Cell.Value);
}

How do I autoindent in Netbeans?

Open Tools -> Options -> Keymap, then look for the action called "Re-indent current line or selection" and set whatever shortcut you want.

HTML / CSS table with GRIDLINES

<table border="1"></table>

should do the trick.

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

Isn't this maybe the most elegant?

REPLACE 
INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) 
VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')

see: http://dev.mysql.com/doc/refman/5.7/en/replace.html

How do you make sure email you send programmatically is not automatically marked as spam?

I always use: https://www.mail-tester.com/

It gives me feedback on the technical part of sending an e-mail. Like SPF-records, DKIM, Spamassassin score and so on. Even though I know what is required, I continuously make errors and mail-tester.com makes it easy to figure out what could be wrong.

How to load html string in a webview?

To load your data in WebView. Call loadData() method of WebView

wv.loadData(yourData, "text/html", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

[Edit 1]

You should add -- \ -- before -- " -- for example --> name=\"spanish press\"

below string worked for me

String webData =  "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
 "<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Print a list of all installed node.js modules

Use npm ls (there is even json output)

From the script:

test.js:

function npmls(cb) {
  require('child_process').exec('npm ls --json', function(err, stdout, stderr) {
    if (err) return cb(err)
    cb(null, JSON.parse(stdout));
  });
}
npmls(console.log);

run:

> node test.js
null { name: 'x11', version: '0.0.11' }

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

Whoops, looks like something went wrong. Laravel 5.0

  • Give write permission to storage and bootstrap/cache directories
  • Rename .env.example file to .env
  • If you get "RuntimeException... No supported encrypter found. The cipher and / or key length are invalid." error, stop the application and generate key from command line "php artisan key:generate"
  • If your get "OpenSSL extension is required" error, enable the openssl extension by opening php.ini in php installation folder and uncommenting the line extension=php_openssl.dll by removing the semicolon at the beginning

Is it possible to output a SELECT statement from a PL/SQL block?

if you want see select query output in pl/sql you need to use a explicit cursor. Which will hold active data set and by fetching each row at a time it will show all the record from active data set as long as it fetches record from data set by iterating in loop. This data will not be generated in tabular format this result will be in plain text format. Hope this will be helpful. For any other query you may ask....

set serveroutput on;
declare
cursor c1 is
   select foo, bar from foobar;
begin
  for i in c1 loop
    dbms_output.put_line(i.foo || ' ' || i.bar);
  end loop;
end;

Prevent cell numbers from incrementing in a formula in Excel

Highlight "B1" and press F4. This will lock the cell.

Now you can drag it around and it will not change. The principle is simple. It adds a dollar sign before both coordinates. A dollar sign in front of a coordinate will lock it when you copy the formula around. You can have partially locked coordinates and fully locked coordinates.

BOOLEAN or TINYINT confusion

As of MySql 5.1 version reference

BIT(M) =  approximately (M+7)/8 bytes, 
BIT(1) =  (1+7)/8 = 1 bytes (8 bits)

=========================================================================

TINYINT(1) take 8 bits.

https://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html#data-types-storage-reqs-numeric

Iterate over object in Angular

I have been tearing my hair out with trying to parse and use data returned form a JSON query/ api call. Im not sure exactly where i was going wrong, i feel like i have been circling the answer for days, chasing various error codes like:

"Cannot find 'iterableDiff' pipe supporting object"

"Generic TYpe Array requires one argument(s)"

JSON parsing Errors, and im sure others

Im assuming i just had the wrong combination of fixes.

So here's a bit of a summary of gotchas and things to look for.

Firstly check the result of your api calls, your results may be in the form of an object, an array, or an array of objects.

i wont go into it too much, suffice to say the OP's original Error of not being iterable is generally caused by you trying to iterate an object, not an Array.

Heres some of my debugging results showing variables of both arrays and objects

So as we generally would like to iterate over our JSON result we need to ensure it is in the form of an Array. I tried numerous examples, and perhaps knowing what i know now some of those would in fact work, but the approach i went with was indeed to implement a pipe and the code i used was that the posted by t.888

   transform(obj: {[key: string]: any}, arg: string) {
if (!obj)
        return undefined;

return arg === 'keyval' ?
    Object.keys(obj).map((key) => ({ 'key': key, 'value': obj[key] })) :
  arg === 'key' ?
    Object.keys(obj) :
  arg === 'value' ?
    Object.keys(obj).map(key => obj[key]) :
  null;

Honestly i think one of the things that was getting me was the lack of error handling, by adding the 'return undefined' call i believe we are now allowing for non expected data to be sent to the pipe, which obviously was occurring in my case.

if you don't want to deal with argument to the pipe (and look i don't think it's necessary in most cases) you can just return the following

       if (!obj)
          return undefined;
       return Object.keys(obj);

Some Notes on creating your pipe and page or component that uses that pipe

is i was receiving errors about ‘name_of_my_pipe’ not being found

Use the ‘ionic generate pipe’ command from the CLI to ensure the pipe modules.ts are created and referenced correctly. ensure you add the following to the mypage.module.ts page.

import { PipesModule } from ‘…/…/pipes/pipes.module’;

(not sure if this changes if you also have your own custom_module, you may also need to add it to the custommodule.module.ts)

if you used the 'ionic generate page' command to make your page, but decide to use that page as your main page, remember to remove the page reference from app.module.ts (here's another answer i posted dealing with that https://forum.ionicframework.com/t/solved-pipe-not-found-in-custom-component/95179/13?u=dreaser

In my searching for answers there where a number of ways to display the data in the html file, and i don't understand enough to explain the differences. You may find it better to use one over another in certain scenarios.

            <ion-item *ngFor="let myPost of posts">
                  <img src="https://somwhereOnTheInternet/{{myPost.ImageUrl}}"/>
                  <img src="https://somwhereOnTheInternet/{{posts[myPost].ImageUrl}}"/>
                  <img [src]="'https://somwhereOnTheInternet/' + myPost.ImageUrl" />
            </ion-item>

However what worked that allowed me to display both the value and the key was the following:

    <ion-list>  
      <ion-item *ngFor="let myPost of posts  | name_of_pip:'optional_Str_Varible'">

        <h2>Key Value = {{posts[myPost]}} 

        <h2>Key Name = {{myPost}} </h2>

      </ion-item>
   </ion-list>  

to make the API call it looks like you need to import HttpModule into app.module.ts

import { HttpModule } from '@angular/http';
 .
 .  
 imports: [
BrowserModule,
HttpModule,

and you need Http in the page you make the call from

import {Http} from '@angular/http';

When making the API call you seem to be able to get to the children data (the objects or arrays within the array) 2 different ways, either seem to work

either during the call

this.http.get('https://SomeWebsiteWithAPI').map(res => res.json().anyChildren.OrSubChildren).subscribe(
        myData => {

or when you assign the data to your local variable

posts: Array<String>;    
this.posts = myData['anyChildren'];

(not sure if that variable needs to be an Array String, but thats what i have it at now. It may work as a more generic variable)

And final note, it was not necessary to use the inbuilt JSON library however you may find these 2 calls handy for converting from an object to a string and vica versa

        var stringifiedData = JSON.stringify(this.movies);                  
        console.log("**mResults in Stringify");
        console.log(stringifiedData);

        var mResults = JSON.parse(<string>stringifiedData);
        console.log("**mResults in a JSON");
        console.log(mResults);

I hope this compilation of info helps someone out.

How to convert a string to an integer in JavaScript?

You can use plus. For example:

var personAge = '24';
var personAge1 = (+personAge)

then you can see the new variable's type bytypeof personAge1 ; which is number.

Xcode build failure "Undefined symbols for architecture x86_64"

I have also seen this error on Xcode 7.2 when the derived data becomes corrupted (in my case I interrupted a build and suspect that was the root cause).

So if the other solutions (notably Chris's and BraveS's which I suspect are more likely) do not fit your problem try deleting derived data (Select: Window / Projects / Derived Data -> Delete) and re-building.

(Added for reference by others - I know the original question has been answered correctly).

Interfaces — What's the point?

class Program {
    static void Main(string[] args) {
        IMachine machine = new Machine();
        machine.Run();
        Console.ReadKey();
    }

}

class Machine : IMachine {
    private void Run() {
        Console.WriteLine("Running...");
    }
    void IMachine.Run() => Run();
}

interface IMachine
{
    void Run();
}

Let me describe this by a different perspective. Let’s create a story according to the example which i have shown above;

Program, Machine and IMachine are the actors of our story. Program wants to run but it has not that ability and Machine knows how to run. Machine and IMachine are best friends but Program is not on speaking terms with Machine. So Program and IMachine make a deal and decided that IMachine will tell to Program how to run by looking Machine(like a reflector).

And Program learns how to run by help of IMachine.

Interface provides communication and developing loosely coupled projects.

PS: I’ve the method of concrete class as private. My aim in here is to achieve loosely coupled by preventing accessing concrete class properties and methods, and left only allowing way to reach them via interfaces. (So i defined interfaces’ methods explicitily).

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

How to make IPython notebook matplotlib plot inline

If your matplotlib version is above 1.4, it is also possible to use

IPython 3.x and above

%matplotlib notebook

import matplotlib.pyplot as plt

older versions

%matplotlib nbagg

import matplotlib.pyplot as plt

Both will activate the nbagg backend, which enables interactivity.

Example plot with the nbagg backend

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

In MVC5.2, add Date.cshtml to folder ~/Views/Shared/EditorTemplates:

@model DateTime?
@{
    IDictionary<string, object> htmlAttributes;
    object objAttributes;
    if (ViewData.TryGetValue("htmlAttributes", out objAttributes))
    {
        htmlAttributes = objAttributes as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(objAttributes);
    }
    else
    {
        htmlAttributes = new RouteValueDictionary();
    }
    htmlAttributes.Add("type", "date");
    String format = (Request.UserAgent != null && Request.UserAgent.Contains("Chrome")) ? "{0:yyyy-MM-dd}" : "{0:d}";
    @Html.TextBox("", Model, format, htmlAttributes)
}

How to open a file for both reading and writing?

I have tried something like this and it works as expected:

f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()

Where:

f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.

And:

f.write(string) writes the contents of string to the file, returning None.

Also if you open Python tutorial about reading and writing files you will find that:

'r+' opens the file for both reading and writing.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.

MySQL FULL JOIN?

Full join in mysql :(left union right) or (right unoin left)

 SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    left JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

    Union

    SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    Right JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

How does one capture a Mac's command key via JavaScript?

Here is how I did it in AngularJS

app = angular.module('MM_Graph')

class Keyboard
  constructor: ($injector)->
    @.$injector  = $injector
    @.$window    = @.$injector.get('$window')                             # get reference to $window and $rootScope objects
    @.$rootScope = @.$injector.get('$rootScope')

  on_Key_Down:($event)=>
    @.$rootScope.$broadcast 'keydown', $event                             # broadcast a global keydown event

    if $event.code is 'KeyS' and ($event.ctrlKey or $event.metaKey)       # detect S key pressed and either OSX Command or Window's Control keys pressed
      @.$rootScope.$broadcast '', $event                                  # broadcast keyup_CtrS event
      #$event.preventDefault()                                             # this should be used by the event listeners to prevent default browser behaviour

  setup_Hooks: ()=>
    angular.element(@.$window).bind "keydown", @.on_Key_Down              # hook keydown event in window (only called once per app load)
    @

app.service 'keyboard', ($injector)=>
  return new Keyboard($injector).setup_Hooks()

VBA copy cells value and format

Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.

Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...

Code:
Cells(1, 3).Copy
    Cells(1, 1).PasteSpecial (xlPasteFormats)
    Application.CutCopyMode = False

What does <![CDATA[]]> in XML mean?

From Wikipedia:

[In] an XML document or external parsed entity, a CDATA section is a section of element content that is marked for the parser to interpret as only character data, not markup.

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

Thus: text inside CDATA is seen by the parser but only as characters not as XML nodes.

Can I override and overload static methods in Java?

Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

Undo a particular commit in Git that's been pushed to remote repos

Because it has already been pushed, you shouldn't directly manipulate history. git revert will revert specific changes from a commit using a new commit, so as to not manipulate commit history.

Why doesn't Java support unsigned ints?

I know this post is too old; however for your interest, in Java 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer and static methods like compareUnsigned(), divideUnsigned() etc. have been added to the Integer class to support the arithmetic operations for unsigned integers.

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

How to change Bootstrap's global default font size?

Bootstrap uses the variable:

$font-size-base: 1rem; // Assumes the browser default, typically 16px

I don't recommend mucking with this, but you can. Best practice is to override the browser default base font size with:

html {
  font-size: 14px;
}

Bootstrap will then take that value and use it via rems to set values for all kinds of things.

jQuery: How to get to a particular child of a parent?

If I understood your problem correctly, $(this).parents('.box').children('.something1') Is this what you are looking for?

TimeStamp on file name using PowerShell

I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:

wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx

The magic code is just this part:

$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Use px-0 on the container and no-gutters on the row to remove the paddings.

Quoting from Bootstrap 4 - Grid system:

Rows are wrappers for columns. Each column has horizontal padding (called a gutter) for controlling the space between them. This padding is then counteracted on the rows with negative margins. This way, all the content in your columns is visually aligned down the left side.

Columns have horizontal padding to create the gutters between individual columns, however, you can remove the margin from rows and padding from columns with .no-gutters on the .row.

Following is a live demo:

_x000D_
_x000D_
h1 {
  background-color: tomato;
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />

<div class="container-fluid" id="div1">
  <div class="row">
    <div class="col">
        <h1>With padding : (</h1>
    </div>
  </div>
</div>

<div class="container-fluid px-0" id="div1">
  <div class="row no-gutters">
    <div class="col">
        <h1>No padding : > </h1>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

The reason this works is that container-fluid and col both have following padding:

padding-right: 15px;
padding-left: 15px;

px-0 can remove the horizontal padding from container-fluid and no-gutters can remove the padding from col.

Python regex for integer?

You are apparently using Django.

You are probably better off just using models.IntegerField() instead of models.TextField(). Not only will it do the check for you, but it will give you the error message translated in several langs, and it will cast the value from it's type in the database to the type in your Python code transparently.

Difference between binary semaphore and mutex

The Toilet example is an enjoyable analogy:

Mutex:

Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library

Disabling Chrome cache for website development

I use (in windows), ctrl + shift + delete and when the chrome dialog comes up, press enter key. This can be configured with what needs to be cleared each time you execute this sequence. No need to have dev. tools open in this case.

How to put php inside JavaScript?

Try this:

<?php $htmlString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">  
      // notice the quotes around the ?php tag         
      var htmlString="<?php echo $htmlString; ?>";
      alert(htmlString);
    </script>
  </body>
</html>

When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.

Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.

JPA entity without id

If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.

Spring Data JPA Update @Query not updating?

The EntityManager doesn't flush change automatically by default. You should use the following option with your statement of query:

@Modifying(clearAutomatically = true)
@Query("update RssFeedEntry feedEntry set feedEntry.read =:isRead where feedEntry.id =:entryId")
void markEntryAsRead(@Param("entryId") Long rssFeedEntryId, @Param("isRead") boolean isRead);

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

Jquery UI tooltip does not support html content

To expand on @Andrew Whitaker's answer above, you can convert your tooltip to html entities within the title tag so as to avoid putting raw html directly in your attributes:

_x000D_
_x000D_
$('div').tooltip({_x000D_
    content: function () {_x000D_
        return $(this).prop('title');_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>_x000D_
<div class="tooltip" title="&lt;div&gt;check out these kool &lt;i&gt;italics&lt;/i&gt; and this &lt;span style=&quot;color:red&quot;&gt;red text&lt;/span&gt;&lt;/div&gt;">Hover Here</div>
_x000D_
_x000D_
_x000D_

More often than not, the tooltip is stored in a php variable anyway so you'd only need:

<div title="<?php echo htmlentities($tooltip); ?>">Hover Here</div>

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Django TemplateDoesNotExist?

I had an embarrassing problem...

I got this error because I was rushing and forgot to put the app in INSTALLED_APPS. You would think Django would raise a more descriptive error.

How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html

The below code displays a heatmap on right and an Image on left.

#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2) 
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()

Output image

Convert a bitmap into a byte array

You can also just Marshal.Copy the bitmap data. No intermediary memorystream etc. and a fast memory copy. This should work on both 24-bit and 32-bit bitmaps.

public static byte[] BitmapToByteArray(Bitmap bitmap)
{

    BitmapData bmpdata = null;

    try
    {
        bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
        int numbytes = bmpdata.Stride * bitmap.Height;
        byte[] bytedata = new byte[numbytes];
        IntPtr ptr = bmpdata.Scan0;

        Marshal.Copy(ptr, bytedata, 0, numbytes);

        return bytedata;
    }
    finally
    {
        if (bmpdata != null)
            bitmap.UnlockBits(bmpdata);
    }

}

.

mysql server port number

This is a PDO-only visualization, as the mysql_* library is deprecated.

<?php
    // Begin Vault (this is in a vault, not actually hard-coded)
    $host="hostname";
    $username="GuySmiley";
    $password="thePassword";
    $dbname="dbname";
    $port="3306";
    // End Vault

    try {
        $dbh = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8", $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "I am connected.<br/>";

        // ... continue with your code

        // PDO closes connection at end of script
    } catch (PDOException $e) {
        echo 'PDO Exception: ' . $e->getMessage();
        exit();
    }
?>

Note that this OP Question appeared not to be about port numbers afterall. If you are using the default port of 3306 always, then consider removing it from the uri, that is, remove the port=$port; part.

If you often change ports, consider the above port usage for more maintainability having changes made to the $port variable.

Some likely errors returned from above:

PDO Exception: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
PDO Exception: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.

In the below error, we are at least getting closer, after changing our connect information:

PDO Exception: SQLSTATE[HY000] [1045] Access denied for user 'GuySmiley'@'localhost' (using password: YES)

After further changes, we are really close now, but not quite:

PDO Exception: SQLSTATE[HY000] [1049] Unknown database 'mustard'

From the Manual on PDO Connections:

How do I add an image to a JButton

I think that your problem is in the location of the image. You shall place it in your source, and then use it like this:

  JButton button = new JButton();
  try {
    Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
    button.setIcon(new ImageIcon(img));
  } catch (Exception ex) {
    System.out.println(ex);
  }

In this example, it is assumed that image is in src/resources/ folder.

moment.js 24h format

moment("01:15:00 PM", "h:mm:ss A").format("HH:mm:ss")
**o/p: 13:15:00 **

it will give convert 24 hrs format to 12 hrs format.

Using Java with Microsoft Visual Studio 2012

If you're proficient in C# and Visual Studio, you might try IKVM. It's not exactly what you were asking for, but will certainly help with bridging the gap by allowing you to call into Java libraries from C# and vise versa. You can use it in Visual Studio, but it also has first class support in MonoDevelop.

SQL Server 2005 Using DateAdd to add a day to a date

Try following code will Add one day to current date

select DateAdd(day, 1, GetDate())

And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function

What's the difference between a web site and a web application?

Both function and perform similarly, but still differ in following ways.

Web application:

  1. We can't include C# and VB page in single web application.

  2. We can set up dependencies between multiple projects.

  3. Can not edit individual files after deployment without recompiling.

  4. Right choice for enterprise environments where multiple developers work unitedly for creating,testing and deployment.

Web site:

  1. Can mix VB and C# page in single website.
  2. Can not establish dependencies.
  3. Edit individual files after deployment.
  4. Right choice when one developer will responsible for creating and managing entire website.

HTTP test server accepting GET/POST requests

There is http://ptsv2.com/

"Here you will find a server which receives any POST you wish to give it and stores the contents for you to review."

jQuery append and remove dynamic table row

You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.

Also, move the .on() outside of the .click() function, as you only need to set it once.

http://jsfiddle.net/samliew/3AJcj/2/

$(document).ready(function(){
    $(".addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });
    $("#customFields").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});

Extracting numbers from vectors of strings

Extract numbers from any string at beginning position.

x <- gregexpr("^[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

Extract numbers from any string INDEPENDENT of position.

x <- gregexpr("[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

fill an array in C#

Write yourself an extension method

public static class ArrayExtensions {
    public static void Fill<T>(this T[] originalArray, T with) {
        for(int i = 0; i < originalArray.Length; i++){
            originalArray[i] = with;
        }
    }  
}

and use it like

int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);

will fill all the elements with 13

Displaying a message in iOS which has the same functionality as Toast in Android

If you want one with iOS Style, download this framework from Github

iOS Toast Alert View Framework

This examples work on you UIViewController, once you imported the Framework.

Example 1:

//Manual 
let tav = ToastAlertView()
tav.message = "Hey!"
tav.image = UIImage(named: "img1")!
tav.show()
//tav.dismiss() to Hide

Example 2:

//Toast Alert View with Time Dissmis Only
self.showToastAlert("5 Seconds",
                image: UIImage(named: "img1")!,
                hideWithTap: false,
                hideWithTime: true,
                hideTime: 5.0)

Final:

Toast Alert View Image Example

How to define an empty object in PHP

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)

Call An Asynchronous Javascript Function Synchronously

The idea that you hope to achieve can be made possible if you tweak the requirement a little bit

The below code is possible if your runtime supports the ES6 specification.

More about async functions

async function myAsynchronousCall(param1) {
    // logic for myAsynchronous call
    return d;
}

function doSomething() {

  var data = await myAsynchronousCall(param1); //'blocks' here until the async call is finished
  return data;
}

How to change active class while click to another link in bootstrap use jquery?

I had the same issue before. Try this answer here, it works on my site.

$(function(){
  var current_page_URL = location.href;
  $( "a" ).each(function() {
     if ($(this).attr("href") !== "#") {
       var target_URL = $(this).prop("href");
       if (target_URL == current_page_URL) {
          $('nav a').parents('li, ul').removeClass('active');
          $(this).parent('li').addClass('active');
          return false;
       }
     }
  });
});

Source: It was original posted here how to set active class to nav menu from twitter bootstrap

Which SchemaType in Mongoose is Best for Timestamp?

new mongoose.Schema({ description: { type: String, required: true, trim: true }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }, { timestamps: true });

Is there a format code shortcut for Visual Studio?

Select all text in the document and press Ctrl + E + D.

React - Display loading screen while DOM is rendering?

You can easily do that by using lazy loading in react. For that you have to use lazy and suspense from react like that.

import React, { lazy, Suspense } from 'react';

const loadable = (importFunc, { fallback = null } = { fallback: null }) => {
  const LazyComponent = lazy(importFunc);

  return props => (
    <Suspense fallback={fallback}>
      <LazyComponent {...props} />
    </Suspense>
  );
};

export default loadable;

After that export your components like this.

export const TeacherTable = loadable(() =>
  import ('./MainTables/TeacherTable'), {
    fallback: <Loading />,
  });

And then in your routes file use it like this.

 <Route exact path="/app/view/teachers" component={TeacherTable} />

Thats it now you are good to go everytime your DOM is rendering your Loading compnent will be displayed as we have specified in the fallback property above. Just make sure that you do any ajax request only in componentDidMount()

How to enable loglevel debug on Apache2 server

Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.

For older version apache:

For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:

RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"

Remove leading comma from a string

Assuming the string is called myStr:

// Strip start and end quotation mark and possible initial comma
myStr=myStr.replace(/^,?'/,'').replace(/'$/,'');

// Split stripping quotations
myArray=myStr.split("','");

Note that if a string can be missing in the list without even having its quotation marks present and you want an empty spot in the corresponding location in the array, you'll need to write the splitting manually for a robust solution.

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

Add an element to an array in Swift

To add to the solutions suggesting append, it's useful to know that this is an amortised constant time operation in many cases:

Complexity: Amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.

I'm looking for a cons like operator for Swift. It should return a new immutable array with the element tacked on the end, in constant time, without changing the original array. I've not yet found a standard function that does this. I'll try to remember to report back if I find one!

Calculate row means on subset of columns

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
  ID    Means
1  A 3.666667
2  B 4.333333
3  C 3.333333
4  D 4.666667
5  E 4.333333

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

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

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

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

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

ng serve not detecting file changes automatically

Because of, The system that detects changes can't handle so much watches by default.

And the solution is to change the amount of watches it can handle (the maximum amount of files that will be in the project) you must run this command:

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches

The problem with inotify is reseting this counter every time you restart your computer.

Set Background color programmatically

This must work:

you must use getResources().getColor(R.color.WHITE) to get the color resource, which you must add in the colors.xml resource file

View someView = findViewById(R.id.screen);

someView.setBackgroundColor(getResources().getColor(R.color.WHITE));

Module AppRegistry is not registered callable module (calling runApplication)

One of the libraries has not been linked. To check, just comment out in the package.json one by one the latest libraries added.

yarn remove libraryName.

Then run the app with xcode and puf !

get keys of json-object in JavaScript

The working code

_x000D_
_x000D_
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
    if(jsonData.hasOwnProperty(obj)){_x000D_
    for(var prop in jsonData[obj]){_x000D_
        if(jsonData[obj].hasOwnProperty(prop)){_x000D_
           alert(prop + ':' + jsonData[obj][prop]);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_

C++ Array of pointers: delete or delete []?

The second one is correct under the circumstances (well, the least wrong, anyway).

Edit: "least wrong", as in the original code shows no good reason to be using new or delete in the first place, so you should probably just use:

std::vector<Monster> monsters;

The result will be simpler code and cleaner separation of responsibilities.

Pull new updates from original GitHub repository into forked GitHub repository

If you're using the GitHub desktop application, there is a synchronise button on the top right corner. Click on it then Update from <original repo> near top left.

If there are no changes to be synchronised, this will be inactive.

Here are some screenshots to make this easy.

Override hosts variable of Ansible playbook from the command line

Here's a cool solution I came up to safely specify hosts via the --limit option. In this example, the play will end if the playbook was executed without any hosts specified via the --limit option.

This was tested on Ansible version 2.7.10

---
- name: Playbook will fail if hosts not specified via --limit option.
  # Hosts must be set via limit. 
  hosts: "{{ play_hosts }}"
  connection: local
  gather_facts: false
  tasks:
  - set_fact:
      inventory_hosts: []
  - set_fact:
      inventory_hosts: "{{inventory_hosts + [item]}}"
    with_items: "{{hostvars.keys()|list}}"

  - meta: end_play
    when: "(play_hosts|length) == (inventory_hosts|length)"

  - debug:
      msg: "About to execute tasks/roles for {{inventory_hostname}}"

Create an empty object in JavaScript with {} or new Object()?

OK, there are just 2 different ways to do the same thing! One called object literal and the other one is a function constructor!

But read on, there are couple of things I'd like to share:

Using {} makes your code more readable, while creating instances of Object or other built-in functions not recommended...

Also, Object function gets parameters as it's a function, like Object(params)... but {} is pure way to start an object in JavaScript...

Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...

While Object in Javascript can be almost anything, {} only points to javascript objects, for the test how it works, do below in your javascript code or console:

var n = new Object(1); //Number {[[PrimitiveValue]]: 1}

Surprisingly, it's creating a Number!

var a = new Object([1,2,3]); //[1, 2, 3]

And this is creating a Array!

var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}

and this weird result for String!

So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {} is better in my experience!

Can RDP clients launch remote applications and not desktops

This is called RemoteApp. To use it you need to install Terminal Services, which is now called Remote Desktop Services.

https://social.technet.microsoft.com/wiki/contents/articles/10817.publishing-remoteapps-in-windows-server-2012.aspx

Can I call a constructor from another constructor (do constructor chaining) in C++?

In Visual C++ you can also use this notation inside constructor: this->Classname::Classname(parameters of another constructor). See an example below:

class Vertex
{
 private:
  int x, y;
 public:
  Vertex(int xCoo, int yCoo): x(xCoo), y(yCoo) {}
  Vertex()
  {
   this->Vertex::Vertex(-1, -1);
  }
};

I don't know whether it works somewhere else, I only tested it in Visual C++ 2003 and 2008. You may also call several constructors this way, I suppose, just like in Java and C#.

P.S.: Frankly, I was surprised that this was not mentioned earlier.

What does "for" attribute do in HTML <label> tag?

It labels whatever input is the parameter for the for attribute.

_x000D_
_x000D_
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
_x000D_
_x000D_

ASP.NET GridView RowIndex As CommandArgument

MSDN says that:

The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.

So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g.

protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
    int rowIndex = Convert.ToInt32( e.CommandArgument );
    ...
}

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

System32 is where Windows historically placed all 32bit DLLs, and System was for the 16bit DLLs. When microsoft created the 64 bit OS, everyone I know of expected the files to reside under System64, but Microsoft decided it made more sense to put 64bit files under System32. The only reasoning I have been able to find, is that they wanted everything that was 32bit to work in a 64bit Windows w/o having to change anything in the programs -- just recompile, and it's done. The way they solved this, so that 32bit applications could still run, was to create a 32bit windows subsystem called Windows32 On Windows64. As such, the acronym SysWOW64 was created for the System directory of the 32bit subsystem. The Sys is short for System, and WOW64 is short for Windows32OnWindows64.
Since windows 16 is already segregated from Windows 32, there was no need for a Windows 16 On Windows 64 equivalence. Within the 32bit subsystem, when a program goes to use files from the system32 directory, they actually get the files from the SysWOW64 directory. But the process is flawed.

It's a horrible design. And in my experience, I had to do a lot more changes for writing 64bit applications, that simply changing the System32 directory to read System64 would have been a very small change, and one that pre-compiler directives are intended to handle.

Full width image with fixed height

Set the height of the parent element, and give that the width. Then use a background image with the rule "background-size: cover"

    .parent {
       background-image: url(../img/team/bgteam.jpg);
       background-repeat: no-repeat;
       background-position: center center;
       -webkit-background-size: cover;
       background-size: cover;
    }

How do I convert two lists into a dictionary?

Solution as dictionary comprehension with enumerate:

dict = {item : values[index] for index, item in enumerate(keys)}

Solution as for loop with enumerate:

dict = {}
for index, item in enumerate(keys):
    dict[item] = values[index]

How do I select between the 1st day of the current month and current day in MySQL?

select * from table_name 
where `date` between curdate() - dayofmonth(curdate()) + 1
                 and curdate()

SQLFiddle example

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

Find string between two substrings

These solutions assume the start string and final string are different. Here is a solution I use for an entire file when the initial and final indicators are the same, assuming the entire file is read using readlines():

def extractstring(line,flag='$'):
    if flag in line: # $ is the flag
        dex1=line.index(flag)
        subline=line[dex1+1:-1] #leave out flag (+1) to end of line
        dex2=subline.index(flag)
        string=subline[0:dex2].strip() #does not include last flag, strip whitespace
    return(string)

Example:

lines=['asdf 1qr3 qtqay 45q at $A NEWT?$ asdfa afeasd',
    'afafoaltat $I GOT BETTER!$ derpity derp derp']
for line in lines:
    string=extractstring(line,flag='$')
    print(string)

Gives:

A NEWT?
I GOT BETTER!

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

How to use double or single brackets, parentheses, curly braces

Brackets

if [ CONDITION ]    Test construct  
if [[ CONDITION ]]  Extended test construct  
Array[1]=element1   Array initialization  
[a-z]               Range of characters within a Regular Expression
$[ expression ]     A non-standard & obsolete version of $(( expression )) [1]

[1] http://wiki.bash-hackers.org/scripting/obsolete

Curly Braces

${variable}                             Parameter substitution  
${!variable}                            Indirect variable reference  
{ command1; command2; . . . commandN; } Block of code  
{string1,string2,string3,...}           Brace expansion  
{a..z}                                  Extended brace expansion  
{}                                      Text replacement, after find and xargs

Parentheses

( command1; command2 )             Command group executed within a subshell  
Array=(element1 element2 element3) Array initialization  
result=$(COMMAND)                  Command substitution, new style  
>(COMMAND)                         Process substitution  
<(COMMAND)                         Process substitution 

Double Parentheses

(( var = 78 ))            Integer arithmetic   
var=$(( 20 + 5 ))         Integer arithmetic, with variable assignment   
(( var++ ))               C-style variable increment   
(( var-- ))               C-style variable decrement   
(( var0 = var1<98?9:21 )) C-style ternary operation

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Just define the button as lateinit var at top of your class:

 lateinit var buttonOk: Button

When you want to use a button in another layout you should define it in that layout. For example if you want to use button in layout which name is 'dialogview', you should write:

 buttonOk = dialogView.findViewById<Button>(R.id.buttonOk)

After this you can use setonclicklistener for the button and you won't have any error. You can see correct answer of this question: Android Kotlin findViewById must not be null

How to read request body in an asp.net core webapi controller?

To be able to rewind the request body, @Jean's answer helped me come up with a solution that seems to work well. I currently use this for Global Exception Handler Middleware but the principle is the same.

I created a middleware that basically enables the rewind on the request body (instead of a decorator).

using Microsoft.AspNetCore.Http.Internal;
[...]
public class EnableRequestRewindMiddleware
{
    private readonly RequestDelegate _next;

    public EnableRequestRewindMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Request.EnableRewind();
        await _next(context);
    }
}

public static class EnableRequestRewindExtension
{
    public static IApplicationBuilder UseEnableRequestRewind(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<EnableRequestRewindMiddleware>();
    }
}

This can then be used in your Startup.cs like so:

[...]
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    [...]
    app.UseEnableRequestRewind();
    [...]
}

Using this approach, I have been able to rewind the request body stream successfully.

Truststore and Keystore Definitions

A keystore contains private keys, and the certificates with their corresponding public keys.

A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.

Export JAR with Netbeans

Do you mean compile it to JAR? NetBeans does that automatically, just do "clean and build" and look in the "dist" subdirectory of your project. There will be the JAR with "lib" folder containing the required libraries. These JAR + lib are enough to run the application.

If you disable "Compile on save" in the project properties, then it is no longer necessary to do "clean and build", simply "build" will suffice in most cases. This will save time if you want to change just a bit of the code and rebuild the JAR. However, note that NetBeans sometimes fails to handle dependencies and binary compatibility properly, which will lead to a faulty JAR throwing "no such method" or other obscure exceptions. Therefore, if you made a lot of changes since the last full rebuild and even remotely unsure that it will still work even if some classes aren't recompiled, then you must still do a full "clean and build" in order to get a perfectly working JAR.

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

How to connect to LocalDB in Visual Studio Server Explorer?

Visual Studio 2015 RC, has LocalDb 12 installed, similar instructions to before but still shouldn't be required to know 'magic', before hand to use this, the default instance should have been turned on ... Rant complete, no for solution:

cmd> sqllocaldb start

Which will display

LocalDB instance "MSSQLLocalDB" started.

Your instance name might differ. Either way pop over to VS and open Server Explorer, right click Data Connections, choose Add, choose SQL Server, in the server name type:

(localdb)\MSSQLLocalDB

Without entering in a DB name, click 'Test Connection'.

String.Format like functionality in T-SQL?

I have created a user defined function to mimic the string.format functionality. You can use it.

stringformat-in-sql

UPDATE:
This version allows the user to change the delimitter.

-- DROP function will loose the security settings.
IF object_id('[dbo].[svfn_FormatString]') IS NOT NULL
    DROP FUNCTION [dbo].[svfn_FormatString]
GO

CREATE FUNCTION [dbo].[svfn_FormatString]
(
    @Format NVARCHAR(4000),
    @Parameters NVARCHAR(4000),
    @Delimiter CHAR(1) = ','
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    /*
        Name: [dbo].[svfn_FormatString]
        Creation Date: 12/18/2020

        Purpose: Returns the formatted string (Just like in C-Sharp)

        Input Parameters:   @Format         = The string to be Formatted
                            @Parameters     = The comma separated list of parameters
                            @Delimiter      = The delimitter to be used in the formatting process

        Format:             @Format         = N'Hi {0}, Welcome to our site {1}. Thank you {0}'
                            @Parameters     = N'Karthik,google.com'
                            @Delimiter      = ','           
        Examples:
            SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik,google.com', default)
            SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik;google.com', ';')
    */
    DECLARE @Message NVARCHAR(400)
    DECLARE @ParamTable TABLE ( Id INT IDENTITY(0,1), Paramter VARCHAR(1000))

    SELECT @Message = @Format

    ;WITH CTE (StartPos, EndPos) AS
    (
        SELECT 1, CHARINDEX(@Delimiter, @Parameters)
        UNION ALL
        SELECT EndPos + (LEN(@Delimiter)), CHARINDEX(@Delimiter, @Parameters, EndPos + (LEN(@Delimiter)))
        FROM CTE
        WHERE EndPos > 0
    )

    INSERT INTO @ParamTable ( Paramter )
    SELECT
        [Id] = SUBSTRING(@Parameters, StartPos, CASE WHEN EndPos > 0 THEN EndPos - StartPos ELSE 4000 END )
    FROM CTE

    UPDATE @ParamTable 
    SET 
        @Message = REPLACE(@Message, '{'+ CONVERT(VARCHAR, Id) + '}', Paramter )

    RETURN @Message
END

Boto3 to download all files from a S3 Bucket

for objs in my_bucket.objects.all():
    print(objs.key)
    path='/tmp/'+os.sep.join(objs.key.split(os.sep)[:-1])
    try:
        if not os.path.exists(path):
            os.makedirs(path)
        my_bucket.download_file(objs.key, '/tmp/'+objs.key)
    except FileExistsError as fe:                          
        print(objs.key+' exists')

This code will download the content in /tmp/ directory. If you want you can change the directory.

Set field value with reflection

It's worth reading Oracle Java Tutorial - Getting and Setting Field Values

Field#set(Object object, Object value) sets the field represented by this Field object on the specified object argument to the specified new value.

It should be like this

f.set(objectOfTheClass, new ConcurrentHashMap<>());

You can't set any value in null Object If tried then it will result in NullPointerException


Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.

How display only years in input Bootstrap Datepicker?

For bootstrap datetimepicker, assign decade value as follow:

$(".years").datetimepicker({
    format: "yyyy",
    startView: 'decade',
    minView: 'decade',
    viewSelect: 'decade',
    autoclose: true,
});

How do I write dispatch_after GCD in Swift 3, 4, and 5?

In Swift 4.1 and Xcode 9.4.1

Simple answer is...

//To call function after 5 seconds time
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
}

Show pop-ups the most elegant way

Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.

Why specify @charset "UTF-8"; in your CSS file?

If you're putting a <meta> tag in your css files, you're doing something wrong. The <meta> tag belongs in your html files, and tells the browser how the html is encoded, it doesn't say anything about the css, which is a separate file. You could conceivably have completely different encodings for your html and css, although I can't imagine this would be a good idea.

PostgreSQL: how to convert from Unix epoch to date?

The solution above not working for the latest version on PostgreSQL. I found this way to convert epoch time being stored in number and int column type is on PostgreSQL 13:

SELECT TIMESTAMP 'epoch' + (<table>.field::int) * INTERVAL '1 second' as started_on from <table>;

For more detail explanation, you can see here https://www.yodiw.com/convert-epoch-time-to-timestamp-in-postgresql/#more-214

How to change the text of a label?

I was having the same problem because i was using

$("#LabelID").val("some value");

I learned that you can either use the provisional jquery method to clear it first then append:

$("#LabelID").empty();
$("#LabelID").append("some Text");

Or conventionaly, you could use:

$("#LabelID").text("some value");

OR

$("#LabelID").html("some value");

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

I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:

<startup>
  <supportedRuntime version="v2.0.50727"/>
</startup>

So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.

Differences between Emacs and Vim

I have worked with spacemacs for about 2 years and neovim for about a year now in a production/research environment. Spacemacs is emacs with couple of nice extra features like layers etc. And neovim is a fork of vim again with some extra features.

I am quite unsatisfied with both of them in terms of experience. And I am still on the look out for a long term solution for my text editing needs.

Here is a simple comparison:

  • Neovim, vim, emacs, spacemacs, etc all of those editors consume less ressources compared to most of the editors out there.

  • Neovim/vim is slightly faster than emacs, noticably faster than spacemacs.

  • In terms of editing experience. I can easily say that emacs packages feel superior. I think that's because they blend in better with the core of emacs.

  • Vimscript is nice and there are certainly great projects in the vim ecosystem as well. The good thing is they are better documented than most emacs projects I have seen so far.

  • Both can be glitchy depending on the package you are using. Spacemacs tend to freeze, and neovim tend to display scary error messages, so pick your poison there.

  • Modal editing in vim, is not an intuitive concept, but once you get used to it, you want it anywere. Both of the editor provide that.

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

Just posting in case it help someone else. The cause of this error for me was a missing do after creating a form with form_with. Hope that may help someone else

How to generate javadoc comments in Android Studio

You can use eclipse style of JavaDoc comment generation through "Fix doc comment". Open "Preference" -> "Keymap" and assign "Fix doc comment" action to a key that you want.

Preventing HTML and Script injections in Javascript

From here

var string="<script>...</script>";
string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Visual Studio Code terminal (Ctrl + `)
  2. Write the Git clone command. For example,

    git clone https://github.com/angular/angular-phonecat.git
    
  3. Open the folder you have just cloned (menu FileOpen Folder)

    Enter image description here

How to include Authorization header in cURL POST HTTP Request in PHP?

use "Content-type: application/x-www-form-urlencoded" instead of "application/json"

Read data from a text file using Java

public class FilesStrings {

public static void main(String[] args) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream("input.txt");
    InputStreamReader input = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(input);
    String data;
    String result = new String();

    while ((data = br.readLine()) != null) {
        result = result.concat(data + " ");
    }

    System.out.println(result);

How to make inline plots in Jupyter Notebook larger?

A small but important detail for adjusting figure size on a one-off basis (as several commenters above reported "this doesn't work for me"):

You should do plt.figure(figsize=(,)) PRIOR to defining your actual plot. For example:

This should correctly size the plot according to your specified figsize:

values = [1,1,1,2,2,3]
_ = plt.figure(figsize=(10,6))
_ = plt.hist(values,bins=3)
plt.show()

Whereas this will show the plot with the default settings, seeming to "ignore" figsize:

values = [1,1,1,2,2,3]
_ = plt.hist(values,bins=3)
_ = plt.figure(figsize=(10,6))
plt.show()

How to find substring from string?

In C++

using namespace std;

string my_string {"Hello world"};
string element_to_be_found {"Hello"};

if(my_string.find(element_to_be_found)!=string::npos)
   std::cout<<"Element Found"<<std::endl;

Empty or Null value display in SSRS text boxes

Try this

=IIF(IsNothing(Fields!MyField.Value)=TRUE,"NA",Fields!MyFields.Value)

How to control the width and height of the default Alert Dialog in Android?

I dont know whether you can change the default height/width of AlertDialog but if you wanted to do this, I think you can do it by creating your own custom dialog. You just have to give android:theme="@android:style/Theme.Dialog" in the android manifest.xml for your activity and can write the whole layout as per your requirement. you can set the height and width of your custom dialog from the Android Resource XML.

Converting bool to text in C++

Without dragging ostream into it:

constexpr char const* to_c_str(bool b) {
   return  
    std::array<char const*, 2>{"false", "true "}[b]
   ;
};

Creating new database from a backup of another Database on the same server?

Checking the Options Over Write Database worked for me :)

enter image description here

ActionBar text color

Ok, I've found a better way. I'm now able to only change the color of the title. You can also tweak the subtitle.

Here is my styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/MyTheme.ActionBarStyle</item>
  </style>

  <style name="MyTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
  </style>

  <style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">@color/red</item>
  </style>
</resources>

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

How can I format bytes a cell in Excel as KB, MB, GB etc?

After seeing the answers here just improved on this formula to have decimal places on bigger values and cater for negative values.

=IF(A1<999500000000,TEXT(A1,"#,##.#0,,,"" TB"""),
IF(A1<-9995000000,TEXT(A1,"#,##.#0,,,"" GB"""),
IF(A1<-9995000,TEXT(A1,"#,##0,,"" MB"""),
IF(A1<-9995,TEXT(A1,"#,##0,"" KB"""),
IF(A1<-1000,TEXT(A1,"#,##0"" B """),
IF(A1<0,TEXT(A1,"#,##0"" B """),
IF(A1<1000,TEXT(A1,"#,##0"" B """),
IF(A1<999500,TEXT(A1,"#,##0,"" KB"""),
IF(A1<999500000,TEXT(A1,"#,##0,,"" MB"""),
IF(A1<999500000000,TEXT(A1,"#,##.#0,,,"" GB"""),
TEXT(A1,"#,##.#0,,,,"" TB""")))))))))))

How to append to the end of an empty list?

Mikola has the right answer but a little more explanation. It will run the first time, but because append returns None, after the first iteration of the for loop, your assignment will cause list1 to equal None and therefore the error is thrown on the second iteration.

How to install Boost on Ubuntu

Get the version of Boost that you require. This is for 1.55 but feel free to change or manually download yourself:

wget -O boost_1_55_0.tar.gz https://sourceforge.net/projects/boost/files/boost/1.55.0/boost_1_55_0.tar.gz/download
tar xzvf boost_1_55_0.tar.gz
cd boost_1_55_0/

Get the required libraries, main ones are icu for boost::regex support:

sudo apt-get update
sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev libbz2-dev libboost-all-dev

Boost's bootstrap setup:

./bootstrap.sh --prefix=/usr/

Then build it with:

./b2

and eventually install it:

sudo ./b2 install

Base64 String throwing invalid character error

Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/

But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.

One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.

MySQL Cannot drop index needed in a foreign key constraint

If you are using PhpMyAdmin sometimes it don't show the foreign key to delete.

The error code gives us the name of the foreign key and the table where it was defined, so the code is:

ALTER TABLE your_table DROP FOREIGN KEY foreign_key_name; 

Fast way to get the min/max values among properties of object

Using the lodash library you can write shorter

_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();

jQuery addClass onClick

$('#button').click(function(){
    $(this).addClass('active');
});

How to get overall CPU usage (e.g. 57%) on Linux

Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:

$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%

This will use awk to print out 100 minus the 12th field (idle), with a percentage sign after it. awk will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/).

You can also average five samples, one second apart:

$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'

Test it like this:

$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'

View list of all JavaScript variables in Google Chrome Console

Open the console and then enter:

  • keys(window) to see variables
  • dir(window) to see objects

NoClassDefFoundError for code in an Java library on Android

I had the same issue, I did the following to fix the problem.

  1. Go to "Properties" of the project.
  2. Select "Java Build Path"
  3. Select "Order and Export" Tab
  4. You should see the selected project's "src" and "gen" paths and dependencies here.
  5. The order how they listed were first "src" and then "gen" path
  6. I switch them, so that "gen" folder is build before the "src"

gen - automated code in project (from dependencies and references)
src - source code in project

There was no need to restart the Eclipse. It just started working.

Honestly I have never tried "Android Tools > Fix Project Properties", sometimes it might be doing the same thing. I do not know, I just did above after seen the error message, thinking something is wrong with the build paths.


Edit


Later on it was not sufficient, I was getting the error again. Then I "checked" all the dependencies listed in that view. Now it works again. So far so good. I will keep this updated if it fails again.

FYI: in my last attempt, I tried "Android Tools > Fix Project Properties", but it didn't work out for me.

convert a char* to std::string

Pass it in through the constructor:

const char* dat = "my string!";
std::string my_string( dat );

You can use the function string.c_str() to go the other way:

std::string my_string("testing!");
const char* dat = my_string.c_str();

Calculating Pearson correlation and significance in Python

The Pearson correlation can be calculated with numpy's corrcoef.

import numpy
numpy.corrcoef(list1, list2)[0, 1]

Object of class stdClass could not be converted to string - laravel

Try this simple in one line of code:-

$data= json_decode( json_encode($data), true);

Hope it helps :)

Convert pandas data frame to series

Another way -

Suppose myResult is the dataFrame that contains your data in the form of 1 col and 23 rows

# label your columns by passing a list of names
myResult.columns = ['firstCol']

# fetch the column in this way, which will return you a series
myResult = myResult['firstCol']

print(type(myResult))

In similar fashion, you can get series from Dataframe with multiple columns.

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

Apply a theme to an activity in Android?

To set it programmatically in Activity.java:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setTheme(R.style.MyTheme); // (for Custom theme)
  setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)

  this.setContentView(R.layout.myactivity);

To set in Application scope in Manifest.xml (all activities):

 <application
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To set in Activity scope in Manifest.xml (single activity):

  <activity
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To build a custom theme, you will have to declare theme in themes.xml file, and set styles in styles.xml file.

Example for boost shared_mutex (multiple reads/one write)?

Use a semaphore with a count that is equal to the number of readers. Let each reader take one count of the semaphore in order to read, that way they can all read at the same time. Then let the writer take ALL the semaphore counts prior to writing. This causes the writer to wait for all reads to finish and then block out reads while writing.

Can you have multiline HTML5 placeholder text in a <textarea>?

If your textarea have a static width you can use combination of non-breaking space and automatic textarea wrapping. Just replace spaces to nbsp for every line and make sure that two neighbour lines can't fit into one. In practice line length > cols/2.

This isn't the best way, but could be the only cross-browser solution.

_x000D_
_x000D_
<textarea class="textAreaMultiligne" _x000D_
          placeholder="Hello,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; This&nbsp;is&nbsp;multiligne&nbsp;example Have&nbsp;Fun&nbsp;&nbsp;&nbsp;&nbsp;"_x000D_
          rows="5" cols="35"></textarea>
_x000D_
_x000D_
_x000D_

Moment.js with Vuejs

TESTED

import Vue from 'vue'
    
Vue.filter('formatYear', (value) => {
  if (!value) return ''
  return moment(value).format('YYYY')
})

Variable not accessible when initialized outside function

A global variable would be best expressed in an external JavaScript file:

var system_status;

Make sure that this has not been used anywhere else. Then to access the variable on your page, just reference it as such. Say, for example, you wanted to fill in the results on a textbox,

document.getElementById("textbox1").value = system_status;

To ensure that the object exists, use the document ready feature of jQuery.

Example:

$(function() {
    $("#textbox1")[0].value = system_status;
});

Android: Internet connectivity change listener

This should work:

public class ConnectivityChangeActivity extends Activity {

    private BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("app","Network connectivity change");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(networkChangeReceiver);
    }
}

'module' has no attribute 'urlencode'

You use the Python 2 docs but write your program in Python 3.

What is the difference between <section> and <div>?

In the HTML5 standard, the <section> element is defined as a block of related elements.

The <div> element is defined as a block of children elements.

How to access pandas groupby dataframe by key

gb = df.groupby(['A'])

gb_groups = grouped_df.groups

If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..

gb_groups.keys()

key_list = [key1, key2, key3 and so on...]

for key, values in gb_groups.iteritems():
    if key in key_list:
        print df.ix[values], "\n"

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

Split by comma and strip whitespace in Python

import re
result=[x for x in re.split(',| ',your_string) if x!='']

this works fine for me.

Check if a property exists in a class

If you are binding like I was:

<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2")  %>