Programs & Examples On #Isaccessibletouser

Should I test private methods or only public ones?

Yes you should test private methods, wherever possible. Why? To avoid an unnecessary state space explosion of test cases which ultimately just end up implicitly testing the same private functions repeatedly on the same inputs. Let's explain why with an example.

Consider the following slightly contrived example. Suppose we want to expose publicly a function that takes 3 integers and returns true if and only if those 3 integers are all prime. We might implement it like this:

public bool allPrime(int a, int b, int c)
{
  return andAll(isPrime(a), isPrime(b), isPrime(c))
}

private bool andAll(bool... boolArray)
{
  foreach (bool b in boolArray)
  {
    if(b == false) return false;
  }
  return true;
}

private bool isPrime(int x){
  //Implementation to go here. Sorry if you were expecting a prime sieve.
}

Now, if we were to take the strict approach that only public functions should be tested, we'd only be allowed to test allPrime and not isPrime or andAll.

As a tester, we might be interested in five possibilities for each argument: < 0, = 0, = 1, prime > 1, not prime > 1. But to be thorough, we'd have to also see how every combination of the arguments plays together. So that's 5*5*5 = 125 test cases we'd need to thoroughly test this function, according to our intuitions.

On the other hand, if we were allowed to test the private functions, we could cover as much ground with fewer test cases. We'd need only 5 test cases to test isPrime to the same level as our previous intuition. And by the small scope hypothesis proposed by Daniel Jackson, we'd only need to test the andAll function up to a small length e.g. 3 or 4. Which would be at most 16 more tests. So 21 tests in total. Instead of 125. Of course, we probably would want to run a few tests on allPrime, but we wouldn't feel so obliged to cover exhaustively all 125 combinations of input scenarios we said we cared about. Just a few happy paths.

A contrived example, for sure, but it was necessary for a clear demonstration. And the pattern extends to real software. Private functions are usually the lowest level building blocks, and are thus often combined together to yield higher level logic. Meaning at higher levels, we have more repetitions of the lower level stuff due to the various combinations.

How to get MD5 sum of a string using python?

Try This 
import hashlib
user = input("Enter text here ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
print(h2)

CSS: create white glow around image

@tamir; you cna do it with css3 property.

img{
-webkit-box-shadow: 0px 0px 3px 5px #f2e1f2;
-moz-box-shadow: 0px 0px 3px 5px #f2e1f2;
box-shadow: 0px 0px 3px 5px #f2e1f2; 
}

check the fiddle http://jsfiddle.net/XUC5q/1/ & your can generate from here http://css3generator.com/

If you need it to work in older versions of IE, you can use CSS3 PIE to emulate the box-shadow in those browsers & you can use filter as kyle said like this

filter:progid:DXImageTransform.Microsoft.Glow(color='red', Strength='5')

you can generate your filter from here http://samples.msdn.microsoft.com/workshop/samples/author/filter/Glow.htm

Python: Random numbers into a list

my_randoms = [randint(n1,n2) for x in range(listsize)]

What are the undocumented features and limitations of the Windows FINDSTR command?

When several commands are enclosed in parentheses and there are redirected files to the whole block:

< input.txt (
   command1
   command2
   . . .
) > output.txt

... then the files remains open as long as the commands in the block be active, so the commands may move the file pointer of the redirected files. Both MORE and FIND commands move the Stdin file pointer to the beginning of the file before process it, so the same file may be processed several times inside the block. For example, this code:

more < input.txt >  output.txt
more < input.txt >> output.txt

... produce the same result than this one:

< input.txt (
   more
   more
) > output.txt

This code:

find    "search string" < input.txt > matchedLines.txt
find /V "search string" < input.txt > unmatchedLines.txt

... produce the same result than this one:

< input.txt (
   find    "search string" > matchedLines.txt
   find /V "search string" > unmatchedLines.txt
)

FINDSTR is different; it does not move the Stdin file pointer from its current position. For example, this code insert a new line after a search line:

call :ProcessFile < input.txt
goto :EOF

:ProcessFile
   rem Read the next line from Stdin and copy it
   set /P line=
   echo %line%
   rem Test if it is the search line
   if "%line%" neq "search line" goto ProcessFile
rem Insert the new line at this point
echo New line
rem And copy the rest of lines
findstr "^"
exit /B

We may make good use of this feature with the aid of an auxiliary program that allow us to move the file pointer of a redirected file, as shown in this example.

This behavior was first reported by jeb at this post.


EDIT 2018-08-18: New FINDSTR bug reported

The FINDSTR command have a strange bug that happen when this command is used to show characters in color AND the output of such a command is redirected to CON device. For details on how use FINDSTR command to show text in color, see this topic.

When the output of this form of FINDSTR command is redirected to CON, something strange happens after the text is output in the desired color: all the text after it is output as "invisible" characters, although a more precise description is that the text is output as black text over black background. The original text will appear if you use COLOR command to reset the foreground and background colors of the entire screen. However, when the text is "invisible" we could execute a SET /P command, so all characters entered will not appear on the screen. This behavior may be used to enter passwords.

@echo off
setlocal

set /P "=_" < NUL > "Enter password"
findstr /A:1E /V "^$" "Enter password" NUL > CON
del "Enter password"
set /P "password="
cls
color 07
echo The password read is: "%password%"

Convert a SQL query result table to an HTML table for email

Suppose someone found his way here and does not understand the usage of the marked answer SQL, please read mine... it is edited and works. Table:staff, columns:staffname,staffphone and staffDOB

declare @body varchar(max)

--    Create the body
set @body = cast( (
select td = dbtable + '</td><td>' + cast( phone as varchar(30) ) + '</td><td>' + cast( age as varchar(30) )
from (
      select dbtable  = StaffName ,
               phone = staffphone,
               age          = datepart(day,staffdob)
      from staff
      group by staffname,StaffPhone,StaffDOB  
      ) as d
for xml path( 'tr' ), type ) as varchar(max) )
set @body = '<table cellpadding="2" cellspacing="2" border="1">'
              + '<tr><th>Database Table</th><th>Entity Count</th><th>Total Rows</th></tr>'
              + replace( replace( @body, '&lt;', '<' ), '&gt;', '>' )
              + '<table>'
print @body

Uploading files to file server using webclient class

namespace FileUpload
{
public partial class Form1 : Form
{
    string fileName = "";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        string path = "";
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Attach customer proposal document";
        fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
        fDialog.InitialDirectory = @"C:\";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = System.IO.Path.GetFileName(fDialog.FileName);
            path = Path.GetDirectoryName(fDialog.FileName);
            textBox1.Text = path + "\\" + fileName;

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            WebClient client = new WebClient();

            NetworkCredential nc = new NetworkCredential("erandika1986", "123");

            Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);

            client.Credentials = nc;
            byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
            MessageBox.Show(arrReturn.ToString());

        }
        catch (Exception ex1)
        {
            MessageBox.Show(ex1.Message);
        }
    }
}
}

How can I remove duplicate rows?

The following query is useful to delete duplicate rows. The table in this example has ID as an identity column and the columns which have duplicate data are Column1, Column2 and Column3.

DELETE FROM TableName
WHERE  ID NOT IN (SELECT MAX(ID)
                  FROM   TableName
                  GROUP  BY Column1,
                            Column2,
                            Column3
                  /*Even if ID is not null-able SQL Server treats MAX(ID) as potentially
                    nullable. Because of semantics of NOT IN (NULL) including the clause
                    below can simplify the plan*/
                  HAVING MAX(ID) IS NOT NULL) 

The following script shows usage of GROUP BY, HAVING, ORDER BY in one query, and returns the results with duplicate column and its count.

SELECT YourColumnName,
       COUNT(*) TotalCount
FROM   YourTableName
GROUP  BY YourColumnName
HAVING COUNT(*) > 1
ORDER  BY COUNT(*) DESC 

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

PermissionError: [Errno 13] Permission denied

Another option that helped me is using pathlib:

from pathlib import Path
p = Path('.') ## if you want to write to current directory
with open(p / 'test.txt', 'w') as f:
    f.write('test message')

and it works

Changing button color programmatically

Here is an example using HTML:

<input type="button" value="click me" onclick="this.style.color='#000000';
this.style.backgroundColor = '#ffffff'" />

And here is an example using JavaScript:

document.getElementById("button").bgcolor="#Insert Color Here";

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Create a static member in your Activity class. Then assign the value during the onPostExecute

For example, if the result of your AsyncTask is a String, create a public static string in your Activity

public static String dataFromAsyncTask;

Then, in the onPostExecute of the AsyncTask, simply make a static call to your main class and set the value.

MainActivity.dataFromAsyncTask = "result blah";

Linq order by, group by and order by each group?

Alternatively you can do like this :

     var _items = from a in StudentsGrades
                  group a by a.Name;

     foreach (var _itemGroup in _items)
     {
        foreach (var _item in _itemGroup.OrderBy(a=>a.grade))
        {
           ------------------------
           --------------------------
        }
     }

How do I get sed to read from standard input?

To make sed catch from stdin , instead of from a file, you should use -e.

Like this:

curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk  'BEGIN{FS=":"} {print $4}'

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

jQuery detect if string contains something

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
{
 //do stuffs to change 
}

Android EditText Max Length

I had the same problem. It works perfectly fine when you add this:

android:inputType="textFilter"

to your EditText.

Get Android shared preferences value in activity/normal class

If you have a SharedPreferenceActivity by which you have saved your values

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");

if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.

and this is how you can retrieve the values.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));

Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.

mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I've faced this error, when there was no enough free space to create backup.

Call Python function from MATLAB

Since MATLAB seamlessly integrates with Java, you can use Jython to write your script and call that from MATLAB (you may have to add a thin pure JKava wrapper to actually call the Jython code). I never tried it, but I can't see why it won't work.

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

Yes, that is supported.

Check the documentation provided here for the supported keywords inside method names.

You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:

List<Inventory> findByIdIn(List<Long> ids);

I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:

The Entity

@Entity
public class Inventory implements Serializable {

  private static final long serialVersionUID = 1L;

  private Long id;

  // other fields
  // getters/setters

}

The Repository

@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {

  List<Inventory> findByIdIn(List<Long> ids);

}

Getting JSONObject from JSONArray

JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}

How to tell if a file is git tracked (by shell exit code)?

Just my two cents:

git ls-files | grep -x relative/path

where relative/path can be easily determined by pressing tab within an auto-completion shell. Add an additional | wc -l to get a 1 or 0 output.

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

Android Layout Weight

<LinearLayout
    android:id="@+id/linear1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="9"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ring_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/ring_oss" />

    <ImageView
        android:id="@+id/maila_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
<EditText
        android:id="@+id/edittxt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
</LinearLayout>

How to add a "confirm delete" option in ASP.Net Gridview?

You can do using OnClientClick of button.

OnClientClick="return confirm('confirm delete')"

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

If you are using arch based system like in manjaro

just use

sudo pacman -S php-sqlite

Restart your httpd

systemctl restart httpd

How to apply color in Markdown?

Short story: links. Make use of something like:

_x000D_
_x000D_
a[href='red'] {
    color: red;
    pointer-events: none;
    cursor: default;
    text-decoration: none;
}
_x000D_
<a href="red">Look, ma! Red!</a>
_x000D_
_x000D_
_x000D_

(HTML above for demonstration purposes)

And in your md source:

[Look, ma! Red!](red)

What do these three dots in React do?

The ...(spread operator) is used in react to:

provide a neat way to pass props from parent to child components. e.g given these props in a parent component,

this.props = {
  username: "danM",
  email: "[email protected]"
}

they could be passed in the following manner to the child,

<ChildComponent {...this.props} />

which is similar to this

<ChildComponent username={this.props.username} email={this.props.email} />

but way cleaner.

How do I do a not equal in Django queryset filtering?

The last bit of code will exclude all objects where x!=5 and a is True. Try this:

results = Model.objects.filter(a=False, x=5)

Remember, the = sign in the above line is assigning False to the parameter a and the number 5 to the parameter x. It's not checking for equality. Thus, there isn't really any way to use the != symbol in a query call.

Stop Chrome Caching My JS Files

A faster way to do this is by right clicking the refresh icon beside the address bar and choosing Empty Cache and Hard reload

Just make sure Chrome's dev tools is open. (Press F12) By the way... This trick only works on Chrome for Windows, Ubuntu, and Mac OS

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

Implementation in Kotlin : Retrofit 2.3.0

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


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

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

val mTrustManagers = mTrustManagerFactory.trustManagers

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

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

}

Best way to encode text data for XML in Java?

If you are looking for a library to get the job done, try:

  1. Guava 26.0 documented here

    return XmlEscapers.xmlContentEscaper().escape(text);

    Note: There is also an xmlAttributeEscaper()

  2. Apache Commons Text 1.4 documented here

    StringEscapeUtils.escapeXml11(text)

    Note: There is also an escapeXml10() method

Add php variable inside echo statement as href link address?

If you want to print in the tabular form with, then you can use this:

echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;

Convert a date format in epoch

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.

Parse XLSX with Node and create json

**podria ser algo asi en react y electron**

 xslToJson = workbook => {
        //var data = [];
        var sheet_name_list = workbook.SheetNames[0];
        return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
            raw: false,
            dateNF: "DD-MMM-YYYY",
            header:1,
            defval: ""
        });
    };

    handleFile = (file /*:File*/) => {
        /* Boilerplate to set up FileReader */
        const reader = new FileReader();
        const rABS = !!reader.readAsBinaryString;

        reader.onload = e => {
            /* Parse data */
            const bstr = e.target.result;
            const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
            /* Get first worksheet */
            let arr = this.xslToJson(wb);

            console.log("arr ", arr)
            var dataNueva = []

            arr.forEach(data => {
                console.log("data renaes ", data)
            })
            // this.setState({ DataEESSsend: dataNueva })
            console.log("dataNueva ", dataNueva)

        };


        if (rABS) reader.readAsBinaryString(file);
        else reader.readAsArrayBuffer(file);
    };

    handleChange = e => {
        const files = e.target.files;
        if (files && files[0]) {
            this.handleFile(files[0]);
        }
    };

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

React Native: Possible unhandled promise rejection

delete build folder projectfile\android\app\build and run project

Print the data in ResultSet along with column names

use further as

rs.getString(1);
rs.getInt(2);

1, 2 is the column number of table and set int or string as per data-type of coloumn

How do I convert a org.w3c.dom.Document object to a String?

A Scala version based on Zaz's answer.

  case class DocumentEx(document: Document) {
    def toXmlString(pretty: Boolean = false):Try[String] = {
      getStringFromDocument(document, pretty)
    }
  }

  implicit def documentToDocumentEx(document: Document):DocumentEx = {
    DocumentEx(document)
  }

  def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
    try
    {
      val domSource= new DOMSource(doc)
      val writer = new StringWriter()
      val result = new StreamResult(writer)
      val tf = TransformerFactory.newInstance()
      val transformer = tf.newTransformer()
      if (pretty)
        transformer.setOutputProperty(OutputKeys.INDENT, "yes")
      transformer.transform(domSource, result)
      Success(writer.toString);
    }
    catch {
      case ex: TransformerException =>
        Failure(ex)
    }
  }

With that, you can do either doc.toXmlString() or call the getStringFromDocument(doc) function.

How to get ASCII value of string in C#

From MSDN

string value = "9quali52ty3";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

You now have an array of the ASCII value of the bytes. I got the following:

57 113 117 97 108 105 53 50 116 121 51

NotificationCenter issue on Swift 3

I think it has changed again.

For posting this works in Xcode 8.2.

NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)

Split Spark Dataframe string column into multiple columns

pyspark.sql.functions.split() is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem() to retrieve each part of the array as a column itself:

split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))

The result will be:

col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
  18 |  856-yygrm |   856 | yygrm
 201 |  777-psgdg |   777 | psgdg

I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

Following what @viveknuna suggested, I upgraded to the latest version of node.js and npm using the downloaded installer. I also installed the latest version of yarn using a downloaded installer. Then, as you can see below, I upgraded angular-cli and typescript. Here's what that process looked like:

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g @angular/cli@latest
C:\Users\Jack\AppData\Roaming\npm\ng -> C:\Users\Jack\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@angular\cli\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ @angular/[email protected]
added 75 packages, removed 166 packages, updated 61 packages and moved 24 packages in 29.084s

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g typescript
C:\Users\Jack\AppData\Roaming\npm\tsserver -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\Jack\AppData\Roaming\npm\tsc -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ [email protected]
updated 1 package in 2.427s

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>node -v
v8.10.0

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm -v
5.6.0

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn --version
1.5.1

Thereafter, I ran yarn and npm start in my angular folder and all appears to be well. Here's what that looked like:

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn
yarn install v1.5.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "@angular/cli > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning "@angular/cli > @angular-devkit/schematics > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning " > [email protected]" has incorrect peer dependency "@angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0".
warning " > [email protected]" has incorrect peer dependency "@angular/core@^2.3.1 || >=4.0.0-beta <5.0.0".
[4/4] Building fresh packages...
Done in 232.79s.

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm start

> [email protected] start D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular
> ng serve --host 0.0.0.0 --port 4200

** NG Live Development Server is listening on 0.0.0.0:4200, open your browser on http://localhost:4200/ **
Date: 2018-03-22T13:17:28.935Z
Hash: 8f226b6fa069b7c201ea
Time: 22494ms
chunk {account.module} account.module.chunk.js () 129 kB  [rendered]
chunk {app.module} app.module.chunk.js () 497 kB  [rendered]
chunk {common} common.chunk.js (common) 1.46 MB  [rendered]
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 515 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.1 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.53 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 15.1 MB [initial] [rendered]

webpack: Compiled successfully.

Passing properties by reference in C#

The accepted answer is good if that function is in your code and you can modify it. But sometimes you have to use an object and a function from some external library and you can't change the property and function definition. Then you can just use a temporary variable.

var phone = Client.WorkPhone;
GetString(input, ref phone);
Client.WorkPhone = phone;

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.

If you look at the call signature of np.int, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()

You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int).

Note that np.vectorize is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int) as @FFT suggests).

Python 2: AttributeError: 'list' object has no attribute 'strip'

One possible solution I have tried right now is: (Make sure do it in general way using for, while with index)

>>> l=['Facebook;Google+;MySpace', 'Apple;Android']
>>> new1 = l[0].split(';')
>>> new1
['Facebook', 'Google+', 'MySpace']
>>> new2= l[1].split(';')`enter code here`
>>> new2
['Apple', 'Android']
>>> totalnew = new1 + new2
>>> totalnew
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

How to get user name using Windows authentication in asp.net?

Username you get like this:

var userName = HttpContext.Current.Request.LogonUserIdentity?.Name;

Using port number in Windows host file

Fiddler2 -> Rules -> Custom Rules

then find function OnBeforeRequest on put in the next script at the end:

if (oSession.HostnameIs("mysite.com")){
    oSession.host="localhost:39901";
}

Select box arrow style

for any1 using ie8 and dont want to use a plugin i've made something inspired by Rohit Azad and Bacotasan's blog, i just added a span using JS to show the selected value.

the html:

<div class="styled-select">
   <select>
      <option>Here is the first option</option>
      <option>The second option</option>
   </select>
   <span>Here is the first option</span>
</div>

the css (i used only an arrow for BG but you could put a full image and drop the positioning):

.styled-select div
{
    display:inline-block;
    border: 1px solid darkgray;
    width:100px;
    background:url("/Style Library/Nifgashim/Images/drop_arrrow.png") no-repeat 10px 10px;
    position:relative;
}

.styled-select div select
{
    height: 30px;
    width: 100px;
    font-size:14px;
    font-family:ariel;

    -moz-opacity: 0.00;
    opacity: .00;
    filter: alpha(opacity=00);
}

.styled-select div span
{
    position: absolute;
    right: 10px;
    top: 6px;
    z-index: -5;
}

the js:

$(".styled-select select").change(function(e){
     $(".styled-select span").html($(".styled-select select").val());
});

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

krosenvold's answer inspired the following script which does the following:

  • get the dd dump via ssh from a remote server (as gz file)
  • unzip the dump
  • convert it to vmware

the script is restartable and checks the existence of the intermediate files. It also uses pv and qemu-img -p to show the progress of each step.

In my environment 2 x Ubuntu 12.04 LTS the steps took:

  • 3 hours to get a 47 GByte disk dump of a 60 GByte partition
  • 20 minutes to unpack to a 60 GByte dd file
  • 45 minutes to create the vmware file
#!/bin/bash
# get a dd disk dump and convert it to vmware
#  see http://stackoverflow.com/questions/454899/how-to-convert-flat-raw-disk-image-to-vmdk-for-virtualbox-or-vmplayer
#  Author: wf  2014-10-1919

#
# get a dd dump from the given host's given disk and create a compressed
#   image at the given target 
#
#  1: host e.g. somehost.somedomain
#  2: disk e.g. sda
#  3: target e.g. image.gz
#
# http://unix.stackexchange.com/questions/132797/how-to-use-ssh-to-make-a-dd-copy-of-disk-a-from-host-b-and-save-on-disk-b
getdump() {
  local l_host="$1"
  local l_disk="$2"
  local l_target="$3"
  echo "getting disk dump of $l_disk from $l_host"
  ssh $l_host sudo fdisk -l  | egrep "^/dev/$l_disk"
  if [ $? -ne 0 ]
  then
    echo "device $l_disk does not exist on host $l_host" 1>&2
    exit 1
  else
    if [ ! -f $l_target ]
    then
      ssh $l_host "sudo dd if=/dev/$disk bs=1M | gzip -1 -" | pv | dd of=$l_target
    else
      echo "$l_target already exists"
    fi
  fi
}

#
# optionally install command from package if it is not available yet
# 1: command
# 2: package
#
opt_install() {
  l_command="$1"
  l_package="$2"
  echo "checking that $l_command from package $l_package  is installed ..."
  which $l_command
  if [ $? -ne 0 ]
  then
    echo "installing $l_package to make $l_command available ..."
    sudo apt-get install $l_package 
  fi
}

#
# convert the given image to vmware
#  1: the dd dump image
#  2: the vmware image file to convert to
#
vmware_convert() {
  local l_ddimage="$1"
  local l_vmwareimage="$2"
  echo "converting dd image $l_image to vmware $l_vmwareimage"
  #  convert to VMware disk format showing progess
  # see http://manpages.ubuntu.com/manpages/precise/man1/qemu-img.1.html
  qemu-img convert -p -O vmdk "$l_ddimage" "$l_vmwareimage"
}

#
# show usage
#
usage() {
  echo "usage: $0 host device"
  echo "      host: the host to get the disk dump from e.g. frodo.lotr.org"  
  echo "            you need ssh and sudo privileges on that host"
  echo "
  echo "    device: the disk to dump from e.g. sda"
  echo ""
  echo "  examples:
  echo "       $0 frodo.lotr.org sda"
  echo "       $0 gandalf.lotr.org sdb"
  echo ""
  echo "  the needed packages pv and qemu-utils will be installed if not available"
  echo "  you need local sudo rights for this to work"
  exit 1
}

# check arguments
if [ $# -lt 2 ]
then
  usage
fi

# get the command line parameters
host="$1"
disk="$2"

# calculate the names of the image files
ts=`date "+%Y-%m-%d"`
# prefix of all images
#   .gz the zipped dd
#   .dd the disk dump file
#   .vmware - the vmware disk file
image="${host}_${disk}_image_$ts"

echo "$0 $host/$disk ->  $image"

# first check/install necessary packages
opt_install qemu-img qemu-utils
opt_install pv pv

# check if dd files was already loaded
#  we don't want to start this tedious process twice if avoidable
if [ ! -f $image.gz ]
then
  getdump $host $disk $image.gz
else
  echo "$image.gz already downloaded"
fi

# check if the dd file was already uncompressed
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.dd ]
then
  echo "uncompressing $image.gz"
  zcat $image.gz | pv -cN zcat > $image.dd
else
  echo "image $image.dd already uncompressed"
fi
# check if the vmdk file was already converted
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.vmdk ]
then
  vmware_convert $image.dd $image.vmdk
else
  echo "vmware image $image.vmdk already converted"
fi

ESRI : Failed to parse source map

Chrome recently added support for source maps in the developer tools. If you go under settings on the chrome developer toolbar you can see the following two options:

Chrome Developer Tools Source Maps

If you disable those two options, and refresh the browser, it should no longer ask for source maps.

These settings can be found here:

Chrome Developer Tools Source Maps

Getting a list item by index

Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array.

List[index]

See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx

How to import a SQL Server .bak file into MySQL?

SQL Server databases are very Microsoft proprietary. Two options I can think of are:

  1. Dump the database in CSV, XML or similar format that you'd then load into MySQL.

  2. Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window.

How to sum up an array of integers in C#

An alternative also it to use the Aggregate() extension method.

var sum = arr.Aggregate((temp, x) => temp+x);

Get value of c# dynamic property via string

public static object GetProperty(object target, string name)
{
    var site = System.Runtime.CompilerServices.CallSite<Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, name, target.GetType(), new[]{Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(0,null)}));
    return site.Target(site, target);
}

Add reference to Microsoft.CSharp. Works also for dynamic types and private properties and fields.

Edit: While this approach works, there is almost 20× faster method from the Microsoft.VisualBasic.dll assembly:

public static object GetProperty(object target, string name)
{
    return Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(target, name, CallType.Get);
}

Get value from SimpleXMLElement Object

foreach($xml->code as $vals )
{ 
    unset($geonames);
    $vals=(array)$vals;
    foreach($vals as $key => $value)
      {
        $value=(array)$value;
        $geonames[$key]=$value[0];
      }
}
print_r($geonames);

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

How to get Wikipedia content using Wikipedia's API?

You can use JQuery to do that. First create the url with appropriate parameters. Check this link to understand what the parameters mean. Then use $.ajax() method to retrieve the articles. Note that wikipedia does not allow cross origin request. That's why we are using dataType : jsonp in the request.

var wikiURL = "https://en.wikipedia.org/w/api.php";
wikiURL += '?' + $.param({
    'action' : 'opensearch',
    'search' : 'your_search_term',
    'prop'  : 'revisions',
    'rvprop' : 'content',
    'format' : 'json',
    'limit' : 10
});

 $.ajax( {
    url: wikiURL,
    dataType: 'jsonp',
    success: function(data) {
       console.log(data);
    }
} );

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

This is what I do when i want to send email with attachment, work fine. :)

 public class NewClass {

    public static void main(String[] args) {
        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465"); // smtp port
            Authenticator auth = new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username-gmail", "password-gmail");
                }
            };
            Session session = Session.getDefaultInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("[email protected]"));
            msg.setSubject("Try attachment gmail");
            msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
            //add atleast simple body
            MimeBodyPart body = new MimeBodyPart();
            body.setText("Try attachment");
            //do attachment
            MimeBodyPart attachMent = new MimeBodyPart();
            FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
            attachMent.setDataHandler(new DataHandler(dataSource));
            attachMent.setFileName("file-sent.txt");
            attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(body);
            multipart.addBodyPart(attachMent);
            msg.setContent(multipart);
            Transport.send(msg);
        } catch (AddressException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Generating a PDF file from React Components

Rendering react as pdf is generally a pain, but there is a way around it using canvas.

The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF

To achieve the above, you'll need :

  1. html2canvas &
  2. jsPDF

_x000D_
_x000D_
import React, {Component, PropTypes} from 'react';_x000D_
_x000D_
// download html2canvas and jsPDF and save the files in app/ext, or somewhere else_x000D_
// the built versions are directly consumable_x000D_
// import {html2canvas, jsPDF} from 'app/ext';_x000D_
_x000D_
_x000D_
export default class Export extends Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
  }_x000D_
_x000D_
  printDocument() {_x000D_
    const input = document.getElementById('divToPrint');_x000D_
    html2canvas(input)_x000D_
      .then((canvas) => {_x000D_
        const imgData = canvas.toDataURL('image/png');_x000D_
        const pdf = new jsPDF();_x000D_
        pdf.addImage(imgData, 'JPEG', 0, 0);_x000D_
        // pdf.output('dataurlnewwindow');_x000D_
        pdf.save("download.pdf");_x000D_
      })_x000D_
    ;_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (<div>_x000D_
      <div className="mb5">_x000D_
        <button onClick={this.printDocument}>Print</button>_x000D_
      </div>_x000D_
      <div id="divToPrint" className="mt4" {...css({_x000D_
        backgroundColor: '#f5f5f5',_x000D_
        width: '210mm',_x000D_
        minHeight: '297mm',_x000D_
        marginLeft: 'auto',_x000D_
        marginRight: 'auto'_x000D_
      })}>_x000D_
        <div>Note: Here the dimensions of div are same as A4</div> _x000D_
        <div>You Can add any component here</div>_x000D_
      </div>_x000D_
    </div>);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

The snippet will not work here because the required files are not imported.

An alternate approach is being used in this answer, where the middle steps are dropped and you can simply convert from HTML to PDF. There is an option to do this in the jsPDF documentation as well, but from personal observation, I feel that better accuracy is achieved when dom is converted into png first.

Update 0: September 14, 2018

The text on the pdfs created by this approach will not be selectable. If that's a requirement, you might find this article helpful.

In php, is 0 treated as empty?

In case of numeric values you should use is_numeric function:

$var = 0;

if (is_numeric($var))
{
  echo "Its not empty";
} 
else 
{
    echo "Its empty";
}

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

OpenCV !_src.empty() in function 'cvtColor' error

I had the same problem and it turned out that my image names included special characters (e.g. château.jpg), which could not bet handled by cv2.imread. My solution was to make a temporary copy of the file, renaming it e.g. temp.jpg, which could be loaded by cv2.imread without any problems.

Note: I did not check the performance of shutil.copy2 vice versa other options. So probably there is a better/faster solution to make a temporary copy.

import shutil, sys, os, dlib, glob, cv2

for f in glob.glob(os.path.join(myfolder_path, "*.jpg")):
    shutil.copy2(f, myfolder_path + 'temp.jpg')
    img = cv2.imread(myfolder_path + 'temp.jpg')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    os.remove(myfolder_path + 'temp.jpg')

If there are only few files with special characters, renaming can also be done as an exeption, e.g.

for f in glob.glob(os.path.join(myfolder_path, "*.jpg")):
    try:
        img = cv2.imread(f)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    except:
        shutil.copy2(f, myfolder_path + 'temp.jpg')
        img = cv2.imread(myfolder_path + 'temp.jpg')
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        os.remove(myfolder_path + 'temp.jpg')

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

There are certain tools that provide dependency injection through their library, for example in .net we have ninject Library .

If you are going further in java then spring provides this capabilities.

Loosly coupled objects can be made by introducing Interfaces in your code, thats what these sources do.

Say in your code you are writing

Myclass m = new Myclass();

now this statement in your method says that you are dependent on myclass this is called a tightly coupled. Now you provide some constructor injection , or property injection and instantiating object then it will become loosly coupled.

How do I set the rounded corner radius of a color drawable using xml?

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    
             
    <stroke android:width="3dp"
            android:color="#ff000000" />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp" /> 
             
    <corners android:radius="7dp" /> 
</shape>

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

JQuery .each() backwards

I prefer creating a reverse plug-in eg

jQuery.fn.reverse = function(fn) {       
   var i = this.length;

   while(i--) {
       fn.call(this[i], i, this[i])
   }
};

Usage eg:

$('#product-panel > div').reverse(function(i, e) {
    alert(i);
    alert(e);
});

displaying a string on the textview when clicking a button in android

First create xml file as follows. Create one textview and a button:

main.xml

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

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

  <Button
    android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me" />

  <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

</LinearLayout>

The first TextView is created by default. You can leave or remove it if you want. Next one is to create a button The next one is TextView where you want to display text.

Now coming to the main activity code... package com.android.example.simple;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SimpleActivity extends Activity {
/** Called when the activity is first created. */
@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final TextView textView=(TextView)findViewById(R.id.textView1);
    final Button button1 =  (Button)findViewById(R.id.mybutton);

    //Implement listener for your button so that when you click the 
    //button, android will listen to it.             

     button1.setOnClickListener(new View.OnClickListener() {             
        public void onClick(View v) {                 
        // Perform action on click 
            textView.setText("You clicked the button");

        }         });
    }
}

Visual Studio 2015 installer hangs during install?

I've got same problem and unfortunately the accepted answer which suggests killing SecondaryInstaller.exe messed up installing the optional items. What I've done is basically opening the task manager and locate SecondaryInstaller.exe and right click and click on Open file location. Then run SecondaryInstaller.exe as an administrator.

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

How do I write out a text file in C# with a code page other than UTF-8?

Change the Encoding of the stream writer. It's a property.

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx

So:

sw.Encoding = Encoding.GetEncoding(28591);

Prior to writing to the stream.

Excel - Sum column if condition is met by checking other column in same table

SUMIF didn't worked for me, had to use SUMIFS.

=SUMIFS(TableAmount,TableMonth,"January")

TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.

Hope this can help someone!

function is not defined error in Python

It works for me:

>>> def pyth_test (x1, x2):
...     print x1 + x2
...
>>> pyth_test(1,2)
3

Make sure you define the function before you call it.

Android SQLite: Update Statement

You can use the code below.

String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);

align images side by side in html

In your CSS:

.image123{
float:left;
}

Select elements by attribute

In addition to selecting all elements with an attribute $('[someAttribute]') or $('input[someAttribute]') you can also use a function for doing boolean checks on an object such as in a click handler:

if(! this.hasAttribute('myattr') ) { ...

Failed loading english.pickle with nltk.data.load

In Spyder, go to your active shell and download nltk using below 2 commands. import nltk nltk.download() Then you should see NLTK downloader window open as below, Go to 'Models' tab in this window and click on 'punkt' and download 'punkt'

Window

How to calculate a mod b in Python?

A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0

Python: OSError: [Errno 2] No such file or directory: ''

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.

How can I find the location of origin/master in git, and how do I change it?

I was wondering the same thing about my repo. In my case I had an old remote that I wasn't pushing to anymore so I needed to remove it.

Get list of remotes:

git remote

Remove the one that you don't need

git remote rm {insert remote to remove}

Getting date format m-d-Y H:i:s.u from milliseconds

You can readily do this this with the input format U.u.

$now = DateTime::createFromFormat('U.u', microtime(true));
echo $now->format("m-d-Y H:i:s.u");

This produces the following output:

04-13-2015 05:56:22.082300

From the PHP manual page for date formats:

  • U = Seconds since the Unix Epoch
  • u = Microseconds

http://php.net/manual/en/function.date.php


Thanks goes to giggsey for pointing out a flaw in my original answer, adding number_format() to the line should fix the case of the exact second. Too bad it doesn't feel quite as elegant any more...

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));

http://php.net/manual/en/function.number-format.php


A note on time zones in response to DaVe.

Normally the createFromFormat() method will use the local time zone if one is not specified.

http://php.net/manual/en/datetime.createfromformat.php

However, the technique described here is initialising the DateTime object using microtime() which returns the number of seconds elapsed since the Unix Epoch (01 Jan 1970 00:00:00 GMT).

http://php.net/manual/en/function.microtime.php

This means that the DateTime object is implicitly initialised to UTC, which is fine for server internal tasks that just want to track elapsed time.

If you need to display the time for a particular time zone then you need to set it accordingly. However, this should be done as a separate step after the initialisation (not using the third parameter of createFromFormat()) because of the reasons discussed above.

The setTimeZone() method can be used to accomplish this requirement.

http://php.net/manual/en/datetime.settimezone.php

As an example:

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
echo $now->format("m-d-Y H:i:s.u") . '<br>';

$local = $now->setTimeZone(new DateTimeZone('Australia/Canberra'));
echo $local->format("m-d-Y H:i:s.u") . '<br>';

Produces the following output:

10-29-2015 00:40:09.433818
10-29-2015 11:40:09.433818

Note that if you want to input into mysql, the time format needs to be:

format("Y-m-d H:i:s.u")

Class has been compiled by a more recent version of the Java Environment

For temporary solution just right click on Project => Properties => Java compiler => over there please select compiler compliance level 1.8 => .class compatibility 1.8 => source compatibility 1.8.

Then your code will start to execute on version 1.8.

What is REST? Slightly confused

It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.

REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.

In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."

Worth reading:

How to add items to a spinner in Android?

It's just to clear the adapter, add all itens and notify change like below:

  public void show(List<Object> objLIst) {
    adapter.clear();
    adapter.addAll(objLIst);
    adapter.notifyDataSetChanged(); }

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

XSL xsl:template match="/"

The value of the match attribute of the <xsl:template> instruction must be a match pattern.

Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.

/ in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node().

A match pattern can contain the // abbreviation.

Examples of match patterns:

<xsl:template match="table">

can be applied on any element named table.

<xsl:template match="x/y">

can be applied on any element named y whose parent is an element named x.

<xsl:template match="*">

can be applied to any element.

<xsl:template match="/*">

can be applied only to the top element of an XML document.

<xsl:template match="@*">

can be applied to any attribute.

<xsl:template match="text()">

can be applied to any text node.

<xsl:template match="comment()">

can be applied to any comment node.

<xsl:template match="processing-instruction()">

can be applied to any processing instruction node.

<xsl:template match="node()">

can be applied to any node: element, text, comment or processing instructon.

Linux bash: Multiple variable assignment

Sometimes you have to do something funky. Let's say you want to read from a command (the date example by SDGuero for example) but you want to avoid multiple forks.

read month day year << DATE_COMMAND
 $(date "+%m %d %Y")
DATE_COMMAND
echo $month $day $year

You could also pipe into the read command, but then you'd have to use the variables within a subshell:

day=n/a; month=n/a; year=n/a
date "+%d %m %Y" | { read day month year ; echo $day $month $year; }
echo $day $month $year

results in...

13 08 2013
n/a n/a n/a

E11000 duplicate key error index in mongodb mongoose

mongoDB Atlas has a indexes tab when under their collections tab that allows you to view and delete any index you do not want.

Currency format for display

The problem with taking a given number and displaying it with .ToString("C", culture) is that it effectively changes the amount to the default currency of the given culture. If you have a given amount, the ISO currency code of that amount, and you want to display it for a given culture, I would recommend just creating a decimal extension method like the one below. This will not automatically assume that the currency is in the default currency of the culture:

public static string ToFormattedCurrencyString(
    this decimal currencyAmount,
    string isoCurrencyCode,
CultureInfo userCulture)
{
    var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;

    if (userCurrencyCode == isoCurrencyCode)
    {
        return currencyAmount.ToString("C", userCulture);
    }

    return string.Format(
        "{0} {1}", 
        isoCurrencyCode, 
        currencyAmount.ToString("N2", userCulture));
}

This will either use the local currency symbol or the ISO currency code with the amount -- whichever is more appropriate. More on the topic in this blog post.

How do I run Visual Studio as an administrator by default?

I have always done it by creating a shortcut, which is not really much of a problem. I believe there is no way of doing it otherwise.

Can I use a :before or :after pseudo-element on an input field?

According to a note in the CSS 2.1 spec, the specification “does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” Although input is not really a replaced element any more, the basic situation has not changed: the effect of :before and :after on it in unspecified and generally has no effect.

The solution is to find a different approach to the problem you are trying to address this way. Putting generated content into a text input control would be very misleading: to the user, it would appear to be part of the initial value in the control, but it cannot be modified – so it would appear to be something forced at the start of the control, but yet it would not be submitted as part of form data.

Entity Framework. Delete all rows in table

In EFCore (version i am using is 3.1) you can use the following to remove all rows -

context.Database.ExecuteSqlRaw("TRUNCATE TABLE [TableName]");

jdk7 32 bit windows version to download

As detailed in the Oracle Java SE Support Roadmap

After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive

Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe (64-bit is named jdk-7u80-windows-x64.exe.

Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget to grab the file without signing in.

wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"

how do I set height of container DIV to 100% of window height?

Did you set the CSS:

html, body
{
    height: 100%;
}

You need this to be able to make the div take up all the space. :)

Composer killed while updating

You can try setting preferred-install to "dist" in Composer config.

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

So I figured out a way to do this effectively. For my particular project I'm building an iPad website so I knew exactly what the pixel X/Y value would be to reach the edge of the screen. Your thisX and thisY values will vary.

Since the popovers are being placed by inline styling anyway, I simply grab the left and top values for each link to decide which direction the popover should be. This is done by appending html5 data- values that .popover() uses upon execution.

if ($('.infopoint').length>0){
    $('.infopoint').each(function(){
        var thisX = $(this).css('left').replace('px','');
        var thisY = $(this).css('top').replace('px','');
        if (thisX > 515)
            $(this).attr('data-placement','left');
        if (thisX < 515)
            $(this).attr('data-placement','right');
        if (thisY > 480)
            $(this).attr('data-placement','top');
        if (thisY < 110)
            $(this).attr('data-placement','bottom');
    });
    $('.infopoint').popover({
        trigger:'hover',
        animation: false,
        html: true
    });
}

Any comments/improvements are welcome but this gets the job done if you're willing to put the values in manually.

CAML query with nested ANDs and ORs for multiple fields

You can try U2U Query Builder http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll

I didn't use them but I'm sure it will help you achieving your task.

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

vertical-align: middle with Bootstrap 2

If I remember correctly from my own use of bootstrap, the .spanN classes are floated, which automatically makes them behave as display: block. To make display: table-cell work, you need to remove the float.

set column width of a gridview in asp.net

Set width

HeaderStyle-width

for Example HeaderStyle-width="10%"

node.js Error: connect ECONNREFUSED; response from server

i ran the local mysql database, but not in administrator mode, which threw this error

How to access to the parent object in c#

I wouldn't reference the parent directly in the child objects. In my opinion the childs shouldn't know anything about the parents. This will limits the flexibility!

I would solve this with events/handlers.

public class Meter
{
    private int _powerRating = 0;
    private Production _production;

    public Meter()
    {
        _production = new Production();
        _production.OnRequestPowerRating += new Func<int>(delegate { return _powerRating; });
        _production.DoSomething();
    }
}

public class Production
{
    protected int RequestPowerRating()
    {
        if (OnRequestPowerRating == null)
            throw new Exception("OnRequestPowerRating handler is not assigned");

        return OnRequestPowerRating();
    }

    public void DoSomething()
    {
        int powerRating = RequestPowerRating();
        Debug.WriteLine("The parents powerrating is :" + powerRating);

    }

    public Func<int> OnRequestPowerRating;
}

In this case I solved it with the Func<> generic, but can be done with 'normal' functions. This why the child(Production) is totally independent from it's parent(Meter).


But! If there are too many events/handlers or you just want to pass a parent object, i would solve it with an interface:

public interface IMeter
{
    int PowerRating { get; }
}

public class Meter : IMeter
{
    private int _powerRating = 0;
    private Production _production;

    public Meter()
    {
        _production = new Production(this);
        _production.DoSomething();
    }

    public int PowerRating { get { return _powerRating; } }
}

public class Production
{
    private IMeter _meter;

    public Production(IMeter meter)
    {
        _meter = meter;
    }

    public void DoSomething()
    {
        Debug.WriteLine("The parents powerrating is :" + _meter.PowerRating);
    }
}

This looks pretty much the same as the solution mentions, but the interface could be defined in another assembly and can be implemented by more than 1 class.


Regards, Jeroen van Langen.

How do I build a graphical user interface in C++?

I use FLTK because Qt is not free. I don't choose wxWidgets, because my first test with a simple Hello, World! program produced an executable of 24 MB, FLTK 0.8 MB...

How to show/hide JPanels in a JFrame?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Style1.java
 *
 * Created on May 5, 2011, 6:31:16 AM
 */
package Test;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Sameera
 */
public class Style2 extends javax.swing.JFrame {

    /** Creates new form Style1 */
    public Style2() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        cmd_SH = new javax.swing.JButton();
        pnl_2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        cmd_SH.setText("Hide");
        cmd_SH.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmd_SHActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(558, Short.MAX_VALUE)
                .addComponent(cmd_SH)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(236, Short.MAX_VALUE)
                .addComponent(cmd_SH)
                .addContainerGap())
        );

        pnl_2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout pnl_2Layout = new javax.swing.GroupLayout(pnl_2);
        pnl_2.setLayout(pnl_2Layout);
        pnl_2Layout.setHorizontalGroup(
            pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 621, Short.MAX_VALUE)
        );
        pnl_2Layout.setVerticalGroup(
            pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 270, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnl_2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pnl_2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void cmd_SHActionPerformed(java.awt.event.ActionEvent evt) {                                       


        System.out.println(evt.getActionCommand());
        if (evt.getActionCommand().equals("Hide")) {
            pnl_2.setVisible(false);
            cmd_SH.setText("Show");
            this.setSize(643, 294);
            this.pack();


        }
        if (evt.getActionCommand().equals("Show")) {
            pnl_2.setVisible(true);
            cmd_SH.setText("Hide");
            this.setSize(643, 583);
            this.pack();    
        }
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Style1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton cmd_SH;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel pnl_2;
    // End of variables declaration
}

SSIS Connection Manager Not Storing SQL Password

It happened with me as well and fixed in following way:

Created expression based connection string and saved password in a variable and used it.

How can I find a specific file from a Linux terminal?

Try this (via a shell):

update db
locate index.html

Or:

find /var -iname "index.html"

Replace /var with your best guess as to the directory it is in but avoid starting from /

Drawing in Java using Canvas

Suggestions:

  • Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
  • Instead use a JPanel or JComponent.
  • Don't get your Graphics object by calling getGraphics() on a component as the Graphics object obtained will be transient.
  • Draw in the JPanel's paintComponent() method.
  • All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?

Key tutorial links:

List the queries running on SQL Server

I would suggest querying the sys views. something similar to

SELECT * 
FROM 
   sys.dm_exec_sessions s
   LEFT  JOIN sys.dm_exec_connections c
        ON  s.session_id = c.session_id
   LEFT JOIN sys.dm_db_task_space_usage tsu
        ON  tsu.session_id = s.session_id
   LEFT JOIN sys.dm_os_tasks t
        ON  t.session_id = tsu.session_id
        AND t.request_id = tsu.request_id
   LEFT JOIN sys.dm_exec_requests r
        ON  r.session_id = tsu.session_id
        AND r.request_id = tsu.request_id
   OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) TSQL

This way you can get a TotalPagesAllocated which can help you figure out the spid that is taking all the server resources. There has lots of times when I can't even bring up activity monitor and use these sys views to see what's going on.

I would recommend you reading the following article. I got this reference from here.

jQuery: keyPress Backspace won't fire?

According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (https://api.jquery.com/keypress/)

In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.

jQuery(el).keydown( function() { 
    var that = this; setTimeout( function(){ 
           /** Code that processes backspace, etc. **/ 
     }, 100 );  
 } );

Use Font Awesome Icons in CSS

Consolidating everything above, the following is the final class which works well

   .faArrowIcon {
        position:relative;
    }

    .faArrowIcon:before {
        font-family: FontAwesome;
        top:0;
        left:-5px;
        padding-right:10px;
        content: "\f0a9"; 
    }

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I realise that WayneM has stated he knows that money is specific to SQL Server. However, he is asking if there are any reasons to use money over decimal or vice versa and I think one obvious reason still ought to be stated and that is using decimal means it's one less thing to worry about if you ever have to change your DBMS - which can happen.

Make your systems as flexible as possible!

How to use radio buttons in ReactJS?

Make the radio component as dumb component and pass props to from parent.

import React from "react";

const Radiocomponent = ({ value, setGender }) => ( 
  <div onChange={setGender.bind(this)}>
    <input type="radio" value="MALE" name="gender" defaultChecked={value ==="MALE"} /> Male
    <input type="radio" value="FEMALE" name="gender" defaultChecked={value ==="FEMALE"}/> Female
  </div>
);

export default Radiocomponent;

How do I set up Android Studio to work completely offline?

for a complete offline android studio 3.5.0 installation - you need to download all these below components

android studio, gradle, android gradle plugin and sdk.

here is a detailed step by step Stackoverflow answer for the question

how to install android studio full offline

Correct way to initialize HashMap and can HashMap hold different value types?

The way you're writing it is equivalent to

HashMap<Object, Object> map = new HashMap<Object, Object>();

What goes inside the brackets is you communicating to the compiler what you're going to put in the HashMap so that it can do error checking for you. If Object, Object is what you actually want (probably not) you should explicitly declare it. In general you should be as explicit as you can with the declaration to facilitate error checking by the compiler. What you've described should probably be declared like this:

HashMap<String, Object> map = new HashMap<String, Object>();

That way you at least declare that your keys are going to be strings, but your values can be anything. Just remember to use a cast when you get a value back out.

jQuery selector first td of each row

You can do it like this

_x000D_
_x000D_
$(function(){_x000D_
  $("tr").find("td:eq(0)").css("color","red");_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Html attributes for EditorFor() in ASP.NET MVC

Set the condition using ViewData in the controller

ViewData["Modifiable"] = model.recProcessed;

Then use this viewdata in editor template to set the html attribute of the control

@Html.RadioButton(prefix, li.Value, li.Selected, @ViewData["Modifiable"].ToString().ToLower() == "true" ? (object)new  { @id = li.Value, @disabled = "disabled" } : new { @id = li.Value })

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

You only need the async pipe:

<li *ngFor="let afd of afdeling | async">
    {{afd.patientid}}
</li>

always use the async pipe when dealing with Observables directly without explicitly unsubscribe.

HashMap with multiple values under the same key

No, not just as a HashMap. You'd basically need a HashMap from a key to a collection of values.

If you're happy to use external libraries, Guava has exactly this concept in Multimap with implementations such as ArrayListMultimap and HashMultimap.

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

For .NET Core 2.2, you can use FormattableString for dynamic SQL.

//Assuming this is your dynamic value and this not coming from user input
var tableName = "LogTable"; 
// let's say target date is coming from user input
var targetDate = DateTime.Now.Date.AddDays(-30);
var param = new SqlParameter("@targetDate", targetDate);  
var sql = string.Format("Delete From {0} Where CreatedDate < @targetDate", tableName);
var froamttedSql = FormattableStringFactory.Create(sql, param);
_db.Database.ExecuteSqlCommand(froamttedSql);

What is the difference between a URI, a URL and a URN?

URI is kind of the super class of URL's and URN's. Wikipedia has a fine article about them with links to the right set of RFCs.

grunt: command not found when running from terminal

My fix for this on Mountain Lion was: -

npm install -g grunt-cli 

Saw it on http://gruntjs.com/getting-started

what does numpy ndarray shape do?

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

For Example: 1D ARRAY:

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

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

2D Array:

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

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

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

git recover deleted file where no commit was made after the delete

git checkout HEAD -- client/src/pp_web/index.cljs

Dropping a connected user from an Oracle 10g database schema

Have you tried ALTER SYSTEM KILL SESSION? Get the SID and SERIAL# from V$SESSION for each session in the given schema, then do

ALTER SCHEMA KILL SESSION sid,serial#;

How to embed YouTube videos in PHP?

You can simply create a php input form for Varchar date,give it a varchar length of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.

How can I find which tables reference a given table in Oracle SQL Developer?

I like to do this with a straight SQL query, rather than messing about with the SQL Developer application.

Here's how I just did it. Best to read through this and understand what's going on, so you can tweak it to fit your needs...

WITH all_primary_keys AS (
  SELECT constraint_name AS pk_name,
         table_name
    FROM all_constraints
   WHERE owner = USER
     AND constraint_type = 'P'
)
  SELECT ac.table_name || ' table has a foreign key called ' || upper(ac.constraint_name)
         || ' which references the primary key ' || upper(ac.r_constraint_name) || ' on table ' || apk.table_name AS foreign_keys
    FROM all_constraints ac
         LEFT JOIN all_primary_keys apk
                ON ac.r_constraint_name = apk.pk_name
   WHERE ac.owner = USER
     AND ac.constraint_type = 'R'
     AND ac.table_name = nvl(upper(:table_name), ac.table_name)
ORDER BY ac.table_name, ac.constraint_name
;

Ruby 'require' error: cannot load such file

First :

$ sudo gem install colored2

And,you should input your password

Then :

$ sudo gem update --system  

Appear Updating rubygems-update ERROR: While executing gem ... (OpenSSL::SSL::SSLError) hostname "gems.ruby-china.org" does not match the server certificate

Then:

$  rvm -v
$ rvm get head

Last What language do you want to use?? [ Swift / ObjC ]

ObjC

Would you like to include a demo application with your library? [ Yes / No ]

Yes

Which testing frameworks will you use? [ Specta / Kiwi / None ]

None

Would you like to do view based testing? [ Yes / No ]

No

What is your class prefix?

XMG

Running pod install on your new library.

Determining Referer in PHP

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

Why use prefixes on member variables in C++ classes

You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example:

_Foo

_L

are all reserved words while

_foo

_l

are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found the _L happened to be reserved by Visual C++ 2005 and the clash created some unexpected results.

I am on the fence about how useful it is to mark up local variables.

Here is a link about which identifiers are reserved: What are the rules about using an underscore in a C++ identifier?

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

I have the same error on amazon AMI linux.

I Solved by setting curl.cainfo on /etc/php.d/curl.ini

https://gist.github.com/reinaldomendes/97fb2ce8a606ec813c4b

Addition October 2018

On Amazon Linux v1 edit this file

vi /etc/php.d/20-curl.ini

To add this line

curl.cainfo="/etc/ssl/certs/ca-bundle.crt"

Is a Java hashmap search really O(1)?

I know this is an old question, but there's actually a new answer to it.

You're right that a hash map isn't really O(1), strictly speaking, because as the number of elements gets arbitrarily large, eventually you will not be able to search in constant time (and O-notation is defined in terms of numbers that can get arbitrarily large).

But it doesn't follow that the real time complexity is O(n)--because there's no rule that says that the buckets have to be implemented as a linear list.

In fact, Java 8 implements the buckets as TreeMaps once they exceed a threshold, which makes the actual time O(log n).

Checking whether a String contains a number value in Java

 try{
      Integer.parseInt(string);
      return true;
}catch (Exception  e){
      return false;
}

or you can do it himself:

 for ( int i = 0; i < string.length; ++i ) {
      if ( !( string[i] >= '0' || string[i] <= '9' ) )
           return false;
 }
 return true;

Of course is also function isDigit

Bootstrap 3 Multi-column within a single ul not floating properly

Thanks, Varun Rathore. It works perfectly!

For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:

<ul class="list-group row">
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>

PHPMailer AddAddress()

All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:

See it in action with jsfiddle here (except the php processor)

### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
    var nextEmail, inside_where;
    nextEmail = document.createElement('input');
    nextEmail.type = 'text';
    nextEmail.name = 'emails[]';
    nextEmail.className = 'class_for_styling';
    nextEmail.style.display = 'block';
    nextEmail.placeholder  = 'Enter E-mail Here';
    inside_where = document.getElementById('addEmail');
    inside_where.appendChild(nextEmail);
    return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
    foreach ($_POST[emails] AS $postEmail){
        if ($postEmail){$mailer->AddAddress($postEmail);}
    }
} 
?>

So what it does basically is to generate a new input text box on every click with the name "emails[]".

The [] added at the end makes it an array when posted.

Then we go through each element of the array with "foreach" on PHP side adding the:

    $mailer->AddAddress($postEmail);

Get the current script file name

$filename = "jquery.js.php";
$ext = pathinfo($filename, PATHINFO_EXTENSION);//will output: php
$file_basename = pathinfo($filename, PATHINFO_FILENAME);//will output: jquery.js

Pagination on a list using ng-repeat

If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.

Here's a simple pagination example: http://jsfiddle.net/2ZzZB/56/

That example was on the list of fiddles on the angular.js github wiki, which should be helpful: https://github.com/angular/angular.js/wiki/JsFiddle-Examples

EDIT: http://jsfiddle.net/2ZzZB/16/ to http://jsfiddle.net/2ZzZB/56/ (won't show "1/4.5" if there is 45 results)

How to get the url parameters using AngularJS

While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location service, as injected in your own service or controller:

var paramValue = $location.search().myParam; 

This simple syntax will work for http://example.com/path?myParam=paramValue. However, only if you configured the $locationProvider in the HTML 5 mode before:

$locationProvider.html5Mode(true);

Otherwise have a look at the http://example.com/#!/path?myParam=someValue "Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.

bash echo number of lines of file given in a bash variable without the file name

You can also use awk:

awk 'END {print NR,"lines"}' filename

Or

awk 'END {print NR}' filename

How to get all options in a drop-down list by Selenium WebDriver using C#?

It seems to be a cast exception. Can you try converting your result to a list i.e. elem.findElements(xx).toList ?

How to input matrix (2D list) in Python?

If the input is formatted like this,

1 2 3
4 5 6
7 8 9

a one liner can be used

mat = [list(map(int,input().split())) for i in range(row)]

Using ls to list directories and their total sizes

ncdu (ncurses du)

This awesome CLI utility allows you to easily find the large files and directories (recursive total size) interactively.

For example, from inside the root of a well known open source project we do:

sudo apt install ncdu
ncdu

The outcome its:

enter image description here

Then, I enter down and right on my keyboard to go into the /drivers folder, and I see:

enter image description here

ncdu only calculates file sizes recursively once at startup for the entire tree, so it is efficient.

"Total disk usage" vs "Apparent size" is analogous to du, and I have explained it at: why is the output of `du` often so different from `du -b`

Project homepage: https://dev.yorhel.nl/ncdu

Related questions:

Tested in Ubuntu 16.04.

Ubuntu list root

You likely want:

ncdu --exclude-kernfs -x /

where:

  • -x stops crossing of filesystem barriers
  • --exclude-kernfs skips special filesystems like /sys

MacOS 10.15.5 list root

To properly list root / on that system, I also needed --exclude-firmlinks, e.g.:

brew install ncdu
cd /
ncdu --exclude-firmlinks

otherwise it seemed to go into some link infinite loop, likely due to: https://www.swiftforensics.com/2019/10/macos-1015-volumes-firmlink-magic.html

The things we learn for love.

ncdu non-interactive usage

Another cool feature of ncdu is that you can first dump the sizes in a JSON format, and later reuse them.

For example, to generate the file run:

ncdu -o ncdu.json

and then examine it interactively with:

ncdu -f ncdu.json

This is very useful if you are dealing with a very large and slow filesystem like NFS.

This way, you can first export only once, which can take hours, and then explore the files, quit, explore again, etc.

The output format is just JSON, so it is easy to reuse it with other programs as well, e.g.:

ncdu -o -  | python -m json.tool | less

reveals a simple directory tree data structure:

[
    1,
    0,
    {
        "progname": "ncdu",
        "progver": "1.12",
        "timestamp": 1562151680
    },
    [
        {
            "asize": 4096,
            "dev": 2065,
            "dsize": 4096,
            "ino": 9838037,
            "name": "/work/linux-kernel-module-cheat/submodules/linux"
        },
        {
            "asize": 1513,
            "dsize": 4096,
            "ino": 9856660,
            "name": "Kbuild"
        },
        [
            {
                "asize": 4096,
                "dsize": 4096,
                "ino": 10101519,
                "name": "net"
            },
            [
                {
                    "asize": 4096,
                    "dsize": 4096,
                    "ino": 11417591,
                    "name": "l2tp"
                },
                {
                    "asize": 48173,
                    "dsize": 49152,
                    "ino": 11418744,
                    "name": "l2tp_core.c"
                },

Tested in Ubuntu 18.04.

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

Java: how to add image to Jlabel?

Simple code that you can write in main(String[] args) function

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame
    frame.setSize(800,600);
    frame.setLocation(200,200);

    JFileChooser fc = new JFileChooser();
    if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
        BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception
        JLabel label = new JLabel();
        label.setIcon(new ImageIcon(img));
        frame.getContentPane().add(label);
    }

    frame.setVisible(true);//showing up the frame

Elegant Python function to convert CamelCase to snake_case?

A horrendous example using regular expressions (you could easily clean this up :) ):

def f(s):
    return s.group(1).lower() + "_" + s.group(2).lower()

p = re.compile("([A-Z]+[a-z]+)([A-Z]?)")
print p.sub(f, "CamelCase")
print p.sub(f, "getHTTPResponseCode")

Works for getHTTPResponseCode though!

Alternatively, using lambda:

p = re.compile("([A-Z]+[a-z]+)([A-Z]?)")
print p.sub(lambda x: x.group(1).lower() + "_" + x.group(2).lower(), "CamelCase")
print p.sub(lambda x: x.group(1).lower() + "_" + x.group(2).lower(), "getHTTPResponseCode")

EDIT: It should also be pretty easy to see that there's room for improvement for cases like "Test", because the underscore is unconditionally inserted.

Rails 4 - passing variable to partial

Syntactically a little different but it looks cleaner in my opinion:

render 'my_partial', locals: { title: "My awesome title" }

# not a big fan of the arrow key syntax
render 'my_partial', :locals => { :title => "My awesome title" }

Remove Datepicker Function dynamically

You can try the enable/disable methods instead of using the option method:

$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");

This disables the entire textbox. So may be you can use datepicker.destroy() instead:

$(document).ready(function() {
    $("#ddlSearchType").change(function() {
        if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
            $("#txtSearch").datepicker();
        }
        else {
            $("#txtSearch").datepicker("destroy");
        }
    }).change();
});

Demo here.

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

jQuery add image inside of div tag

$("#theDiv").append("<img id='theImg' src='theImg.png'/>");

You need to read the documentation here.

Create new user in MySQL and give it full access to one database

To create a user and grant all privileges on a database.

Log in to MySQL:

mysql -u root

Now create and grant

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

Anonymous user (for local testing only)

Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:

GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'

Be aware

This is fine for junk data in development. Don't do this with anything you care about.

Element-wise addition of 2 lists?

[list1[i] + list2[i] for i in range(len(list1))]

How do I repair an InnoDB table?

Note: If your issue is, "innodb index is marked as corrupted"! Then, the simple solution can be, just remove the indexes and add them again. That can solve pretty quickly without losing any records nor restarting or moving table contents into a temporary table and back.

what is the difference between json and xml

They are two formats of representation of information. While JSON was designed to be more compact, XML was design to be more readable.

ToString() function in Go

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Playground: http://play.golang.org/p/Azql7_pDAA


Output

101010

PHP foreach with Nested Array?

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

How do you create different variable names while in a loop?

Don't do this use a dictionary

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, 'string%s' % x, 'Hello')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

don't do this use a dict

globals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from globals() is not a good idea

How to watch for array changes?

There are a few options...

1. Override the push method

Going the quick and dirty route, you could override the `push()` method for your array1:
Object.defineProperty(myArray, "push", {
  enumerable: false, // hide from for...in
  configurable: false, // prevent further meddling...
  writable: false, // see above ^
  value: function () {
    for (var i = 0, n = this.length, l = arguments.length; i < l; i++, n++) {          
      RaiseMyEvent(this, n, this[n] = arguments[i]); // assign/raise your event
    }
    return n;
  }
});

1 Alternatively, if you'd like to target all arrays, you could override Array.prototype.push(). Use caution, though; other code in your environment may not like or expect that kind of modification. Still, if a catch-all sounds appealing, just replace myArray with Array.prototype.

Now, that's just one method and there are lots of ways to change array content. We probably need something more comprehensive...

2. Create a custom observable array

Rather than overriding methods, you could create your own observable array. This particular implementation copies an array into a new array-like object and provides custom `push()`, `pop()`, `shift()`, `unshift()`, `slice()`, and `splice()` methods **as well as** custom index accessors (provided that the array size is only modified via one of the aforementioned methods or the `length` property).

_x000D_
_x000D_
function ObservableArray(items) {
  var _self = this,
    _array = [],
    _handlers = {
      itemadded: [],
      itemremoved: [],
      itemset: []
    };

  function defineIndexProperty(index) {
    if (!(index in _self)) {
      Object.defineProperty(_self, index, {
        configurable: true,
        enumerable: true,
        get: function() {
          return _array[index];
        },
        set: function(v) {
          _array[index] = v;
          raiseEvent({
            type: "itemset",
            index: index,
            item: v
          });
        }
      });
    }
  }

  function raiseEvent(event) {
    _handlers[event.type].forEach(function(h) {
      h.call(_self, event);
    });
  }

  Object.defineProperty(_self, "addEventListener", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function(eventName, handler) {
      eventName = ("" + eventName).toLowerCase();
      if (!(eventName in _handlers)) throw new Error("Invalid event name.");
      if (typeof handler !== "function") throw new Error("Invalid handler.");
      _handlers[eventName].push(handler);
    }
  });

  Object.defineProperty(_self, "removeEventListener", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function(eventName, handler) {
      eventName = ("" + eventName).toLowerCase();
      if (!(eventName in _handlers)) throw new Error("Invalid event name.");
      if (typeof handler !== "function") throw new Error("Invalid handler.");
      var h = _handlers[eventName];
      var ln = h.length;
      while (--ln >= 0) {
        if (h[ln] === handler) {
          h.splice(ln, 1);
        }
      }
    }
  });

  Object.defineProperty(_self, "push", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function() {
      var index;
      for (var i = 0, ln = arguments.length; i < ln; i++) {
        index = _array.length;
        _array.push(arguments[i]);
        defineIndexProperty(index);
        raiseEvent({
          type: "itemadded",
          index: index,
          item: arguments[i]
        });
      }
      return _array.length;
    }
  });

  Object.defineProperty(_self, "pop", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function() {
      if (_array.length > -1) {
        var index = _array.length - 1,
          item = _array.pop();
        delete _self[index];
        raiseEvent({
          type: "itemremoved",
          index: index,
          item: item
        });
        return item;
      }
    }
  });

  Object.defineProperty(_self, "unshift", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function() {
      for (var i = 0, ln = arguments.length; i < ln; i++) {
        _array.splice(i, 0, arguments[i]);
        defineIndexProperty(_array.length - 1);
        raiseEvent({
          type: "itemadded",
          index: i,
          item: arguments[i]
        });
      }
      for (; i < _array.length; i++) {
        raiseEvent({
          type: "itemset",
          index: i,
          item: _array[i]
        });
      }
      return _array.length;
    }
  });

  Object.defineProperty(_self, "shift", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function() {
      if (_array.length > -1) {
        var item = _array.shift();
        delete _self[_array.length];
        raiseEvent({
          type: "itemremoved",
          index: 0,
          item: item
        });
        return item;
      }
    }
  });

  Object.defineProperty(_self, "splice", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function(index, howMany /*, element1, element2, ... */ ) {
      var removed = [],
          item,
          pos;

      index = index == null ? 0 : index < 0 ? _array.length + index : index;

      howMany = howMany == null ? _array.length - index : howMany > 0 ? howMany : 0;

      while (howMany--) {
        item = _array.splice(index, 1)[0];
        removed.push(item);
        delete _self[_array.length];
        raiseEvent({
          type: "itemremoved",
          index: index + removed.length - 1,
          item: item
        });
      }

      for (var i = 2, ln = arguments.length; i < ln; i++) {
        _array.splice(index, 0, arguments[i]);
        defineIndexProperty(_array.length - 1);
        raiseEvent({
          type: "itemadded",
          index: index,
          item: arguments[i]
        });
        index++;
      }

      return removed;
    }
  });

  Object.defineProperty(_self, "length", {
    configurable: false,
    enumerable: false,
    get: function() {
      return _array.length;
    },
    set: function(value) {
      var n = Number(value);
      var length = _array.length;
      if (n % 1 === 0 && n >= 0) {        
        if (n < length) {
          _self.splice(n);
        } else if (n > length) {
          _self.push.apply(_self, new Array(n - length));
        }
      } else {
        throw new RangeError("Invalid array length");
      }
      _array.length = n;
      return value;
    }
  });

  Object.getOwnPropertyNames(Array.prototype).forEach(function(name) {
    if (!(name in _self)) {
      Object.defineProperty(_self, name, {
        configurable: false,
        enumerable: false,
        writable: false,
        value: Array.prototype[name]
      });
    }
  });

  if (items instanceof Array) {
    _self.push.apply(_self, items);
  }
}

(function testing() {

  var x = new ObservableArray(["a", "b", "c", "d"]);

  console.log("original array: %o", x.slice());

  x.addEventListener("itemadded", function(e) {
    console.log("Added %o at index %d.", e.item, e.index);
  });

  x.addEventListener("itemset", function(e) {
    console.log("Set index %d to %o.", e.index, e.item);
  });

  x.addEventListener("itemremoved", function(e) {
    console.log("Removed %o at index %d.", e.item, e.index);
  });
 
  console.log("popping and unshifting...");
  x.unshift(x.pop());

  console.log("updated array: %o", x.slice());

  console.log("reversing array...");
  console.log("updated array: %o", x.reverse().slice());

  console.log("splicing...");
  x.splice(1, 2, "x");
  console.log("setting index 2...");
  x[2] = "foo";

  console.log("setting length to 10...");
  x.length = 10;
  console.log("updated array: %o", x.slice());

  console.log("setting length to 2...");
  x.length = 2;

  console.log("extracting first element via shift()");
  x.shift();

  console.log("updated array: %o", x.slice());

})();
_x000D_
_x000D_
_x000D_

See Object.defineProperty() for reference.

That gets us closer but it's still not bullet proof... which brings us to:

3. Proxies

A Proxy object offers another solution to the modern browser. It allows you to intercept method calls, accessors, etc. Most importantly, you can do this without even providing an explicit property name... which would allow you to test for an arbitrary, index-based access/assignment. You can even intercept property deletion. Proxies would effectively allow you to inspect a change before deciding to allow it... in addition to handling the change after the fact.

Here's a stripped down sample:

_x000D_
_x000D_
(function() {

  if (!("Proxy" in window)) {
    console.warn("Your browser doesn't support Proxies.");
    return;
  }

  // our backing array
  var array = ["a", "b", "c", "d"];

  // a proxy for our array
  var proxy = new Proxy(array, {
    apply: function(target, thisArg, argumentsList) {
      return thisArg[target].apply(this, argumentList);
    },
    deleteProperty: function(target, property) {
      console.log("Deleted %s", property);
      return true;
    },
    set: function(target, property, value, receiver) {      
      target[property] = value;
      console.log("Set %s to %o", property, value);
      return true;
    }
  });

  console.log("Set a specific index..");
  proxy[0] = "x";

  console.log("Add via push()...");
  proxy.push("z");

  console.log("Add/remove via splice()...");
  proxy.splice(1, 3, "y");

  console.log("Current state of array: %o", array);

})();
_x000D_
_x000D_
_x000D_

Python concatenate text files

I don't know about elegance, but this works:

    import glob
    import os
    for f in glob.glob("file*.txt"):
         os.system("cat "+f+" >> OutFile.txt")

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

Fill in the service layer with the model and then send it to the view. For example: ViewItem=ModelItem.ToString().Substring(0,100);

iterating quickly through list of tuples

I think that you can use

for j,k in my_list:
  [ ... stuff ... ]

I need to round a float to two decimal places in Java

If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:

double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);

Which will output (depending on locale):

$2.30

Also, if currency isn't required (just the exact two decimal places) you can use this instead:

NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);

Which will output 2.30

bundle install fails with SSL certificate verification error

My permanent fix for Windows:

  1. Download the CACert , save as C:\ruby\ssl_certs\GlobalSignRootCA.pem from http://guides.rubygems.org/ssl-certificate-update/

  2. Create system variable named "SSL_CERT_FILE", set to C:\ruby\ssl_certs\GlobalSignRootCA.pem.

  3. Try again: gem install bundler:

C:\gem sources
*** CURRENT SOURCES ***
https://rubygems.org/

C:\gem install bundler
Fetching: bundler-1.13.5.gem (100%)
Successfully installed bundler-1.13.5
1 gem installed

How to retrieve checkboxes values in jQuery

Here's one that works (see the example):

 function updateTextArea() {         
     var allVals = [];
     $('#c_b :checked').each(function() {
       allVals.push($(this).val());
     });
     $('#t').val(allVals);
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });

Update

Some number of months later another question was asked in regards to how to keep the above working if the ID changes. Well, the solution boils down to mapping the updateTextArea function into something generic that uses CSS classes, and to use the live function to monitor the DOM for those changes.

What are OLTP and OLAP. What is the difference between them?

OLTP: It stands for OnLine Transaction Processing and is used for managing current day to day data information.
OLAP: It stands for OnLine Analytical Processing and is used to maintain the past history of data and mainly used for data analysis, it can also be referred to as warehouse.

Difference Between Cohesion and Coupling

I think the differences can be put as the following:

  • Cohesion represents the degree to which a part of a code base forms a logically single, atomic unit.
  • Coupling represents the degree to which a single unit is independent from others.
  • It’s impossible to archive full decoupling without damaging cohesion, and vice versa.

In this blog post I write about it in more detail.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

An addition to the other answers that didn't work for me: In my case the error occurred due to permission errors. The project got deployed while the tomcat was running as root, later when started as tomcat user I got the error from the question title.

Solution in my case was to set the right permissions, e.x. on a unix system:

cd <tomcat-dir>
chown -R <tomcat-user> *

How can I find where Python is installed on Windows?

If you have Python in your environment variable then you can use the following command in cmd:

 where python

or for Unix enviroment

 which python

command line image :

enter image description here

Change values of select box of "show 10 entries" of jquery datatable

If you want to use 'lengthMenu' together with buttons(copy, export), you have to use this option dom: 'lBfrtip'. Here https://datatables.net/reference/option/dom you can find meaning of each symbol. For example, if you will use like this 'Bfrtip', lengthMenu will not appears.

MySQL load NULL values from CSV data

This will do what you want. It reads the fourth field into a local variable, and then sets the actual field value to NULL, if the local variable ends up containing an empty string:

LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(one, two, three, @vfour, five)
SET four = NULLIF(@vfour,'')
;

If they're all possibly empty, then you'd read them all into variables and have multiple SET statements, like this:

LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(@vone, @vtwo, @vthree, @vfour, @vfive)
SET
one = NULLIF(@vone,''),
two = NULLIF(@vtwo,''),
three = NULLIF(@vthree,''),
four = NULLIF(@vfour,'')
;

Custom fonts and XML layouts (Android)

Old question, but I sure wish I read this answer here before I started my own search for a good solution. Calligraphy extends the android:fontFamily attribute to add support for custom fonts in your asset folder, like so:

<TextView 
  android:text="@string/hello_world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:fontFamily="fonts/Roboto-Bold.ttf"/>

The only thing you have to do to activate it is attaching it to the Context of the Activity you're using:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}

You can also specify your own custom attribute to replace android:fontFamily

It also works in themes, including the AppTheme.

Frame Buster Buster ... buster code needed

I might just have just gotten a way to bust the frame buster buster javascript. Using the getElementsByName in my javascript function, i've set a loop between the frame buster and the actual frame buster buster script. check this post out. http://www.phcityonweb.com/frame-buster-buster-buster-2426

Regular expression for a hexadecimal number?

Just for the record I would specify the following:

/^[xX]?[0-9a-fA-F]{6}$/

Which differs in that it checks that it has to contain the six valid characters and on lowercase or uppercase x in case we have one.

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Algorithm for solving Sudoku

There are four steps to solve a sudoku puzzle:

  1. Identify all possibilities for each cell (getting from the row, column and box) and try to develop a possible matrix. 2.Check for double pair, if it exists then remove these two values from all the cells in that row/column/box, wherever the pair exists If any cell is having single possiblity then assign that run step 1 again
  2. Check for each cell with each row, column and box. If the cell has one value which does not belong in the other possible values then assign that value to that cell. run step 1 again
  3. If the sudoku is still not solved, then we need to start the following assumption, Assume the first possible value and assign. Then run step 1–3 If still not solved then do it for next possible value and run it in recursion.
  4. If the sudoku is still not solved, then we need to start the following assumption, Assume the first possible value and assign. Then run step 1–3

If still not solved then do it for next possible value and run it in recursion.

import math
import sys


def is_solved(l):
    for x, i in enumerate(l):
        for y, j in enumerate(i):
            if j == 0:
                # Incomplete
                return None
            for p in range(9):
                if p != x and j == l[p][y]:
                    # Error
                    print('horizontal issue detected!', (x, y))
                    return False
                if p != y and j == l[x][p]:
                    # Error
                    print('vertical issue detected!', (x, y))
                    return False
            i_n, j_n = get_box_start_coordinate(x, y)
            for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
                           if (p, q) != (x, y) and j == l[p][q]]:
                    # Error
                print('box issue detected!', (x, y))
                return False
    # Solved
    return True


def is_valid(l):
    for x, i in enumerate(l):
        for y, j in enumerate(i):
            if j != 0:
                for p in range(9):
                    if p != x and j == l[p][y]:
                        # Error
                        print('horizontal issue detected!', (x, y))
                        return False
                    if p != y and j == l[x][p]:
                        # Error
                        print('vertical issue detected!', (x, y))
                        return False
                i_n, j_n = get_box_start_coordinate(x, y)
                for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
                               if (p, q) != (x, y) and j == l[p][q]]:
                        # Error
                    print('box issue detected!', (x, y))
                    return False
    # Solved
    return True


def get_box_start_coordinate(x, y):
    return 3 * int(math.floor(x/3)), 3 * int(math.floor(y/3))


def get_horizontal(x, y, l):
    return [l[x][i] for i in range(9) if l[x][i] > 0]


def get_vertical(x, y, l):
    return [l[i][y] for i in range(9) if l[i][y] > 0]


def get_box(x, y, l):
    existing = []
    i_n, j_n = get_box_start_coordinate(x, y)
    for (i, j) in [(i, j) for i in range(i_n, i_n + 3) for j in range(j_n, j_n + 3)]:
        existing.append(l[i][j]) if l[i][j] > 0 else None
    return existing


def detect_and_simplify_double_pairs(l, pl):
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if len(pl[i][j]) == 2]:
        temp_pair = pl[i][j]
        for p in (p for p in range(j+1, 9) if len(pl[i][p]) == 2 and len(set(pl[i][p]) & set(temp_pair)) == 2):
            for q in (q for q in range(9) if q != j and q != p):
                pl[i][q] = list(set(pl[i][q]) - set(temp_pair))
                if len(pl[i][q]) == 1:
                    l[i][q] = pl[i][q].pop()
                    return True
        for p in (p for p in range(i+1, 9) if len(pl[p][j]) == 2 and len(set(pl[p][j]) & set(temp_pair)) == 2):
            for q in (q for q in range(9) if q != i and p != q):
                pl[q][j] = list(set(pl[q][j]) - set(temp_pair))
                if len(pl[q][j]) == 1:
                    l[q][j] = pl[q][j].pop()
                    return True
        i_n, j_n = get_box_start_coordinate(i, j)
        for (a, b) in [(a, b) for a in range(i_n, i_n+3) for b in range(j_n, j_n+3)
                       if (a, b) != (i, j) and len(pl[a][b]) == 2 and len(set(pl[a][b]) & set(temp_pair)) == 2]:
            for (c, d) in [(c, d) for c in range(i_n, i_n+3) for d in range(j_n, j_n+3)
                           if (c, d) != (a, b) and (c, d) != (i, j)]:
                pl[c][d] = list(set(pl[c][d]) - set(temp_pair))
                if len(pl[c][d]) == 1:
                    l[c][d] = pl[c][d].pop()
                    return True
    return False


def update_unique_horizontal(x, y, l, pl):
    tl = pl[x][y]
    for i in (i for i in range(9) if i != y):
        tl = list(set(tl) - set(pl[x][i]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def update_unique_vertical(x, y, l, pl):
    tl = pl[x][y]
    for i in (i for i in range(9) if i != x):
        tl = list(set(tl) - set(pl[i][y]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def update_unique_box(x, y, l, pl):
    tl = pl[x][y]
    i_n, j_n = get_box_start_coordinate(x, y)
    for (i, j) in [(i, j) for i in range(i_n, i_n+3) for j in range(j_n, j_n+3) if (i, j) != (x, y)]:
        tl = list(set(tl) - set(pl[i][j]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def find_and_place_possibles(l):
    while True:
        pl = populate_possibles(l)
        if pl != False:
            return pl


def populate_possibles(l):
    pl = [[[]for j in i] for i in l]
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
        p = list(set(range(1, 10)) - set(get_horizontal(i, j, l) +
                                         get_vertical(i, j, l) + get_box(i, j, l)))
        if len(p) == 1:
            l[i][j] = p.pop()
            return False
        else:
            pl[i][j] = p
    return pl


def find_and_remove_uniques(l, pl):
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
        if update_unique_horizontal(i, j, l, pl) == True:
            return True
        if update_unique_vertical(i, j, l, pl) == True:
            return True
        if update_unique_box(i, j, l, pl) == True:
            return True
    return False


def try_with_possibilities(l):
    while True:
        improv = False
        pl = find_and_place_possibles(l)
        if detect_and_simplify_double_pairs(
                l, pl) == True:
            continue
        if find_and_remove_uniques(
                l, pl) == True:
            continue
        if improv == False:
            break
    return pl


def get_first_conflict(pl):
    for (x, y) in [(x, y) for x, i in enumerate(pl) for y, j in enumerate(i) if len(j) > 0]:
        return (x, y)


def get_deep_copy(l):
    new_list = [i[:] for i in l]
    return new_list


def run_assumption(l, pl):
    try:
        c = get_first_conflict(pl)
        fl = pl[c[0]
                ][c[1]]
        # print('Assumption Index : ', c)
        # print('Assumption List: ',  fl)
    except:
        return False
    for i in fl:
        new_list = get_deep_copy(l)
        new_list[c[0]][c[1]] = i
        new_pl = try_with_possibilities(new_list)
        is_done = is_solved(new_list)
        if is_done == True:
            l = new_list
            return new_list
        else:
            new_list = run_assumption(new_list, new_pl)
            if new_list != False and is_solved(new_list) == True:
                return new_list
    return False


if __name__ == "__main__":
    l = [
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 8, 0, 0, 0, 0, 4, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 6, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [2, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 2, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]
    ]
    # This puzzle copied from Hacked rank test case
    if is_valid(l) == False:
        print("Sorry! Invalid.")
        sys.exit()
    pl = try_with_possibilities(l)
    is_done = is_solved(l)
    if is_done == True:
        for i in l:
            print(i)
        print("Solved!!!")
        sys.exit()

    print("Unable to solve by traditional ways")
    print("Starting assumption based solving")
    new_list = run_assumption(l, pl)
    if new_list != False:
        is_done = is_solved(new_list)
        print('is solved ? - ', is_done)
        for i in new_list:
            print(i)
        if is_done == True:
            print("Solved!!! with assumptions.")
        sys.exit()
    print(l)
    print("Sorry! No Solution. Need to fix the valid function :(")
    sys.exit()

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

db.collection.update(  { _id:...} , { $set: { some_key : new_info  } } 

to

db.collection.update( { _id: ..} , { $set: { some_key: { param1: newValue} } } ); 

Hope this help!

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

How to escape a single quote inside awk

For small scripts an optional way to make it readable is to use a variable like this:

awk -v fmt="'%s'\n" '{printf fmt, $1}'

I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

Just run below command with admin access

npm install --global --production windows-build-tools

"The Controls collection cannot be modified because the control contains code blocks"

Keep the java script code inside the body tag

<body> 
   <script type="text/javascript">
   </script>
</body>

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

How to change value of a request parameter in laravel

If you need to customize the request

$data = $request->all();

you can pass the name of the field and the value

$data['product_ref_code'] = 1650;

and finally pass the new request

$last = Product::create($data);

Changing the URL in react-router v4 without using Redirect or Link

React Router v4

There's a couple of things that I needed to get this working smoothly.

The doc page on auth workflow has quite a lot of what is required.

However I had three issues

  1. Where does the props.history come from?
  2. How do I pass it through to my component which isn't directly inside the Route component
  3. What if I want other props?

I ended up using:

  1. option 2 from an answer on 'Programmatically navigate using react router' - i.e. to use <Route render> which gets you props.history which can then be passed down to the children.
  2. Use the render={routeProps => <MyComponent {...props} {routeProps} />} to combine other props from this answer on 'react-router - pass props to handler component'

N.B. With the render method you have to pass through the props from the Route component explicitly. You also want to use render and not component for performance reasons (component forces a reload every time).

const App = (props) => (
    <Route 
        path="/home" 
        render={routeProps => <MyComponent {...props} {...routeProps}>}
    />
)

const MyComponent = (props) => (
    /**
     * @link https://reacttraining.com/react-router/web/example/auth-workflow
     * N.B. I use `props.history` instead of `history`
     */
    <button onClick={() => {
        fakeAuth.signout(() => props.history.push('/foo'))
    }}>Sign out</button>
)

One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match }) i.e. Object destructuring, which meant initially I didn't realise that Route passes down three props, match, location and history

I think some of the other answers here are assuming that everything is done via JavaScript classes.

Here's an example, plus if you don't need to pass any props through you can just use component

class App extends React.Component {
    render () {
        <Route 
            path="/home" 
            component={MyComponent}
        />
    }
}

class MyComponent extends React.Component {
    render () {
        /**
         * @link https://reacttraining.com/react-router/web/example/auth-workflow
         * N.B. I use `props.history` instead of `history`
         */
        <button onClick={() => {
            this.fakeAuth.signout(() => this.props.history.push('/foo'))
        }}>Sign out</button>
    }
}

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Using an attribute of the current class instance as a default value for method's parameter

Default value for parameters are evaluated at "compilation", once. So obviously you can't access self. The classic example is list as default parameter. If you add elements into it, the default value for the parameter changes!

The workaround is to use another default parameter, typically None, and then check and update the variable.

How do I get which JRadioButton is selected from a ButtonGroup

You can put and actionCommand to each radio button (string).

this.jButton1.setActionCommand("dog");
this.jButton2.setActionCommand("cat");
this.jButton3.setActionCommand("bird");

Assuming they're already in a ButtonGroup (state_group in this case) you can get the selected radio button like this:

String selection = this.state_group.getSelection().getActionCommand();

Hope this helps

Convert String (UTF-16) to UTF-8 in C#

A string in C# is always UTF-16, there is no way to "convert" it. The encoding is irrelevant as long as you manipulate the string in memory, it only matters if you write the string to a stream (file, memory stream, network stream...).

If you want to write the string to a XML file, just specify the encoding when you create the XmlWriter

What is the 'open' keyword in Swift?

open is only for another module for example: cocoa pods, or unit test, we can inherit or override

Target WSGI script cannot be loaded as Python module

I had the same error

Target WSGI script cannot be loaded as Python module

This was because the python path was not added in the apache.conf

Depending on the Apache and Ubuntu version you need to update the apache.conf or httpd.conf file with the pythonWSGIPath

In my case I need to edit the apache.conf

sudo nano /etc/apache2/apache2.conf

Then add the following line at the end (Change the my_project to the project your project name)

WSGIPythonPath /var/www/my_project

And everything works with charm