Programs & Examples On #Data retrieval

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

python - if not in list

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item

jQuery: print_r() display equivalent?

How about something like:

<script src='http://code.jquery.com/jquery-latest.js'></script>

function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;'); }

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

ORA-01000, the maximum-open-cursors error, is an extremely common error in Oracle database development. In the context of Java, it happens when the application attempts to open more ResultSets than there are configured cursors on a database instance.

Common causes are:

  1. Configuration mistake

    • You have more threads in your application querying the database than cursors on the DB. One case is where you have a connection and thread pool larger than the number of cursors on the database.
    • You have many developers or applications connected to the same DB instance (which will probably include many schemas) and together you are using too many connections.
    • Solution:

  2. Cursor leak

    • The applications is not closing ResultSets (in JDBC) or cursors (in stored procedures on the database)
    • Solution: Cursor leaks are bugs; increasing the number of cursors on the DB simply delays the inevitable failure. Leaks can be found using static code analysis, JDBC or application-level logging, and database monitoring.

Background

This section describes some of the theory behind cursors and how JDBC should be used. If you don't need to know the background, you can skip this and go straight to 'Eliminating Leaks'.

What is a cursor?

A cursor is a resource on the database that holds the state of a query, specifically the position where a reader is in a ResultSet. Each SELECT statement has a cursor, and PL/SQL stored procedures can open and use as many cursors as they require. You can find out more about cursors on Orafaq.

A database instance typically serves several different schemas, many different users each with multiple sessions. To do this, it has a fixed number of cursors available for all schemas, users and sessions. When all cursors are open (in use) and request comes in that requires a new cursor, the request fails with an ORA-010000 error.

Finding and setting the number of cursors

The number is normally configured by the DBA on installation. The number of cursors currently in use, the maximum number and the configuration can be accessed in the Administrator functions in Oracle SQL Developer. From SQL it can be set with:

ALTER SYSTEM SET OPEN_CURSORS=1337 SID='*' SCOPE=BOTH;

Relating JDBC in the JVM to cursors on the DB

The JDBC objects below are tightly coupled to the following database concepts:

  • JDBC Connection is the client representation of a database session and provides database transactions. A connection can have only a single transaction open at any one time (but transactions can be nested)
  • A JDBC ResultSet is supported by a single cursor on the database. When close() is called on the ResultSet, the cursor is released.
  • A JDBC CallableStatement invokes a stored procedure on the database, often written in PL/SQL. The stored procedure can create zero or more cursors, and can return a cursor as a JDBC ResultSet.

JDBC is thread safe: It is quite OK to pass the various JDBC objects between threads.

For example, you can create the connection in one thread; another thread can use this connection to create a PreparedStatement and a third thread can process the result set. The single major restriction is that you cannot have more than one ResultSet open on a single PreparedStatement at any time. See Does Oracle DB support multiple (parallel) operations per connection?

Note that a database commit occurs on a Connection, and so all DML (INSERT, UPDATE and DELETE's) on that connection will commit together. Therefore, if you want to support multiple transactions at the same time, you must have at least one Connection for each concurrent Transaction.

Closing JDBC objects

A typical example of executing a ResultSet is:

Statement stmt = conn.createStatement();
try {
    ResultSet rs = stmt.executeQuery( "SELECT FULL_NAME FROM EMP" );
    try {
        while ( rs.next() ) {
            System.out.println( "Name: " + rs.getString("FULL_NAME") );
        }
    } finally {
        try { rs.close(); } catch (Exception ignore) { }
    }
} finally {
    try { stmt.close(); } catch (Exception ignore) { }
}

Note how the finally clause ignores any exception raised by the close():

  • If you simply close the ResultSet without the try {} catch {}, it might fail and prevent the Statement being closed
  • We want to allow any exception raised in the body of the try to propagate to the caller. If you have a loop over, for example, creating and executing Statements, remember to close each Statement within the loop.

In Java 7, Oracle has introduced the AutoCloseable interface which replaces most of the Java 6 boilerplate with some nice syntactic sugar.

Holding JDBC objects

JDBC objects can be safely held in local variables, object instance and class members. It is generally better practice to:

  • Use object instance or class members to hold JDBC objects that are reused multiple times over a longer period, such as Connections and PreparedStatements
  • Use local variables for ResultSets since these are obtained, looped over and then closed typically within the scope of a single function.

There is, however, one exception: If you are using EJBs, or a Servlet/JSP container, you have to follow a strict threading model:

  • Only the Application Server creates threads (with which it handles incoming requests)
  • Only the Application Server creates connections (which you obtain from the connection pool)
  • When saving values (state) between calls, you have to be very careful. Never store values in your own caches or static members - this is not safe across clusters and other weird conditions, and the Application Server may do terrible things to your data. Instead use stateful beans or a database.
  • In particular, never hold JDBC objects (Connections, ResultSets, PreparedStatements, etc) over different remote invocations - let the Application Server manage this. The Application Server not only provides a connection pool, it also caches your PreparedStatements.

Eliminating leaks

There are a number of processes and tools available for helping detect and eliminating JDBC leaks:

  1. During development - catching bugs early is by far the best approach:

    1. Development practices: Good development practices should reduce the number of bugs in your software before it leaves the developer's desk. Specific practices include:

      1. Pair programming, to educate those without sufficient experience
      2. Code reviews because many eyes are better than one
      3. Unit testing which means you can exercise any and all of your code base from a test tool which makes reproducing leaks trivial
      4. Use existing libraries for connection pooling rather than building your own
    2. Static Code Analysis: Use a tool like the excellent Findbugs to perform a static code analysis. This picks up many places where the close() has not been correctly handled. Findbugs has a plugin for Eclipse, but it also runs standalone for one-offs, has integrations into Jenkins CI and other build tools

  2. At runtime:

    1. Holdability and commit

      1. If the ResultSet holdability is ResultSet.CLOSE_CURSORS_OVER_COMMIT, then the ResultSet is closed when the Connection.commit() method is called. This can be set using Connection.setHoldability() or by using the overloaded Connection.createStatement() method.
    2. Logging at runtime.

      1. Put good log statements in your code. These should be clear and understandable so the customer, support staff and teammates can understand without training. They should be terse and include printing the state/internal values of key variables and attributes so that you can trace processing logic. Good logging is fundamental to debugging applications, especially those that have been deployed.
      2. You can add a debugging JDBC driver to your project (for debugging - don't actually deploy it). One example (I have not used it) is log4jdbc. You then need to do some simple analysis on this file to see which executes don't have a corresponding close. Counting the open and closes should highlight if there is a potential problem

        1. Monitoring the database. Monitor your running application using the tools such as the SQL Developer 'Monitor SQL' function or Quest's TOAD. Monitoring is described in this article. During monitoring, you query the open cursors (eg from table v$sesstat) and review their SQL. If the number of cursors is increasing, and (most importantly) becoming dominated by one identical SQL statement, you know you have a leak with that SQL. Search your code and review.

Other thoughts

Can you use WeakReferences to handle closing connections?

Weak and soft references are ways of allowing you to reference an object in a way that allows the JVM to garbage collect the referent at any time it deems fit (assuming there are no strong reference chains to that object).

If you pass a ReferenceQueue in the constructor to the soft or weak Reference, the object is placed in the ReferenceQueue when the object is GC'ed when it occurs (if it occurs at all). With this approach, you can interact with the object's finalization and you could close or finalize the object at that moment.

Phantom references are a bit weirder; their purpose is only to control finalization, but you can never get a reference to the original object, so it's going to be hard to call the close() method on it.

However, it is rarely a good idea to attempt to control when the GC is run (Weak, Soft and PhantomReferences let you know after the fact that the object is enqueued for GC). In fact, if the amount of memory in the JVM is large (eg -Xmx2000m) you might never GC the object, and you will still experience the ORA-01000. If the JVM memory is small relative to your program's requirements, you may find that the ResultSet and PreparedStatement objects are GCed immediately after creation (before you can read from them), which will likely fail your program.

TL;DR: The weak reference mechanism is not a good way to manage and close Statement and ResultSet objects.

Reverse of JSON.stringify?

Check this out.
http://jsfiddle.net/LD55x/

Code:

var myobj = {};
myobj.name="javascriptisawesome";
myobj.age=25;
myobj.mobile=123456789;
debugger;
var str = JSON.stringify(myobj);
alert(str);
var obj = JSON.parse(str);
alert(obj);

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <label>Email</label>
    <input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  
  </form>
</section>

and controller code:

app.controller('MainCtrl', function($scope) {  
  $scope.save = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
      console.log(model); 
    } else {
      console.log('Errors in form data');
    }
  };
});

I hope this helps.

How to set default value to all keys of a dict object in python?

Is this what you want:

>>> d={'a':1,'b':2,'c':3}
>>> default_val=99
>>> for k in d:
...     d[k]=default_val
...     
>>> d
{'a': 99, 'b': 99, 'c': 99}
>>> 

>>> d={'a':1,'b':2,'c':3}
>>> from collections import defaultdict
>>> d=defaultdict(lambda:99,d)
>>> d
defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
>>> d[3]
99

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Swift 3 version code without using any library:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tableView.tableFooterView = UIView(frame: CGRect.zero) //Hiding blank cells.
        tableView.separatorInset = UIEdgeInsets.zero
        tableView.dataSource = self
        tableView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 4
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        return cell
    }

    //Enable cell editing methods.
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
            //self.isEditing = false
            print("more button tapped")
        }
        more.backgroundColor = UIColor.lightGray

        let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
            //self.isEditing = false
            print("favorite button tapped")
        }
        favorite.backgroundColor = UIColor.orange

        let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
            //self.isEditing = false
            print("share button tapped")
        }
        share.backgroundColor = UIColor.blue

        return [share, favorite, more]
    }

}

ASP.NET MVC - Getting QueryString values

I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.

How to remove padding around buttons in Android?

It doesn't seem to be padding, margin, or minheight/width. Setting android:background="@null" the button loses its touch animation, but it turns out that setting the background to anything at all fixes that border.


I am currently working with:

minSdkVersion 19
targetSdkVersion 23

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

How to list all available Kafka brokers in a cluster?

Using Confluent's REST Proxy API v3:

curl -X GET -H "Accept: application/vnd.api+json" localhost:8082/v3/clusters

where localhost:8082 is Kafka Proxy address.

How can a Javascript object refer to values in itself?

You can't refer to a property of an object before you have initialized that object; use an external variable.

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).

Formula px to dp, dp to px android

DisplayMetrics displayMetrics = contaxt.getResources()
            .getDisplayMetrics();

    int densityDpi = (int) (displayMetrics.density * 160f);
    int ratio = (densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    int px;
    if (ratio == 0) {
        px = dp;
    } else {
        px = Math.round(dp * ratio);

    }

member names cannot be the same as their enclosing type C#

just remove this because constructor don't have a return type like void it will be like this :

private Flow()
    {
        X = x;
        Y = y;
    }  

Using the HTML5 "required" attribute for a group of checkboxes?

I guess there's no standard HTML5 way to do this, but if you don't mind using a jQuery library, I've been able to achieve a "checkbox group" validation using webshims' "group-required" validation feature:

The docs for group-required say:

If a checkbox has the class 'group-required' at least one of the checkboxes with the same name inside the form/document has to be checked.

And here's an example of how you would use it:

<input name="checkbox-group" type="checkbox" class="group-required" id="checkbox-group-id" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />

I mostly use webshims to polyfill HTML5 features, but it also has some great optional extensions like this one.

It even allows you to write your own custom validity rules. For example, I needed to create a checkbox group that wasn't based on the input's name, so I wrote my own validity rule for that...

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

Custom designing EditText

android:background="#E1E1E1" 
// background add in layout
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff">
</EditText>

window.location.href not working

The browser is still submitting the form after your code runs.

Add return false; to the handler to prevent that.

Difference between Convert.ToString() and .ToString()

i wrote this code and compile it.

class Program
{
    static void Main(string[] args)
    {
        int a = 1;
        Console.WriteLine(a.ToString());
        Console.WriteLine(Convert.ToString(a));
    }
}

by using 'reverse engineering' (ilspy) i find out 'object.ToString()' and 'Convert.ToString(obj)' do exactly one thing. infact 'Convert.ToString(obj)' call 'object.ToString()' so 'object.ToString()' is faster.

Object.ToString Method:

class System.Object
{
    public string ToString(IFormatProvider provider)
    {
        return Number.FormatInt32(this, null, NumberFormatInfo.GetInstance(provider));
    }
}

Conver.ToString Method:

class System.Convert
{
    public static string ToString(object value)
    {
        return value.ToString(CultureInfo.CurrentCulture);
    }
}

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

In our network I have found that restarting the Workstation service on the client computer is able to resolve this problem. This has worked in cases where a reboot of the client would also fix the problem. But restarting the service is much quicker & easier [and may work when a reboot does not].

My impression is that the local Windows PC is caching some old information and this seems to clear it out.

For information on restarting a service, see this question. It boils down to running the following commands on a command line:

C:\> net stop workstation /y
C:\> net start workstation

Note - the /y flag will force the service to stop even if this will interrupt existing connections. But otherwise it will prompt the user and wait. So this may be necessary for scripting.


Be aware that on Windows Server 2016 (+ possibly others) these commands may also stop the netlogon service. If so you will have to add: net start netlogon

How to concatenate strings in windows batch file for loop?

A very simple example:

SET a=Hello
SET b=World
SET c=%a% %b%!
echo %c%

The result should be:

Hello World!

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

I believe python arrays just admit values. So convert it to list:

kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()

Extracting date from a string in Python

Using python-dateutil:

In [1]: import dateutil.parser as dparser

In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)

Invalid dates raise a ValueError:

In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month

It can recognize dates in many formats:

In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)

Note that it makes a guess if the date is ambiguous:

In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)

But the way it parses ambiguous dates is customizable:

In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)

Class has no member named

Most of the time, the problem is due to some error on the human side. In my case, I was using some classes whose names are similar. I have added the empty() method under one class; however, my code was calling the empty() method from another class. At that moment, the mind was stuck. I was running make clean, and remake thinking that it was some older version of the header got used. After walking away for a moment, I found that problem right away. We programmers tends to blame others first. Maybe we should insist on ourselves to be wrong first.

Sometimes, I forget to write the latest update to disk and looking at the correct version of the code, but the compiler is seeing the wrong version of the code. This situation may be less a issue on IDE (I use vi to do coding).

What is the difference between Linear search and Binary search?

A linear search starts at the beginning of a list of values, and checks 1 by 1 in order for the result you are looking for.

A binary search starts in the middle of a sorted array, and determines which side (if any) the value you are looking for is on. That "half" of the array is then searched again in the same fashion, dividing the results in half by two each time.

Lost connection to MySQL server during query?

I encountered similar problems too. In my case it was solved by getting the cursor in this way:

cursor = self.conn.cursor(buffered=True)

Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

Referencing a string in a string array resource with xml

Maybe this would help:

String[] some_array = getResources().getStringArray(R.array.your_string_array)

So you get the array-list as a String[] and then choose any i, some_array[i].

Compiling a C++ program with gcc

gcc can actually compile c++ code just fine. The errors you received are linker errors, not compiler errors.

Odds are that if you change the compilation line to be this:

gcc info.C -lstdc++

which makes it link to the standard c++ library, then it will work just fine.

However, you should just make your life easier and use g++.


EDIT:

Rup says it best in his comment to another answer:

[...] gcc will select the correct back-end compiler based on file extension (i.e. will compile a .c as C and a .cc as C++) and links binaries against just the standard C and GCC helper libraries by default regardless of input languages; g++ will also select the correct back-end based on extension except that I think it compiles all C source as C++ instead (i.e. it compiles both .c and .cc as C++) and it includes libstdc++ in its link step regardless of input languages.

Hide Text with CSS, Best Practice?

Can't you use simply display: none; like this

HTML

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

CSS

.webname {
   display: none;
}

Or how about playing with visibility if you are concerned to reserve the space

.webname {
   visibility: hidden;
}

Count all values in a matrix greater than a value

There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask array is the easiest one (and iirc a much faster one):

>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[  123, 24123, 32432],
       [  234,    24,    23]])
>>> b = y > 200
>>> b
array([[False,  True,  True],
       [ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432,   234])
>>> len(y[b])
3
>>>> y[b].sum()
56789

Update:

As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:

>>>> (y>200).sum()
3

which is a simpler solution.


Speed comparison with filter:

### use boolean/mask array ###

b = y > 200

%timeit y[b]
100000 loops, best of 3: 3.31 us per loop

%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop

### use filter ###

x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop

%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop

%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop

%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop

*** use numpy.where ***

nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop

%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop

URL string format for connecting to Oracle database with JDBC

Look here.

Your URL is quite incorrect. Should look like this:

url="jdbc:oracle:thin:@localhost:1521:orcl"

You don't register a driver class, either. You want to download the thin driver JAR, put it in your CLASSPATH, and make your code look more like this.

UPDATE: The "14" in "ojdbc14.jar" stands for JDK 1.4. You should match your driver version with the JDK you're running. I'm betting that means JDK 5 or 6.

Associative arrays in Shell scripts

For Bash 3, there is a particular case that has a nice and simple solution:

If you don't want to handle a lot of variables, or keys are simply invalid variable identifiers, and your array is guaranteed to have less than 256 items, you can abuse function return values. This solution does not require any subshell as the value is readily available as a variable, nor any iteration so that performance screams. Also it's very readable, almost like the Bash 4 version.

Here's the most basic version:

hash_index() {
    case $1 in
        'foo') return 0;;
        'bar') return 1;;
        'baz') return 2;;
    esac
}

hash_vals=("foo_val"
           "bar_val"
           "baz_val");

hash_index "foo"
echo ${hash_vals[$?]}

Remember, use single quotes in case, else it's subject to globbing. Really useful for static/frozen hashes from the start, but one could write an index generator from a hash_keys=() array.

Watch out, it defaults to the first one, so you may want to set aside zeroth element:

hash_index() {
    case $1 in
        'foo') return 1;;
        'bar') return 2;;
        'baz') return 3;;
    esac
}

hash_vals=("",           # sort of like returning null/nil for a non existent key
           "foo_val"
           "bar_val"
           "baz_val");

hash_index "foo" || echo ${hash_vals[$?]}  # It can't get more readable than this

Caveat: the length is now incorrect.

Alternatively, if you want to keep zero-based indexing, you can reserve another index value and guard against a non-existent key, but it's less readable:

hash_index() {
    case $1 in
        'foo') return 0;;
        'bar') return 1;;
        'baz') return 2;;
        *)   return 255;;
    esac
}

hash_vals=("foo_val"
           "bar_val"
           "baz_val");

hash_index "foo"
[[ $? -ne 255 ]] && echo ${hash_vals[$?]}

Or, to keep the length correct, offset index by one:

hash_index() {
    case $1 in
        'foo') return 1;;
        'bar') return 2;;
        'baz') return 3;;
    esac
}

hash_vals=("foo_val"
           "bar_val"
           "baz_val");

hash_index "foo" || echo ${hash_vals[$(($? - 1))]}

jQuery - Getting form values for ajax POST

you can use val function to collect data from inputs:

jQuery("#myInput1").val();

http://api.jquery.com/val/

How do I reset the setInterval timer?

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

var ticker = function() {
    console.log('idle');
};

then:

var myTimer = window.setInterval(ticker, 4000);

then when you decide to restart:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

Easiest way to rotate by 90 degrees an image using OpenCV?

Here's my EmguCV (a C# port of OpenCV) solution:

public static Image<TColor, TDepth> Rotate90<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static Image<TColor, TDepth> Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = img.CopyBlank();
    rot = img.Flip(FLIP.VERTICAL);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static void _Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    img._Flip(FLIP.VERTICAL);
    img._Flip(FLIP.HORIZONTAL);
}

public static Image<TColor, TDepth> Rotate270<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.VERTICAL);
    return rot;
}

Shouldn't be too hard to translate it back into C++.

How to mention C:\Program Files in batchfile

I had a similar issue as you, although I was trying to use start to open Chrome and using the file path. I used only start chrome.exe and it opened just fine. You may want to try to do the same with exe file. Using the file path may be unnecessary.

Here are some examples (using the file name you gave in a comment on another answer):

  • Instead of C:\Program^ Files\temp.exe you can try temp.exe.

  • Instead of start C:\Program^ Files\temp.exe you can try start temp.exe

Create a copy of a table within the same database DB2

You have to surround the select part with parenthesis.

CREATE TABLE SCHEMA.NEW_TB AS (
    SELECT *
    FROM SCHEMA.OLD_TB
) WITH NO DATA

Should work. Pay attention to all the things @Gilbert said would not be copied.

I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.

Get the current user, within an ApiController action, without passing the userID as a parameter

In WebApi 2 you can use RequestContext.Principal from within a method on ApiController

milliseconds to time in javascript

An Easier solution would be the following:

var d = new Date();
var n = d.getMilliseconds(); 

Difference between two dates in Python

Use - to get the difference between two datetime objects and take the days member.

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

Check if Cookie Exists

Sorry, not enough rep to add a comment, but from zmbq's answer:

Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.

is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:

bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to get first and last day of the current week in JavaScript

JavaScript

function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
  var cd = curr.getDate() - curr.getDay();
  var from = new Date(curr.setDate(cd + firstDay));
  var to = new Date(curr.setDate(cd + 6 + firstDay));

  return {
    from,
    to,
  };
};

TypeScript

export enum WEEK_DAYS {
  Sunday = 0,
  Monday = 1,
  Tuesday = 2,
  Wednesday = 3,
  Thursday = 4,
  Friday = 5,
  Saturday = 6,
}

export const getWeekDays = (
  curr: Date,
  firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
  const cd = curr.getDate() - curr.getDay();
  const from = new Date(curr.setDate(cd + firstDay));
  const to = new Date(curr.setDate(cd + 6 + firstDay));

  return {
    from,
    to,
  };
};

How do I create a unique ID in Java?

We can create a unique ID in java by using the UUID and call the method like randomUUID() on UUID.

String uniqueID = UUID.randomUUID().toString();

This will generate the random uniqueID whose return type will be String.

openssl s_client -cert: Proving a client certificate was sent to the server

In order to verify a client certificate is being sent to the server, you need to analyze the output from the combination of the -state and -debug flags.

First as a baseline, try running

$ openssl s_client -connect host:443 -state -debug

You'll get a ton of output, but the lines we are interested in look like this:

SSL_connect:SSLv3 read server done A
write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
0000 - 16 03 01 00 07 0b 00 00-03                        .........
000c - <SPACES/NULS>
SSL_connect:SSLv3 write client certificate A

What's happening here:

  • The -state flag is responsible for displaying the end of the previous section:

    SSL_connect:SSLv3 read server done A  
    

    This is only important for helping you find your place in the output.

  • Then the -debug flag is showing the raw bytes being sent in the next step:

    write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
    0000 - 16 03 01 00 07 0b 00 00-03                        .........
    000c - <SPACES/NULS>
    
  • Finally, the -state flag is once again reporting the result of the step that -debug just echoed:

    SSL_connect:SSLv3 write client certificate A
    

So in other words: s_client finished reading data sent from the server, and sent 12 bytes to the server as (what I assume is) a "no client certificate" message.


If you repeat the test, but this time include the -cert and -key flags like this:

$ openssl s_client -connect host:443 \
   -cert cert_and_key.pem \
   -key cert_and_key.pem  \
   -state -debug

your output between the "read server done" line and the "write client certificate" line will be much longer, representing the binary form of your client certificate:

SSL_connect:SSLv3 read server done A
write to 0x7bd970 [0x86d890] (1576 bytes => 1576 (0x628))
0000 - 16 03 01 06 23 0b 00 06-1f 00 06 1c 00 06 19 31   ....#..........1
(*SNIP*)
0620 - 95 ca 5e f4 2f 6c 43 11-                          ..^%/lC.
SSL_connect:SSLv3 write client certificate A

The 1576 bytes is an excellent indication on its own that the cert was transmitted, but on top of that, the right-hand column will show parts of the certificate that are human-readable: You should be able to recognize the CN and issuer strings of your cert in there.

What is the Java ?: operator called and what does it do?

Others have answered this to reasonable extent, but often with the name "ternary operator".

Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.

However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.

How can I start and check my MySQL log?

Its given on OFFICIAL MYSQL website.

SET GLOBAL general_log = 'ON';

You can also use custom path:

[mysqld]
# Set Slow Query Log
long_query_time = 1
slow_query_log = 1
slow_query_log_file = "C:/slowquery.log"

#Set General Log
log = "C:/genquery.log"

Best database field type for a URL

You'll want to choose between a TEXT or VARCHAR column based on how often the URL will be used and whether you actually need the length to be unbound.

Use VARCHAR with maxlength >= 2,083 as micahwittman suggested if:

  1. You'll use a lot of URLs per query (unlike TEXT columns, VARCHARs are stored inline with the row)
  2. You're pretty sure that a URL will never exceed the row-limit of 65,535 bytes.

Use TEXT if :

  1. The URL really might break the 65,535 byte row limit
  2. Your queries won't select or update a bunch of URLs at once (or very often). This is because TEXT columns just hold a pointer inline, and the random accesses involved in retrieving the referenced data can be painful.

Switch statement with returns -- code correctness

What do you think? Is it fine to remove them? Or would you keep them for increased "correctness"?

It is fine to remove them. Using return is exactly the scenario where break should not be used.

Find the location of a character in string

find the position of the nth occurrence of str2 in str1(same order of parameters as Oracle SQL INSTR), returns 0 if not found

instr <- function(str1,str2,startpos=1,n=1){
    aa=unlist(strsplit(substring(str1,startpos),str2))
    if(length(aa) < n+1 ) return(0);
    return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) )
}


instr('xxabcdefabdddfabx','ab')
[1] 3
instr('xxabcdefabdddfabx','ab',1,3)
[1] 15
instr('xxabcdefabdddfabx','xx',2,1)
[1] 0

Centering image and text in R Markdown for a PDF report

There is now a much better solution, a lot more elegant, based on fenced div, which have been implemented in pandoc, as explained here:

::: {.center data-latex=""}
Some text here...
:::

All you need to do is to change your css file accordingly. The following chunk for instance does the job:

```{cat, engine.opts = list(file = "style.css")}
.center {
  text-align: center;
}
``` 

(Obviously, you can also directly type the content of the chunk into your .css file...).
The tex file includes the proper centering commands.
The crucial advantage of this method is that it allows writing markdown code inside the block.
In my previous answer, r ctrFmt("Centered **text** in html and pdf!") does not bold for the word "text", but it would if inside a fenced div.

For images, etc... the lua filter is available here

Simplest way to throw an error/exception with a custom message in Swift 2?

Swift 4:

As per:

https://developer.apple.com/documentation/foundation/nserror

if you don't want to define a custom exception, you could use a standard NSError object as follows:

import Foundation

do {
  throw NSError(domain: "my error domain", code: 42, userInfo: ["ui1":12, "ui2":"val2"] ) 
}
catch let error as NSError {
  print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
  let uis = error.userInfo 
  print("\tUser info:")
  for (key,value) in uis {
    print("\t\tkey=\(key), value=\(value)")
  }
}

Prints:

Caught NSError: The operation could not be completed, my error domain, 42
    User info:
        key=ui1, value=12
        key=ui2, value=val2

This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.

N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).

How to use OKHTTP to make a post request?

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    RequestBody formBody = new FormEncodingBuilder()
        .add("search", "Jurassic Park")
        .build();
    Request request = new Request.Builder()
        .url("https://en.wikipedia.org/w/index.php")
        .post(formBody)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }

Converting an integer to a string in PHP

You can use the strval() function to convert a number to a string.

From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context.

$var = 5;

// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles

// String concatenation 
echo "I'd like ".$var." waffles"; // I'd like 5 waffles

// The two examples above have the same end value...
// ... And so do the two below

// Explicit cast 
$items = (string)$var; // $items === "5";

// Function call
$items = strval($var); // $items === "5";

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

Getting data from selected datagridview row and which event?

Simple solution would be as below. This is improvement of solution from vale.

private void dgMapTable_SelectionChanged(object sender, EventArgs e) 
{
    int active_map=0;
    if(dgMapTable.SelectedRows.Count>0)
        active_map = dgMapTable.SelectedRows[0].Index;
    // User code if required Process_ROW(active_map);
}

Note for other reader, for above code to work FullRowSelect selection mode for datagridview should be used. You may extend this to give message if more than two rows selected.

Entity Framework. Delete all rows in table

There are several issues with pretty much all the answers here:

1] Hard-coded sql. Will brackets work on all database engines?
2] Entity framework Remove and RemoveRange calls. This loads all entities into memory affected by the operation. Yikes.
3] Truncate table. Breaks with foreign key references and may not work accross all database engines.

Use https://entityframework-plus.net/, they handle the cross database platform stuff, translate the delete into the correct sql statement and don't load entities into memory, and the library is free and open source.

Disclaimer: I am not affiliated with the nuget package. They do offer a paid version that does even more stuff.

How to remove RVM (Ruby Version Manager) from my system

A lot of people do a common mistake of thinking that 'rvm implode' does it . You need to delete all traces of any .rm files . Also , it will take some manual deletions from root . Make sure , it gets deleted and also all the ruby versions u installed using it .

How Big can a Python List Get?

There is no limitation of list number. The main reason which causes your error is the RAM. Please upgrade your memory size.

How to display HTML tags as plain text

You can use htmlentities when echoing to the browser, this will show the tag rather than have html interpret it.

See here http://uk3.php.net/manual/en/function.htmlentities.php

Example:

 echo htmlentities("<strong>Look just like this line - so then know how to type it</strong>"); 

Output:

<strong>Look just like this line - so then know how to type it</strong>

How to do a background for a label will be without color?

You are right. but here is the simplest way for making the back color of the label transparent In the properties window of that label select Web.. In Web select Transparent :)

Line continue character in C#

@"string here
that is long you mean"

But be careful, because

@"string here
           and space before this text
     means the space is also a part of the string"

It also escapes things in the string

@"c:\\folder" // c:\\folder
@"c:\folder" // c:\folder
"c:\\folder" // c:\folder

Related

Java: How to Indent XML Generated by Transformer

You need to enable 'INDENT' and set the indent amount for the transformer:

t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

Update:


Reference : How to strip whitespace-only text nodes from a DOM before serialization?

(Many thanks to all members especially @marc-novakowski, @james-murty and @saad):

Can't install gems on OS X "El Capitan"

As it have been said, the issue comes from a security function of Mac OSX since "El Capitan".

Using the default system Ruby, the install process happens in the /Library/Ruby/Gems/2.0.0 directory which is not available to the user and gives the error.

You can have a look to your Ruby environments parameters with the command

$ gem env

There is an INSTALLATION DIRECTORY and a USER INSTALLATION DIRECTORY. To use the user installation directory instead of the default installation directory, you can use --user-install parameter instead as using sudo which is never a recommanded way of doing.

$ gem install myGemName --user-install

There should not be any rights issue anymore in the process. The gems are then installed in the user directory : ~/.gem/Ruby/2.0.0/bin

But to make the installed gems available, this directory should be available in your path. According to the Ruby’s faq, you can add the following line to your ~/.bash_profile or ~/.bashrc

if which ruby >/dev/null && which gem >/dev/null; then
    PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi

Then close and reload your terminal or reload your .bash_profile or .bashrc (. ~/.bash_profile)

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

RE error: illegal byte sequence on Mac OS X

Does anyone know how to get sed to print the position of the illegal byte sequence? Or does anyone know what the illegal byte sequence is?

$ uname -a
Darwin Adams-iMac 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64

I got part of the way to answering the above just by using tr.

I have a .csv file that is a credit card statement and I am trying to import it into Gnucash. I am based in Switzerland so I have to deal with words like Zürich. Suspecting Gnucash does not like " " in numeric fields, I decide to simply replace all

; ;

with

;;

Here goes:

$ head -3 Auswertungen.csv | tail -1 | sed -e 's/; ;/;;/g'
sed: RE error: illegal byte sequence

I used od to shed some light: Note the 374 halfway down this od -c output

$ head -3 Auswertungen.csv | tail -1 | od -c
0000000    1   6   8   7       9   6   1   9       7   1   2   2   ;   5
0000020    4   6   8       8   7   X   X       X   X   X   X       2   6
0000040    6   0   ;   M   Y       N   A   M   E       I   S   X   ;   1
0000060    4   .   0   2   .   2   0   1   9   ;   9   5   5   2       -
0000100        M   i   t   a   r   b   e   i   t   e   r   r   e   s   t
0000120                Z 374   r   i   c   h                            
0000140    C   H   E   ;   R   e   s   t   a   u   r   a   n   t   s   ,
0000160        B   a   r   s   ;   6   .   2   0   ;   C   H   F   ;    
0000200    ;   C   H   F   ;   6   .   2   0   ;       ;   1   5   .   0
0000220    2   .   2   0   1   9  \n                                    
0000227

Then I thought I might try to persuade tr to substitute 374 for whatever the correct byte code is. So first I tried something simple, which didn't work, but had the side effect of showing me where the troublesome byte was:

$ head -3 Auswertungen.csv | tail -1 | tr . .  ; echo
tr: Illegal byte sequence
1687 9619 7122;5468 87XX XXXX 2660;MY NAME ISX;14.02.2019;9552 - Mitarbeiterrest   Z

You can see tr bails at the 374 character.

Using perl seems to avoid this problem

$ head -3 Auswertungen.csv | tail -1 | perl -pne 's/; ;/;;/g'
1687 9619 7122;5468 87XX XXXX 2660;ADAM NEALIS;14.02.2019;9552 - Mitarbeiterrest   Z?rich       CHE;Restaurants, Bars;6.20;CHF;;CHF;6.20;;15.02.2019

Warning: Found conflicts between different versions of the same dependent assembly

This actually depends on your external component. When you reference an external component in a .NET application it generates a GUID to identify that component. This error occurs when the external component referenced by one of your projects has the same name and but different version as another such component in another assembly.

This sometimes happens when you use "Browse" to find references and add the wrong version of the assembly, or you have a different version of the component in your code repository as the one you installed in the local machine.

Do try to find which projects have these conflicts, remove the components from the reference list, then add them again making sure that you're pointing to the same file.

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

How to suppress Update Links warning?

UPDATE:

After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all is.

Preparations

First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).

Then, I changed only the following Excel options (i.e. all the other are left as is after installation):

  • Advanced > General > Ask to update automatic links checked:

Ask to update automatic links

  • Trust Center > Trust Center Settings... > External Content > Enable All... (although that one that relates to Data Connections is most likely not important for the case):

External Content

Preconditions

I prepared and placed to C:\ a workbook exactly as per @Siddharth Rout suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).

Manual Opening

The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:

WARNING #1

This workbook contains links to other data sources

After click on Update I expectedly got another:

WARNING #2

This workbook contains one or more links that cannot be updated

So, I suppose my testing environment is now pretty much similar to OP's) So far so good, we finally go to

VBA Opening

Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).

1. Simple Application.Workbooks.Open

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"

No surprise - this produces BOTH warnings, as for manual opening above.

2. Application.DisplayAlerts = False

Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True

This code ends up with WARNING #1, and either option clicked (Update / Don't Update) produces NO further warnings, i.e. Application.DisplayAlerts = False suppresses WARNING #2.

3. Application.AskToUpdateLinks = False

Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True

Opposite to DisplayAlerts, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False suppresses WARNING #1.

4. Double False

Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True

Apparently, this code ends up with suppressing BOTH WARNINGS.

5. UpdateLinks:=False

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False

Finally, this 1-line solution (originally proposed by @brettdj) works the same way as Double False: NO WARNINGS are shown!

Conclusions

Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:

  1. Excel options DO matter, regardless of version - especially when we come to VBA solutions.
  2. Every trouble has short and elegant solution - together with not obvious and complicated one. Just one more proof for that!)

Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)

Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

Original answer (tested for Excel 2007 with certain options):

This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder:

Sub WorkbookOpening2007()

Dim InputFolder As String
Dim LoopFileNameExt As String

InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!

LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""

Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True

LoopFileNameExt = Dir
Loop

End Sub

I tried it with books with unavailable external links - no warnings.

Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

How to delete a specific line in a file?

The issue with reading lines in first pass and making changes (deleting specific lines) in the second pass is that if you file sizes are huge, you will run out of RAM. Instead, a better approach is to read lines, one by one, and write them into a separate file, eliminating the ones you don't need. I have run this approach with files as big as 12-50 GB, and the RAM usage remains almost constant. Only CPU cycles show processing in progress.

What is the C# version of VB.net's InputDialog?

To sum it up:

  • There is none in C#.
  • You can use the dialog from Visual Basic by adding a reference to Microsoft.VisualBasic:

    1. In Solution Explorer right-click on the References folder.
    2. Select Add Reference...
    3. In the .NET tab (in newer Visual Studio verions - Assembly tab) - select Microsoft.VisualBasic
    4. Click on OK

Then you can use the previously mentioned code:

string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt", "Title", "Default", 0, 0);

That said, I suggest that you consider the need of an input box in the first place. Dialogs are not always the best way to do things and sometimes they do more harm than good - but that depends on the particular situation.

How to create a HTML Table from a PHP array?

   <table>
     <tr>
       <td>title</td>
       <td>price</td>
       <td>number</td>
     </tr>
     <? foreach ($shop as $row) : ?>
     <tr>
       <td><? echo $row[0]; ?></td>
       <td><? echo $row[1]; ?></td>
       <td><? echo $row[2]; ?></td>
     </tr>
     <? endforeach; ?>
   </table>

Mockito matcher and array of primitives

I would rather use Matchers.<byte[]>any(). This worked for me.

How to make an HTML back link?

You can also use history.back() alongside document.write() to show link only when there is actually somewhere to go back to:

<script>
  if (history.length > 1) {
    document.write('<a href="javascript:history.back()">Go back</a>');
  }
</script>

Updating to latest version of CocoaPods?

This is a really quick & detailed solution

Open the Terminal and execute the following to get the latest stable version:

sudo gem install cocoapods

Add --pre to get the latest pre release:

sudo gem install cocoapods --pre

Incase any error occured

Try uninstall and install again:

sudo gem uninstall cocoapods
sudo gem install cocoapods

Run after updating CocoaPods

sudo gem clean cocoapods

After updating CocoaPods, also need to update Podfile.lock file in your project.

Go to your project directory

pod install

Calculate logarithm in python

The math.log function is to the base e, i.e. natural logarithm. If you want to the base 10 use math.log10.

How to convert int[] to Integer[] in Java?

If you want to convert an int[] to an Integer[], there isn't an automated way to do it in the JDK. However, you can do something like this:

int[] oldArray;

... // Here you would assign and fill oldArray

Integer[] newArray = new Integer[oldArray.length];
int i = 0;
for (int value : oldArray) {
    newArray[i++] = Integer.valueOf(value);
}

If you have access to the Apache lang library, then you can use the ArrayUtils.toObject(int[]) method like this:

Integer[] newArray = ArrayUtils.toObject(oldArray);

Cannot uninstall angular-cli

Step 1:

npm uninstall -g angular-cli

Step 2:

npm cache clean

Step 3:

npm cache verify

Step 4:

npm cache verify --force

Note: You can also delete by the following the paths

C:\Users"System_name"\AppData\Roaming\npm and

C:\Users"System_name"\AppData\Roaming\npm-cache

Then

Step 5:

npm install -g @angular/cli@latest

Chrome / Safari not filling 100% height of flex parent

For Mobile Safari There is a Browser fix. you need to add -webkit-box for iOS devices.

Ex.

display: flex;
display: -webkit-box;
flex-direction: column;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
align-items: stretch;

if you're using align-items: stretch; property for parent element, remove the height : 100% from the child element.

Git: How to reset a remote Git repository to remove all commits?

Were I you I would do something like this:

Before doing anything please keep a copy (better safe than sorry)

git checkout master
git checkout -b temp 
git reset --hard <sha-1 of your first commit> 
git add .
git commit -m 'Squash all commits in single one'
git push origin temp

After doing that you can delete other branches.

Result: You are going to have a branch with only 2 commits.

Use git log --oneline to see your commits in a minimalistic way and to find SHA-1 for commits!

How to remove any URL within a string in Python

the shortest way

re.sub(r'http\S+', '', stringliteral)

How to remove folders with a certain name

find ./ -name "FOLDERNAME" | xargs rm -Rf

Should do the trick. WARNING, if you accidentally pump a . or / into xargs rm -Rf your entire computer will be deleted without an option to get it back, requiring an OS reinstall.

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

How can I list all foreign keys referencing a given table in SQL Server?

You should also mind the references to other objects.

If the table was highly referenced by other tables than it’s probably also highly referenced by other objects such as views, stored procedures, functions and more.

I’d really recommend GUI tool such as ‘view dependencies’ dialog in SSMS or free tool like ApexSQL Search for this because searching for dependencies in other objects can be error prone if you want to do it only with SQL.

If SQL is the only option you could try doing it like this.

select O.name as [Object_Name], C.text as [Object_Definition]
from sys.syscomments C
inner join sys.all_objects O ON C.id = O.object_id
where C.text like '%table_name%'

WordPress query single post by slug

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

What is the difference between properties and attributes in HTML?

After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.

HTML attribute vs. DOM property

-------------------------------

Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

  • A few HTML attributes have 1:1 mapping to properties. id is one example.

  • Some HTML attributes don't have corresponding properties. colspan is one example.

  • Some DOM properties don't have corresponding attributes. textContent is one example.

  • Many HTML attributes appear to map to properties ... but not in the way you might think!

That last category is confusing until you grasp this general rule:

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

For example, when the browser renders <input type="text" value="Bob">, it creates a corresponding DOM node with a value property initialized to "Bob".

When the user enters "Sally" into the input box, the DOM element value property becomes "Sally". But the HTML value attribute remains unchanged as you discover if you ask the input element about that attribute: input.getAttribute('value') returns "Bob".

The HTML attribute value specifies the initial value; the DOM value property is the current value.


The disabled attribute is another peculiar example. A button's disabled property is false by default so the button is enabled. When you add the disabled attribute, its presence alone initializes the button's disabled property to true so the button is disabled.

Adding and removing the disabled attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing <button disabled="false">Still Disabled</button>.

Setting the button's disabled property disables or enables the button. The value of the property matters.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

Spring Boot Program cannot find main class

I was having the same problem just delete .m2 folder folder from your local repositry Hope it will work.

Getting only Month and Year from SQL DATE

For result: "YYYY-MM"

SELECT cast(YEAR(<DateColumn>) as varchar) + '-' + cast(Month(<DateColumn>) as varchar)

Refresh page after form submitting

You can maybe use :

<form method="post" action=" " onSubmit="window.location.reload()">

Escaping regex string

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

Does Ruby have a string.startswith("abc") built in method?

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?

Does Notepad++ show all hidden characters?

Yes, and unfortunately you cannot turn them off, or any other special characters. The options under \View\Show Symbols only turns on or off things like tabs, spaces, EOL, etc. So if you want to read some obscure coding with text in it - you actually need to look elsewhere. I also looked at changing the coding, ASCII is not listed, and that would not make the mess invisible anyway.

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

SHA512 vs. Blowfish and Bcrypt

I would recommend Ulrich Drepper's SHA-256/SHA-512 based crypt implementation.

We ported these algorithms to Java, and you can find a freely licensed version of them at ftp://ftp.arlut.utexas.edu/java_hashes/.

Note that most modern (L)Unices support Drepper's algorithm in their /etc/shadow files.

See full command of running/stopped container in Docker

Use runlike from git repository https://github.com/lavie/runlike

To install runlike

pip install runlike

As it accept container id as an argument so to extract container id use following command

docker ps -a -q

You are good to use runlike to extract complete docker run command with following command

runlike <docker container ID>

Retain precision with double in Java

Observe that you'd have the same problem if you used limited-precision decimal arithmetic, and wanted to deal with 1/3: 0.333333333 * 3 is 0.999999999, not 1.00000000.

Unfortunately, 5.6, 5.8 and 11.4 just aren't round numbers in binary, because they involve fifths. So the float representation of them isn't exact, just as 0.3333 isn't exactly 1/3.

If all the numbers you use are non-recurring decimals, and you want exact results, use BigDecimal. Or as others have said, if your values are like money in the sense that they're all a multiple of 0.01, or 0.001, or something, then multiply everything by a fixed power of 10 and use int or long (addition and subtraction are trivial: watch out for multiplication).

However, if you are happy with binary for the calculation, but you just want to print things out in a slightly friendlier format, try java.util.Formatter or String.format. In the format string specify a precision less than the full precision of a double. To 10 significant figures, say, 11.399999999999 is 11.4, so the result will be almost as accurate and more human-readable in cases where the binary result is very close to a value requiring only a few decimal places.

The precision to specify depends a bit on how much maths you've done with your numbers - in general the more you do, the more error will accumulate, but some algorithms accumulate it much faster than others (they're called "unstable" as opposed to "stable" with respect to rounding errors). If all you're doing is adding a few values, then I'd guess that dropping just one decimal place of precision will sort things out. Experiment.

How to clear input buffer in C?

Try this:

stdin->_IO_read_ptr = stdin->_IO_read_end;

How do I test if a variable does not equal either of two values?

May I suggest trying to use in else if statement in your if/else statement. And if you don't want to run any code that not under any conditions you want you can just leave the else out at the end of the statement. else if can also be used for any number of diversion paths that need things to be a certain condition for each.

if(condition 1){

} else if (condition 2) {

}else {

}

How to instantiate, initialize and populate an array in TypeScript?

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

Get total size of file in bytes

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

Find indices of elements equal to zero in a NumPy array

You can use numpy.nonzero to find zero.

>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0)  # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.

If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar, which is available in SQLLIB/java/ folder of your db2 installation.

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

$ rails server -b $IP -p $PORT - that solved the same problem for me

How To Auto-Format / Indent XML/HTML in Notepad++

Just install the latest notepad++ and install indent By fold. On the menu bar select Plugins -> Plugins Admin and selct indent By fold and the install. Works finest

How to run functions in parallel?

Seems like you have a single function that you need to call on two different parameters. This can be elegantly done using a combination of concurrent.futures and map with Python 3.2+

import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def sleep_secs(seconds):
  time.sleep(seconds)
  print(f'{seconds} has been processed')

secs_list = [2,4, 6, 8, 10, 12]

Now, if your operation is IO bound, then you can use the ThreadPoolExecutor as such:

with ThreadPoolExecutor() as executor:
  results = executor.map(sleep_secs, secs_list)

Note how map is used here to map your function to the list of arguments.

Now, If your function is CPU bound, then you can use ProcessPoolExecutor

with ProcessPoolExecutor() as executor:
  results = executor.map(sleep_secs, secs_list)

If you are not sure, you can simply try both and see which one gives you better results.

Finally, if you are looking to print out your results, you can simply do this:

with ThreadPoolExecutor() as executor:
  results = executor.map(sleep_secs, secs_list)
  for result in results:
    print(result)

How to replace an entire line in a text file by line number

Excellent answer from Chepner. It is working for me in bash Shell.

 # To update/replace the new line string value with the exiting line of the file
 MyFile=/tmp/ps_checkdb.flag

 `sed -i "${index}s/.*/${newLine}/" $MyFile`

here
index - Line no
newLine - new line string which we want to replace.


Similarly below code is used to read a particular line in the file. This won't affect the actual file.

LineString=`sed "$index!d" $MyFile` 

here
!d - will delete the lines other than line no $index So we will get the output as line string of no $index in the file.

SQL: Two select statements in one query

You can union the queries as long as the columns match.

SELECT name,
       games,
       goals
FROM   tblMadrid
WHERE  id = 1
UNION ALL
SELECT name,
       games,
       goals
FROM   tblBarcelona
WHERE  id = 2 

Xcode 6 Bug: Unknown class in Interface Builder file

I'm a PyObjC user and I had my NSView subclass in its own file. What solved this problem for me was to move the NSView subclass from its own file into my AppController.py file. This is the file that has the application controller in it.

HTML Mobile -forcing the soft keyboard to hide

For further readers/searchers:

As Rene Pot points out on this topic,

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.

This solution also works fine with date-time-pickers which generally already implement controls.

How to retrieve a module's path?

I'd like to contribute with one common scenario (in Python 3) and explore a few approaches to it.

The built-in function open() accepts either relative or absolute path as its first argument. The relative path is treated as relative to the current working directory though so it is recommended to pass the absolute path to the file.

Simply said, if you run a script file with the following code, it is not guaranteed that the example.txt file will be created in the same directory where the script file is located:

with open('example.txt', 'w'):
    pass

To fix this code we need to get the path to the script and make it absolute. To ensure the path to be absolute we simply use the os.path.realpath() function. To get the path to the script there are several common functions that return various path results:

  • os.getcwd()
  • os.path.realpath('example.txt')
  • sys.argv[0]
  • __file__

Both functions os.getcwd() and os.path.realpath() return path results based on the current working directory. Generally not what we want. The first element of the sys.argv list is the path of the root script (the script you run) regardless of whether you call the list in the root script itself or in any of its modules. It might come handy in some situations. The __file__ variable contains path of the module from which it has been called.


The following code correctly creates a file example.txt in the same directory where the script is located:

filedir = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(filedir, 'example.txt')

with open(filepath, 'w'):
    pass

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

You should add AVD Emulator. Go to this location:

C:\Users\%username%\AppData\Local\Android\sdk\

start AVD Manager and in the second tab(Device Definitions) click on the button "createAVD".

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

How to store custom objects in NSUserDefaults

Synchronize the data/object that you have saved into NSUserDefaults

-(void)saveCustomObject:(Player *)object
{ 
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [prefs setObject:myEncodedObject forKey:@"testing"];
    [prefs synchronize];
}

Hope this will help you. Thanks

Docker: adding a file from a parent directory

Since -f caused another problem, I developed another solution.

  • Create a base image in the parent folder
  • Added the required files.
  • Used this image as a base image for the project which in a descendant folder.

The -f flag does not solved my problem because my onbuild image looks for a file in a folder and had to call like this:

-f foo/bar/Dockerfile foo/bar

instead of

-f foo/bar/Dockerfile .

Also note that this is only solution for some cases as -f flag

How do I add files and folders into GitHub repos?

Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.

d

How to upper case every first letter of word in a string?

Trying to be more memory efficient than splitting the string into multiple strings, and using the strategy shown by Darshana Sri Lanka. Also, handles all white space between words, not just the " " character.

public static String UppercaseFirstLetters(String str) 
{
    boolean prevWasWhiteSp = true;
    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (Character.isLetter(chars[i])) {
            if (prevWasWhiteSp) {
                chars[i] = Character.toUpperCase(chars[i]);    
            }
            prevWasWhiteSp = false;
        } else {
            prevWasWhiteSp = Character.isWhitespace(chars[i]);
        }
    }
    return new String(chars);
}

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

execute this

EXEC sp_MSforeachtable 'PRINT ''ALTER TABLE ? NOCHECK CONSTRAINT ALL'''
EXEC sp_MSforeachtable 'print ''DELETE FROM ?'''
EXEC sp_MSforeachtable 'print ''ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'''

After copy the printed result and paste it on Query field and Execute it. It will truncate all tables.

Open Google Chrome from VBA/Excel

I found an easier way to do it and it works perfectly even if you don't know the path where the chrome is located.

First of all, you have to paste this code in the top of the module.

Option Explicit
Private pWebAddress As String
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

After that you have to create this two modules:

Sub LoadExplorer()
    LoadFile "Chrome.exe" ' Here you are executing the chrome. exe
End Sub

Sub LoadFile(FileName As String)
    ShellExecute 0, "Open", FileName, "http://test.123", "", 1 ' You can change the URL.
End Sub

With this you will be able (if you want) to set a variable for the url or just leave it like hardcode.

Ps: It works perfectly for others browsers just changing "Chrome.exe" to opera, bing, etc.

Interface or an Abstract Class: which one to use?

The differences between an Abstract Class and an Interface:

Abstract Classes

An abstract class can provide some functionality and leave the rest for derived class.

  • The derived class may or may not override the concrete functions defined in the base class.

  • A child class extended from an abstract class should logically be related.

Interface

An interface cannot contain any functionality. It only contains definitions of the methods.

  • The derived class MUST provide code for all the methods defined in the interface.

  • Completely different and non-related classes can be logically grouped together using an interface.

Remove items from one list in another

You can use Except:

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();

You probably don't even need those temporary variables:

List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();

Note that Except does not modify either list - it creates a new list with the result.

How to check if a column exists in a datatable

It is much more accurate to use IndexOf:

If dt.Columns.IndexOf("ColumnName") = -1 Then
    'Column not exist
End If

If the Contains is used it would not differentiate between ColumName and ColumnName2.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

Just in case someone else runs into this problem I solved it by the following

brew update && brew upgrade # installs libpng 1.6

This caused an error with other packages requiring 1.5 which they were built with, so I linked it:

cd /usr/local/lib/
ln -s ../Cellar/libpng/1.5.18/lib/libpng15.15.dylib

Now they are both living in harmony and side by side for the different packages. It would be better to rebuild the packages that depend on 1.5, but this works as a quick bandage fix.

Converting Stream to String and back...what are we missing?

I wrote a useful method to call any action that takes a StreamWriter and write it out to a string instead. The method is like this;

static void SendStreamToString(Action<StreamWriter> action, out string destination)
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream, Encoding.Unicode))
    {
        action(writer);
        writer.Flush();
        stream.Position = 0;
        destination = Encoding.Unicode.GetString(stream.GetBuffer(), 0, (int)stream.Length);
    }
}

And you can use it like this;

string myString;

SendStreamToString(writer =>
{
    var ints = new List<int> {1, 2, 3};
    writer.WriteLine("My ints");
    foreach (var integer in ints)
    {
        writer.WriteLine(integer);
    }
}, out myString);

I know this can be done much easier with a StringBuilder, the point is that you can call any method that takes a StreamWriter.

How to convert rdd object to dataframe in spark

Note: This answer was originally posted here

I am posting this answer because I would like to share additional details about the available options that I did not find in the other answers


To create a DataFrame from an RDD of Rows, there are two main options:

1) As already pointed out, you could use toDF() which can be imported by import sqlContext.implicits._. However, this approach only works for the following types of RDDs:

  • RDD[Int]
  • RDD[Long]
  • RDD[String]
  • RDD[T <: scala.Product]

(source: Scaladoc of the SQLContext.implicits object)

The last signature actually means that it can work for an RDD of tuples or an RDD of case classes (because tuples and case classes are subclasses of scala.Product).

So, to use this approach for an RDD[Row], you have to map it to an RDD[T <: scala.Product]. This can be done by mapping each row to a custom case class or to a tuple, as in the following code snippets:

val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => (val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

or

case class MyClass(val1: String, ..., valN: Long = 0L)
val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => MyClass(val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

The main drawback of this approach (in my opinion) is that you have to explicitly set the schema of the resulting DataFrame in the map function, column by column. Maybe this can be done programatically if you don't know the schema in advance, but things can get a little messy there. So, alternatively, there is another option:


2) You can use createDataFrame(rowRDD: RDD[Row], schema: StructType) as in the accepted answer, which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:

val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)

Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.

php variable in html no other way than: <?php echo $var; ?>

Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.

echo <<<MYTAG
  <tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;

javascript setTimeout() not working

To make little more easy to understand use like below, which i prefer the most. Also it permits to call multiple function at once. Obviously

setTimeout(function(){
      startTimer();
      function2();
      function3();
}, startInterval);

How to prevent http file caching in Apache httpd (MAMP)

Based on the example here: http://drupal.org/node/550488

The following will probably work in .htaccess

 <IfModule mod_expires.c>
   # Enable expirations.
   ExpiresActive On

   # Cache all files for 2 weeks after access (A).
   ExpiresDefault A1209600

  <FilesMatch (\.js|\.html)$>
     ExpiresActive Off
  </FilesMatch>
 </IfModule>

How to use onClick event on react Link component?

You should use this:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

Why is Visual Studio 2013 very slow?

I was using a solution upgraded from Visual Studio 2012. Visual Studio 2013 also upgraded the .suo file. Deleting the solution's .suo file (it's next to the .sln file), closing and re-opening Visual Studio fixed the problem for me. My .suo file went from 91KB to 27KB.

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

How to install Python MySQLdb module using pip?

If pip3 isn't working, you can try:

sudo apt install python3-mysqldb

How to parse a CSV file in Bash?

From the man page:

-d delim The first character of delim is used to terminate the input line, rather than newline.

You are using -d, which will terminate the input line on the comma. It will not read the rest of the line. That's why $y is empty.

How to get the body's content of an iframe in Javascript?

The following code is cross-browser compliant. It works in IE7, IE8, Fx 3, Safari, and Chrome, so no need to handle cross-browser issues. Did not test in IE6.

<iframe id="iframeId" name="iframeId">...</iframe>

<script type="text/javascript">
    var iframeDoc;
    if (window.frames && window.frames.iframeId &&
        (iframeDoc = window.frames.iframeId.document)) {
        var iframeBody = iframeDoc.body;
        var ifromContent = iframeBody.innerHTML;
    }
</script>

Passing command line arguments from Maven as properties in pom.xml

mvn clean package -DpropEnv=PROD

Then using like this in POM.xml

<properties>
    <myproperty>${propEnv}</myproperty>
</properties>

Execute PHP scripts within Node.js web server

A simple, fast approach in my opinion would be to use dnode-php for that.

You can see a brief introduction here. Simple, quick and easy!

XPath to select multiple tags

One correct answer is:

/a/b/*[self::c or self::d or self::e]

Do note that this

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

is both too-long and incorrect. This XPath expression will select nodes like:

OhMy:c

NotWanted:d 

QuiteDifferent:e

How do I get first element rather than using [0] in jQuery?

You can use the first method:

$('li').first()

http://api.jquery.com/first/

btw I agree with Nick Craver -- use document.getElementById()...

Parse string to DateTime in C#

var dateStr = @"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);

Check out this link for other format strings!

span with onclick event inside a tag

When you click on hide me, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide()

You can see this for more clarification

http://jsfiddle.net/jzn82/

jQuery datepicker, onSelect won't work

The function datepicker is case sensitive and all lowercase. The following however works fine for me:

$(document).ready(function() {
  $('.date-pick').datepicker( {
    onSelect: function(date) {
        alert(date);
    },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1
  });
});

YouTube iframe API: how do I control an iframe player that's already in the HTML?

You can do this with far less code:

function callPlayer(func, args) {
    var i = 0,
        iframes = document.getElementsByTagName('iframe'),
        src = '';
    for (i = 0; i < iframes.length; i += 1) {
        src = iframes[i].getAttribute('src');
        if (src && src.indexOf('youtube.com/embed') !== -1) {
            iframes[i].contentWindow.postMessage(JSON.stringify({
                'event': 'command',
                'func': func,
                'args': args || []
            }), '*');
        }
    }
}

Working example: http://jsfiddle.net/kmturley/g6P5H/296/

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

In my case the error got resolved by migrating to OpenCV 4.0 (or higher).

Convert JS Object to form data

Here is a short and sweet solution using Object.entries() that will take care of even your nested objects.

// If this is the object you want to convert to FormData...
const item = {
    description: 'First item',
    price: 13,
    photo: File
};

const formData = new FormData();

Object.entries(item).forEach(([key, value]) => {
    formData.append(key, value);
});

// At this point, you can then pass formData to your handler method

Read more about Object.entries() over here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

For Windows, I was able to get it working by enabling TLS for secure communication on the SMTP Virtual server. TLS will not be available on the SMTP virtual server without a certificate. This link will give the steps needed.

https://support.microsoft.com/en-ie/help/4014125/how-to-configure-iis-smtp-for-outgoing-tls-authentication

How can I stream webcam video with C#?

You could just use VideoLAN. VideoLAN will work as a server (or you can wrap your own C# application around it for more control). There are also .NET wrappers for the viewer that you can use and thus embed in your C# client.

Regex to match 2 digits, optional decimal, two digits

To build on Lee's answer, you need to anchor the expression to satisfy the requirement of not having more than 2 numbers before the decimal.

If each number is a separate string, you can use the string anchors:

^\d{0,2}(\.\d{1,2})?$

If each number is within a string, you can use the word anchors:

\b\d{0,2}(\.\d{1,2})?\b

Allow 2 decimal places in <input type="number">

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

How to import multiple .csv files at once?

Here are some options to convert the .csv files into one data.frame using R base and some of the available packages for reading files in R.

This is slower than the options below.

# Get the files names
files = list.files(pattern="*.csv")
# First apply read.csv, then rbind
myfiles = do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))

Edit: - A few more extra choices using data.table and readr

A fread() version, which is a function of the data.table package. This is by far the fastest option in R.

library(data.table)
DT = do.call(rbind, lapply(files, fread))
# The same using `rbindlist`
DT = rbindlist(lapply(files, fread))

Using readr, which is another package for reading csv files. It's slower than fread, faster than base R but has different functionalities.

library(readr)
library(dplyr)
tbl = lapply(files, read_csv) %>% bind_rows()

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

What is :: (double colon) in Python when subscripting sequences?

Python uses the :: to separate the End, the Start, and the Step value.

How to redirect output of an entire shell script within the script itself?

Addressing the question as updated.

#...part of script without redirection...

{
    #...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...

#...residue of script without redirection...

The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (Yes, that can be made more precise; if you want to quibble, let me know.)

You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.

The relevant sections of the Bash manual are Grouping Commands and I/O Redirection. The relevant sections of the POSIX shell specification are Compound Commands and I/O Redirection. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.

Javascript Equivalent to C# LINQ Select

Had to merge this nice answers. It revealed something like that;

Extension;

 Array.prototype.where = function (filter) {

                                var collection = this;

                                switch (typeof filter) {

                                    case 'function':
                                        return $.grep(collection, filter);

                                    case 'object':
                                        for (var property in filter) {
                                            if (!filter.hasOwnProperty(property))
                                                continue; // ignore inherited properties

                                            collection = $.grep(collection, function (item) {
                                                return item[property] === filter[property];
                                            });
                                        }
                                        return collection.slice(0); // copy the array 
                                    // (in case of empty object filter)

                                    default:
                                        throw new TypeError('func must be either a' +
                                            'function or an object of properties and values to filter by');
                                }
                            };

Usage;



masterTableView.get_dataItems().where(function (t) {
if (t.findElement("_invoiceGridCheckbox").checked) {
    invoiceIds.push(t.getDataKeyValue("Id"));
  }
});

Environment variables in Mac OS X

For 2020 Mac OS X Catalina users:

Forget about other useless answers, here only two steps needed:

  1. Create a file with the naming convention: priority-appname. Then copy-paste the path you want to add to PATH.

    E.g. 80-vscode with content /Applications/Visual Studio Code.app/Contents/Resources/app/bin/ in my case.

  2. Move that file to /etc/paths.d/. Don't forget to open a new tab(new session) in the Terminal and type echo $PATH to check that your path is added!

Notice: this method only appends your path to PATH.

Why must wait() always be in synchronized block

The problem it may cause if you do not synchronize before wait() is as follows:

  1. If the 1st thread goes into makeChangeOnX() and checks the while condition, and it is true (x.metCondition() returns false, means x.condition is false) so it will get inside it. Then just before the wait() method, another thread goes to setConditionToTrue() and sets the x.condition to true and notifyAll().
  2. Then only after that, the 1st thread will enter his wait() method (not affected by the notifyAll() that happened few moments before). In this case, the 1st thread will stay waiting for another thread to perform setConditionToTrue(), but that might not happen again.

But if you put synchronized before the methods that change the object state, this will not happen.

class A {

    private Object X;

    makeChangeOnX(){
        while (! x.getCondition()){
            wait();
            }
        // Do the change
    }

    setConditionToTrue(){
        x.condition = true; 
        notifyAll();

    }
    setConditionToFalse(){
        x.condition = false;
        notifyAll();
    }
    bool getCondition(){
        return x.condition;
    }
}

What is the difference between a port and a socket?

A port denotes a communication endpoint in the TCP and UDP transports for the IP network protocol. A socket is a software abstraction for a communication endpoint commonly used in implementations of these protocols (socket API). An alternative implementation is the XTI/TLI API.

See also:

Stevens, W. R. 1998, UNIX Network Programming: Networking APIs: Sockets and XTI; Volume 1, Prentice Hall.
Stevens, W. R., 1994, TCP/IP Illustrated, Volume 1: The Protocols, Addison-Wesley.

Using Alert in Response.Write Function in ASP.NET

Replace:

Response.Write("<script language=javascript>alert('ERROR');</script>);

With

Response.Write("<script language=javascript>alert('ERROR');</script>");

In other words, you're missing a closing " at the end of the Response.Write statement.

It's worth mentioning that the code shown in the screenshot appears to correctly contain a closing double quote, however your best bet overall would be to use the ClientScriptManager.RegisterScriptBlock method:

var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true);

This will take care of wrapping the script with <script> tags and writing the script into the page for you.

Force update of an Android app when a new version is available

What should definitely be mentioned here is the soon-to-be released In-app Updates API.

You'll have two options with this API; the first is a full-screen experience for critical updates when you expect the user to wait for the update to be applied immediately. The second option is a flexible update, which means the user can keep using the app while the update is downloaded. You can completely customize the update flow so it feels like part of your app.

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

Where do you include the jQuery library from? Google JSAPI? CDN?

In addition to people who advices to host it on own server, I'd proposed to keep it on separate domain (e.g. static.website.com) to allow browsers to load it into separate from other content thread. This tip also works for all static stuff, say images and css.

MySQL create stored procedure syntax with delimiter

Here is my code to create procedure in MySQL :

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `procedureName`(IN comId int)
BEGIN
select * from tableName 
         (add joins OR sub query as per your requirement)
         Where (where condition here)
END $$
DELIMITER ;

To call this procedure use this query :

call procedureName(); // without parameter
call procedureName(id,pid); // with parameter

Detail :

1) DEFINER : root is the user name and change it as per your username of mysql localhost is the host you can change it with ip address of the server if you are execute this query on hosting server.

Read here for more detail

:first-child not working as expected

The h1:first-child selector means

Select the first child of its parent
if and only if it's an h1 element.

The :first-child of the container here is the ul, and as such cannot satisfy h1:first-child.

There is CSS3's :first-of-type for your case:

.detail_container h1:first-of-type
{
    color: blue;
} 

But with browser compatibility woes and whatnot, you're better off giving the first h1 a class, then targeting that class:

.detail_container h1.first
{
    color: blue;
}

HRESULT: 0x800A03EC on Worksheet.range

Simply, the excel file is corrupt. Best solution is change/repair the file.(make a copy of the existing file and rename it)

How to auto-indent code in the Atom editor?

I found the option in the menu, under Edit > Lines > Auto Indent. It doesn't seem to have a default keymap bound.

You could try to add a key mapping (Atom > Open Your Keymap [on Windows: File > Settings > Keybindings > "your keymap file"]) like this one:

'atom-text-editor':
  'cmd-alt-l': 'editor:auto-indent'

It worked for me :)


For Windows:

'atom-text-editor':
  'ctrl-alt-l': 'editor:auto-indent'

Interfaces vs. abstract classes

The real question is: whether to use interfaces or base classes. This has been covered before.

In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.

Angular2 - Focusing a textbox on component load

you can use $ (jquery) :

<div>
    <form role="form" class="form-horizontal ">        
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>
                <div class="col-md-7 col-sm-7">
                    <input id="txtname`enter code here`" type="text" [(ngModel)]="person.Name" class="form-control" />

                </div>
                <div class="col-md-2 col-sm-2">
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>
                <div class="col-md-7 col-sm-7">
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>
                </div>
            </div>
        </div>        
    </form>
</div>

then in ts :

    declare var $: any;

    @Component({
      selector: 'app-my-comp',
      templateUrl: './my-comp.component.html',
      styleUrls: ['./my-comp.component.css']
    })
    export class MyComponent  {

    @ViewChild('loadedComponent', { read: ElementRef, static: true }) loadedComponent: ElementRef<HTMLElement>;

    setFocus() {
    const elem = this.loadedComponent.nativeElement.querySelector('#txtname');
          $(elem).focus();
    }
    }

How to clear the cache in NetBeans

Before 7.2, the cache is at C:\Users\username\.netbeans\7.0\var\cache. Deleting this directory should clear the cache for you.

Converting a year from 4 digit to 2 digit and back again in C#

I've seen some systems decide that the cutoff is 75; 75+ is 19xx and below is 20xx.

ASP.NET MVC Html.DropDownList SelectedValue

You can still name the DropDown as "UserId" and still have model binding working correctly for you.

The only requirement for this to work is that the ViewData key that contains the SelectList does not have the same name as the Model property that you want to bind. In your specific case this would be:

// in my controller
ViewData["Users"] = new SelectList(
    users, 
    "UserId", 
    "DisplayName", 
    selectedUserId.Value); // this has a value

// in my view
<%=Html.DropDownList("UserId", (SelectList)ViewData["Users"])%>

This will produce a select element that is named UserId, which has the same name as the UserId property in your model and therefore the model binder will set it with the value selected in the html's select element generated by the Html.DropDownList helper.

I'm not sure why that particular Html.DropDownList constructor won't select the value specified in the SelectList when you put the select list in the ViewData with a key equal to the property name. I suspect it has something to do with how the DropDownList helper is used in other scenarios, where the convention is that you do have a SelectList in the ViewData with the same name as the property in your model. This will work correctly:

// in my controller
ViewData["UserId"] = new SelectList(
    users, 
    "UserId", 
    "DisplayName", 
    selectedUserId.Value); // this has a value

// in my view
<%=Html.DropDownList("UserId")%>

Trying to use fetch and pass in mode: no-cors

mode: 'no-cors' won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from looking at contents of the response body and headers under all circumstances.” Of course you almost never want that.

What happens with cross-origin requests from frontend JavaScript is that browsers by default block frontend code from accessing resources cross-origin. If Access-Control-Allow-Origin is in a response, then browsers will relax that blocking and allow your code to access the response.

But if a site sends no Access-Control-Allow-Origin in its responses, your frontend code can’t directly access responses from that site. In particular, you can’t fix it by specifying mode: 'no-cors' (in fact that’ll ensure your frontend code can’t access the response contents).

However, one thing that will work: if you send your request through a CORS proxy.

You can also easily deploy your own proxy to Heroku in literally just 2-3 minutes, with 5 commands:

git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master

After running those commands, you’ll end up with your own CORS Anywhere server running at, for example, https://cryptic-headland-94862.herokuapp.com/.

Prefix your request URL with your proxy URL; for example:

https://cryptic-headland-94862.herokuapp.com/https://example.com

Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:

  1. Forwards the request to https://example.com.
  2. Receives the response from https://example.com.
  3. Adds the Access-Control-Allow-Origin header to the response.
  4. Passes that response, with that added header, back to the requesting frontend code.

The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS request, because in that case, the proxy also sends back the Access-Control-Allow-Headers and Access-Control-Allow-Methods headers needed to make the preflight successful.


I can hit this endpoint, http://catfacts-api.appspot.com/api/facts?number=99 via Postman

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why it is that even though you can access the response with Postman, browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin response header.

http://catfacts-api.appspot.com/api/facts?number=99 has no Access-Control-Allow-Origin response header, so there’s no way your frontend code can access the response cross-origin.

Your browser can get the response fine and you can see it in Postman and even in browser devtools—but that doesn’t mean browsers will expose it to your code. They won’t, because it has no Access-Control-Allow-Origin response header. So you must instead use a proxy to get it.

The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin header added is what the browser sees, so the browser lets your frontend code actually access the response.


So I am trying to pass in an object, to my Fetch which will disable CORS

You don’t want to do that. To be clear, when you say you want to “disable CORS” it seems you actually mean you want to disable the same-origin policy. CORS itself is actually a way to do that — CORS is a way to loosen the same-origin policy, not a way to restrict it.

But anyway, it’s true you can — in just your local environment — do things like give your browser runtime flags to disable security and run insecurely, or you can install a browser extension locally to get around the same-origin policy, but all that does is change the situation just for you locally.

No matter what you change locally, anybody else trying to use your app is still going to run into the same-origin policy, and there’s no way you can disable that for other users of your app.

You most likely never want to use mode: 'no-cors' in practice except in a few limited cases, and even then only if you know exactly what you’re doing and what the effects are. That’s because what setting mode: 'no-cors' actually says to the browser is, “Block my frontend JavaScript code from looking into the contents of the response body and headers under all circumstances.” In most cases that’s obviously really not what you want.


As far as the cases when you would want to consider using mode: 'no-cors', see the answer at What limitations apply to opaque responses? for the details. The gist of it is that the cases are:

  • In the limited case when you’re using JavaScript to put content from another origin into a <script>, <link rel=stylesheet>, <img>, <video>, <audio>, <object>, <embed>, or <iframe> element (which works because embedding of resources cross-origin is allowed for those) — but for some reason you don’t want to or can’t do that just by having the markup of the document use the resource URL as the href or src attribute for the element.

  • When the only thing you want to do with a resource is to cache it. As alluded to in the answer What limitations apply to opaque responses?, in practice the scenario that applies to is when you’re using Service Workers, in which case the API that’s relevant is the Cache Storage API.

But even in those limited cases, there are some important gotchas to be aware of; see the answer at What limitations apply to opaque responses? for the details.


I have also tried to pass in the object { mode: 'opaque'}

There is no mode: 'opaque' request mode — opaque is instead just a property of the response, and browsers set that opaque property on responses from requests sent with the no-cors mode.

But incidentally the word opaque is a pretty explicit signal about the nature of the response you end up with: “opaque” means you can’t see it.

How to "Open" and "Save" using java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing

CodeIgniter removing index.php from url

Follow these step your problem will be solved

1- Download .htaccess file from here https://www.dropbox.com/s/tupcu1ctkb8pmmd/.htaccess?dl=0

2- Change the CodeIgnitor directory name on Line #5. like my directory name is abc (add your name)

3- Save .htaccess file on main directory (abc) of your codeignitor folder

4- Change uri_protocol from AUTO to PATH_INFO in Config.php file

Note: First of all you have to enable mod_rewrite from httpd.conf of apachi by removing the comments

Combining (concatenating) date and time into a datetime

drop table test

create table test(
    CollectionDate date NULL,
    CollectionTime  [time](0) NULL,
    CollectionDateTime as (isnull(convert(datetime,CollectionDate)+convert(datetime,CollectionTime),CollectionDate))
-- if CollectionDate is datetime no need to convert it above
)

insert test (CollectionDate, CollectionTime)
values ('2013-12-10', '22:51:19.227'),
       ('2013-12-10', null),
       (null, '22:51:19.227')

select * from test

CollectionDate  CollectionTime  CollectionDateTime
2013-12-10      22:51:19        2013-12-10 22:51:19.000
2013-12-10      NULL            2013-12-10 00:00:00.000
NULL            22:51:19        NULL

Numpy array dimensions

First:

By convention, in Python world, the shortcut for numpy is np, so:

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

Second:

In Numpy, dimension, axis/axes, shape are related and sometimes similar concepts:

dimension

In Mathematics/Physics, dimension or dimensionality is informally defined as the minimum number of coordinates needed to specify any point within a space. But in Numpy, according to the numpy doc, it's the same as axis/axes:

In Numpy dimensions are called axes. The number of axes is rank.

In [3]: a.ndim  # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2

axis/axes

the nth coordinate to index an array in Numpy. And multidimensional arrays can have one index per axis.

In [4]: a[1,0]  # to index `a`, we specific 1 at the first axis and 0 at the second axis.
Out[4]: 3  # which results in 3 (locate at the row 1 and column 0, 0-based index)

shape

describes how many data (or the range) along each available axis.

In [5]: a.shape
Out[5]: (2, 2)  # both the first and second axis have 2 (columns/rows/pages/blocks/...) data

Javascript Array.sort implementation?

try this with quick sort:

function sort(arr, compareFn = (a, b) => a <= b) {

    if (!arr instanceof Array || arr.length === 0) {
        return arr;
    }

    if (typeof compareFn !== 'function') {
        throw new Error('compareFn is not a function!');
    }

    const partition = (arr, low, high) => {
        const pivot = arr[low];
        while (low < high) {
            while (low < high && compareFn(pivot, arr[high])) {
                --high;
            }
            arr[low] = arr[high];
            while (low < high && compareFn(arr[low], pivot)) {
                ++low;
            }
            arr[high] = arr[low];
        }
        arr[low] = pivot;
        return low;
    };

    const quickSort = (arr, low, high) => {
        if (low < high) {
            let pivot = partition(arr, low, high);
            quickSort(arr, low, pivot - 1);
            quickSort(arr, pivot + 1, high);
        }
        return arr;
    };

    return quickSort(arr, 0, arr.length - 1);
}

How to configure logging to syslog in Python?

I fix it on my notebook. The rsyslog service did not listen on socket service.

I config this line bellow in /etc/rsyslog.conf file and solved the problem:

$SystemLogSocketName /dev/log

How do you add swap to an EC2 instance?

You can use the following script to add swap on Amazon Linux.

https://github.com/chetankapoor/swap

Download the script using wget:

wget https://raw.githubusercontent.com/chetankapoor/swap/master/swap.sh -O swap.sh

Then run the script with the following format:

sh swap.sh 2G

For a complete tutorial you can visit:

https://installvirtual.com/shell-script-to-create-swap/

Open a selected file (image, pdf, ...) programmatically from my Android Application?

To Open a File in Android Programatically,you can use this code :- We use File Provider for internal file access .You can also see details about File Provider here in this linkfileprovidr1,file provider2,file provider3. Create a File Provider and defined in Manifest File .

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.packagename.app.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">

    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths">
    </meta-data>

</provider>

Define file_path in resources file.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="my_images"
        path="Android/data/com.packagename.app/files/Pictures" />

    <external-files-path name="vivalinkComProp" path="Android/data/com.vivalink.app/vivalinkComProp/docs"/>
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />

</paths>

Define Intent For View

String directory_path = Environment.getExternalStorageDirectory().getPath() + "/MyFile/";
String targetPdf = directory_path + fileName + ".pdf";
File filePath = new File(targetPdf);

Intent intentShareFile = new Intent(Intent.ACTION_VIEW);
File fileWithinMyDir = new File(targetPdf);
Uri bmpUri = FileProvider.getUriForFile(activity, "com.packagename.app.fileprovider", filePath);
if (fileWithinMyDir.exists()) {
    intentShareFile.setDataAndType(bmpUri,"application/pdf");
    intentShareFile.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intentShareFile.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(Intent.createChooser(intentShareFile, "Open File Using..."));

}

You can use different way to create a file provider in android . Hope this will help you.

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

AngularJS: How can I pass variables between controllers?

The following example shows how to pass variables between siblings controllers and take an action when the value changes.

Use case example: you have a filter in a sidebar that changes the content of another view.

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
_x000D_
  .factory('MyService', function() {_x000D_
_x000D_
    // private_x000D_
    var value = 0;_x000D_
_x000D_
    // public_x000D_
    return {_x000D_
      _x000D_
      getValue: function() {_x000D_
        return value;_x000D_
      },_x000D_
      _x000D_
      setValue: function(val) {_x000D_
        value = val;_x000D_
      }_x000D_
      _x000D_
    };_x000D_
  })_x000D_
  _x000D_
  .controller('Ctrl1', function($scope, $rootScope, MyService) {_x000D_
_x000D_
    $scope.update = function() {_x000D_
      MyService.setValue($scope.value);_x000D_
      $rootScope.$broadcast('increment-value-event');_x000D_
    };_x000D_
  })_x000D_
  _x000D_
  .controller('Ctrl2', function($scope, MyService) {_x000D_
_x000D_
    $scope.value = MyService.getValue();_x000D_
_x000D_
    $scope.$on('increment-value-event', function() {    _x000D_
      $scope.value = MyService.getValue();_x000D_
    });_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp">_x000D_
  _x000D_
  <h3>Controller 1 Scope</h3>_x000D_
  <div ng-controller="Ctrl1">_x000D_
    <input type="text" ng-model="value"/>_x000D_
    <button ng-click="update()">Update</button>_x000D_
  </div>_x000D_
  _x000D_
  <hr>_x000D_
  _x000D_
  <h3>Controller 2 Scope</h3>_x000D_
  <div ng-controller="Ctrl2">_x000D_
    Value: {{ value }}_x000D_
  </div>  _x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Lombok annotations do not compile under Intellij idea

In order to solve the problem set:

  • Preferences (Ctrl + Alt + S)
    • Build, Execution, Deployment
      • Compiler
        • Annotation Processors
          • Enable annotation processing

Make sure you have the Lombok plugin for IntelliJ installed!

  • Preferences -> Plugins
  • Search for "Lombok Plugin"
  • Click Browse repositories...
  • Choose Lombok Plugin
  • Install
  • Restart IntelliJ

Installing mcrypt extension for PHP on OSX Mountain Lion

I tend to use Homebrew on Mac. It will install and configure all the stuff for you.
http://mxcl.github.com/homebrew/

Then you should be able to install it with brew install mcrypt php53-mcrypt and it'll Just Work (tm).

You can replace the 53 with whatever version of PHP you're using, such as php56-mcrypt or php70-mcrypt. If you're not sure, use brew search php.

Do also remember that if you are using the built in Mac PHP it's installed into /usr/bin you can see which php you are using with which php at the terminal and it'll return the path.

Remove all special characters except space from a string using JavaScript

The first solution does not work for any UTF-8 alphabet. (It will cut text such as ??????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    }
    return res;
}

Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).

How can I get a file's size in C++?

Have you considered not computing the file size and just growing the array if necessary? Here's an example (with error checking ommitted):

#define CHUNK 1024

/* Read the contents of a file into a buffer.  Return the size of the file 
 * and set buf to point to a buffer allocated with malloc that contains  
 * the file contents.
 */
int read_file(FILE *fp, char **buf) 
{
  int n, np;
  char *b, *b2;

  n = CHUNK;
  np = n;
  b = malloc(sizeof(char)*n);
  while ((r = fread(b, sizeof(char), CHUNK, fp)) > 0) {
    n += r;
    if (np - n < CHUNK) { 
      np *= 2;                      // buffer is too small, the next read could overflow!
      b2 = malloc(np*sizeof(char));
      memcpy(b2, b, n * sizeof(char));
      free(b);
      b = b2;
    }
  }
  *buf = b;
  return n;
}

This has the advantage of working even for streams in which it is impossible to get the file size (like stdin).

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

When correctly use Task.Run and when just async-await

Note the guidelines for performing work on a UI thread, collected on my blog:

  • Don't block the UI thread for more than 50ms at a time.
  • You can schedule ~100 continuations on the UI thread per second; 1000 is too much.

There are two techniques you should use:

1) Use ConfigureAwait(false) when you can.

E.g., await MyAsync().ConfigureAwait(false); instead of await MyAsync();.

ConfigureAwait(false) tells the await that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async method (after the ConfigureAwait), you cannot do anything that assumes you're in the current context (e.g., update UI elements).

For more information, see my MSDN article Best Practices in Asynchronous Programming.

2) Use Task.Run to call CPU-bound methods.

You should use Task.Run, but not within any code you want to be reusable (i.e., library code). So you use Task.Run to call the method, not as part of the implementation of the method.

So purely CPU-bound work would look like this:

// Documentation: This method is CPU-bound.
void DoWork();

Which you would call using Task.Run:

await Task.Run(() => DoWork());

Methods that are a mixture of CPU-bound and I/O-bound should have an Async signature with documentation pointing out their CPU-bound nature:

// Documentation: This method is CPU-bound.
Task DoWorkAsync();

Which you would also call using Task.Run (since it is partially CPU-bound):

await Task.Run(() => DoWorkAsync());

How do I remove packages installed with Python's easy_install?

try

$ easy_install -m [PACKAGE]

then

$ rm -rf .../python2.X/site-packages/[PACKAGE].egg

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

I just solved this error for myself, but it was a bit silly on my part. Still worth checking if the above doesn't help you.

In my case, I was editing the config files in /etc/phpmyadmin, my install was located in /usr/share/phpmyadmin, and my install was not actually opening the /etc/phpmyadmin config files, as I thought it would. So I just did this command:

ln -s /etc/phpmyadmin/conf* /usr/share/phpmyadmin

For those not in the know, ln -s makes a soft link (basically a shortcut). So that command just makes shortcuts from the config files in /etc to the /usr/share install.

By the way, I figured this out after using the program opensnoop, which shows you what files are being opened (technically, traces open() syscalls and the pid of the process, as they happen), which you can install on Ubuntu with apt-get install perf-tools-unstable, or you can get it here.

Create WordPress Page that redirects to another URL

(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)

I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php all the time, or fiddle around with your server settings on each addition (I do not like both).

TLTR

You can add a filter on the actual WP permalink function you need (for me it was post_link, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.

This is ok, because the post is an alias, so you won't need the content anyways.

First step is to open the alias post and put the ID of the referenced post as content (and nothing else):

enter image description here

Next, open your functions.php and add:

function prefix_filter_post_permalink($url, $post) {
    // if the content of the post to get the permalink for is just a number...
    if (is_numeric($post->post_content)) {
        // instead, return the permalink for the post that has this ID
        return get_the_permalink((int)$post->post_content);
    }
    return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );

That's it

Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.

This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP code is far from ideal, but like this for making the point readable.

What does if __name__ == "__main__": do?

All the answers have pretty much explained the functionality. But I will provide one example of its usage which might help clearing out the concept further.

Assume that you have two Python files, a.py and b.py. Now, a.py imports b.py. We run the a.py file, where the "import b.py" code is executed first. Before the rest of the a.py code runs, the code in the file b.py must run completely.

In the b.py code there is some code that is exclusive to that file b.py and we don't want any other file (other than b.py file), that has imported the b.py file, to run it.

So that is what this line of code checks. If it is the main file (i.e., b.py) running the code, which in this case it is not (a.py is the main file running), then only the code gets executed.

SQL query to get the deadlocks in SQL SERVER 2008

In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.

I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:

DBCC TRACEON(1222, -1);

A quick search yielded this tutorial:

http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/

Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.

Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:

enter image description here

Disclaimer: I work for SQL Sentry.

how to stop Javascript forEach?

jQuery provides an each() method, not forEach(). You can break out of each by returning false. forEach() is part of the ECMA-262 standard, and the only way to break out of that that I'm aware of is by throwing an exception.

function recurs(comment) {
  try {
    comment.comments.forEach(function(elem) {
      recurs(elem);
      if (...) throw "done";
    });
  } catch (e) { if (e != "done") throw e; }
}

Ugly, but does the job.

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

regular expression for anything but an empty string

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character

References

Related questions

How to change Oracle default data pump directory to import dumpfile?

use DIRECTORY option.

Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907

  DIRECTORY

  Default: DATA_PUMP_DIR

  Purpose

  Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.

  Syntax and Description

  DIRECTORY=directory_object
  The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.

  A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.

  Example

  The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".

  > impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp 
  LOGFILE=dpump_dir2:expfull.log
  This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.