Programs & Examples On #Jform designer

JForm-Designer is a Java/Swing GUI Designer which can be used both standalone or a plugin

How to add anchor tags dynamically to a div in Javascript?

var newA = document.createElement('a');
newA.setAttribute('href',"http://localhost");
newA.innerHTML = "link text";
document.appendChild(newA);

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

refer intel.com's requirements : Important: Intel HAXM cannot be used on systems without an Intel processor, or with an Intel processor that lacks the hardware features described in the "Hardware Requirements" section above.To determine the capabilities of your Intel processor

[Installation Instructions for Intel® Hardware Accelerated Execution Manager ] https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-mac-os-x

My PC does not support vt-x, I can not use android studio 1.0.2.

Does calling clone() on an array also clone its contents?

If I invoke clone() method on array of Objects of type A, how will it clone its elements?

The elements of the array will not be cloned.

Will the copy be referencing to the same objects?

Yes.

Or will it call (element of type A).clone() for each of them?

No, it will not call clone() on any of the elements.

To show error message without alert box in Java Script

Try this code

<html>
<head>
 <script type="text/javascript">
 function validate() {
  if(myform.fname.value.length==0)
  {
document.getElementById('errfn').innerHTML="this is invalid name";
  }
 }
 </script>
</head>
<body>
 <form name="myform">
  First_Name
  <input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn">   </div>

<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>

<br>
<input type=button value=check> 

</form>
</body>
</html>

How do I get the value of a textbox using jQuery?

By Using

$("#txtEmail").val()

you get the actual value of the element

Testing javascript with Mocha - how can I use console.log to debug a test?

If you are testing asynchronous code, you need to make sure to place done() in the callback of that asynchronous code. I had that issue when testing http requests to a REST API.

Bash script error [: !=: unary operator expected

Quotes!

if [ "$1" != -v ]; then

Otherwise, when $1 is completely empty, your test becomes:

[ != -v ]

instead of

[ "" != -v ]

...and != is not a unary operator (that is, one capable of taking only a single argument).

What's the difference between jquery.js and jquery.min.js?

Both contain the same functionality but the .min.js equivalent has been optimized in size. You can open both files and take a look at them. In the .min.js file you'll notice that all variables names have been reduced to short names and that most whitespace & comments have been taken out.

How To: Best way to draw table in console app (C#)

public static void ToPrintConsole(this DataTable dataTable)
    {
        // Print top line
        Console.WriteLine(new string('-', 75));

        // Print col headers
        var colHeaders = dataTable.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName);
        foreach (String s in colHeaders)
        {
            Console.Write("| {0,-20}", s);
        }
        Console.WriteLine();

        // Print line below col headers
        Console.WriteLine(new string('-', 75));

        // Print rows
        foreach (DataRow row in dataTable.Rows)
        {
            foreach (Object o in row.ItemArray)
            {
                Console.Write("| {0,-20}", o.ToString());
            }
            Console.WriteLine();
        }

        // Print bottom line
        Console.WriteLine(new string('-', 75));
    }

The AWS Access Key Id does not exist in our records

another thing that can cause this, even if everything is set up correctly, is running the command from a Makefile. for example, I had a rule:

awssetup:
        aws configure
        aws s3 sync s3://mybucket.whatever .

when I ran make awssetup I got the error: fatal error: An error occurred (InvalidAccessKeyId) when calling the ListObjects operation: The AWS Access Key Id you provided does not exist in our records.. but running it from the command line worked.

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.

Java method to swap primitives

Try this magic

public static <T> void swap(T a, T b) {
    try {
        Field[] fields = a.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object temp = field.get(a);
            field.set(a, field.get(b));
            field.set(b, temp);
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

And test it!

    System.out.println("a:" + a);
    System.out.println("b:" + b);
    swap(a,b);
    System.out.println("a:" + a);
    System.out.println("b:" + b);

Disable Rails SQL logging in console

Here's a variation I consider somewhat cleaner, that still allows potential other logging from AR. In config/environments/development.rb :

config.after_initialize do
  ActiveRecord::Base.logger = Rails.logger.clone
  ActiveRecord::Base.logger.level = Logger::INFO
end

How to change the font size on a matplotlib plot

The changes to the rcParams are very granular, most of the time all you want is just scaling all of the font sizes so they can be seen better in your figure. The figure size is a good trick but then you have to carry it for all of your figures. Another way (not purely matplotlib, or maybe overkill if you don't use seaborn) is to just set the font scale with seaborn:

sns.set_context('paper', font_scale=1.4)

DISCLAIMER: I know, if you only use matplotlib then probably you don't want to install a whole module for just scaling your plots (I mean why not) or if you use seaborn, then you have more control over the options. But there's the case where you have the seaborn in your data science virtual env but not using it in this notebook. Anyway, yet another solution.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

Setting default value in select drop-down using Angularjs

we should use name value pair binding values into dropdown.see the code for more details

_x000D_
_x000D_
function myCtrl($scope) {_x000D_
     $scope.statusTaskList = [_x000D_
        { name: 'Open', value: '1' },_x000D_
        { name: 'In Progress', value: '2' },_x000D_
        { name: 'Complete', value: '3' },_x000D_
        { name: 'Deleted', value: '4' },_x000D_
    ];_x000D_
    $scope.atcStatusTasks = $scope.statusTaskList[0]; // 0 -> Open _x000D_
}
_x000D_
<select ng-model="atcStatusTasks" ng-options="s.name for s in statusTaskList"></select>
_x000D_
_x000D_
_x000D_

Python convert csv to xlsx

First install openpyxl:

pip install openpyxl

Then:

from openpyxl import Workbook
import csv


wb = Workbook()
ws = wb.active
with open('test.csv', 'r') as f:
    for row in csv.reader(f):
        ws.append(row)
wb.save('name.xlsx')

calling Jquery function from javascript

jQuery functions are called just like JavaScript functions.

For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:

$("#orderedlist").addClass("red");

As opposed to a regular line of JavaScript calling a regular function:

var x = document.getElementById("orderedlist");

addClass() is a jQuery function, getElementById() is a JavaScript function.

The dollar sign function makes the jQuery addClass function available.

The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.

In your code

$(function() {
// code to execute when the DOM is ready
});

Is used to specify code to run when the DOM is ready.

It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.

So, to answer your question, just call functions you defined as you normally would.

//create a function
function my_fun(){
  // call a jQuery function:
  $("#orderedlist").addClass("red");
}

//call the function you defined:
myfun();

Rethrowing exceptions in Java without losing the stack trace

In Java is almost the same:

try
{
   ...
}
catch (Exception e)
{
   if (e instanceof FooException)
     throw e;
}

Implement a loading indicator for a jQuery AJAX call

This is how I realised the loading indicator by an Glyphicon:

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>

    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"></script>

    <style>
        .gly-ani {
          animation: ani 2s infinite linear;
        }
        @keyframes ani {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(359deg);
          }
        }
    </style>  
</head>

<body>
<div class="container">

    <span class="glyphicon glyphicon-refresh gly-ani" style="font-size:40px;"></span>

</div>
</body>

</html>

How can I enable the Windows Server Task Scheduler History recording?

This may help others where there is no option to Enable/Disable the history anywhere in Task Scheduler.

Open Event Viewer (either in Computer Management or Admin Tools > Event Viewer).

In Event Viewer make sure the Preview Pane is showing (View > Preview Pane should be ticked)

In the left hand pane expand Application and Service Logs then Microsoft, Windows, TaskScheduler and then select Operational.

You should have Actions showing in the preview pane with two sections - Operational and below that Event nnn, TaskScheduler. One of the items listed in the Operational section should be Properties. Click this item and the Enable Logging option is on the General tab.

My problem was that the maximum log size had been reached and even though the overwrite old events option was selected it wasn't logging new events. I suspect that might have been a permissions issue but I changed it to Archive when full and all is now working again.

Hope this helps someone else out there. If you don't have the options I've mentioned above I'm sorry, but I don't know where you should look.

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

You can find information and a little description of the MBDB/MBDX format here:

http://code.google.com/p/iphonebackupbrowser/

This is my application to browse the backup files. I have tried to document the format of the new files that come with iTunes 9.2.

What is the difference between Html.Hidden and Html.HiddenFor

The Html.Hidden creates a hidden input but you have to specify the name and all the attributes you want to give that field and value. The Html.HiddenFor creates a hidden input for the object that you pass to it, they look like this:

Html.Hidden("yourProperty",model.yourProperty);

Html.HiddenFor(m => m.yourProperty)

In this case the output is the same!

make bootstrap twitter dialog modal draggable

i did this:

$("#myModal").modal({}).draggable();

and it make my very standard/basic modal draggable.

not sure how/why it worked, but it did.

Ignoring directories in Git repositories on Windows

It seems that for ignoring files and directories there are two main ways:

  1. .gitignore

    • Placing .gitignore file into the root of your repository besides the .git folder (in Windows, make sure you see the true file extension and then make .gitignore. (with the point at the end to make an empty file extension))
    • Making the global configuration ~/.gitignore_global and running git config --global core.excludesfile ~/.gitignore_global to add this to your Git configuration

    Note: files tracked before can be untracked by running git rm --cached filename

  2. Repository exclude - For local files that do not need to be shared, you just add the file pattern or directory to the file .git/info/exclude. Theses rules are not committed, so they are not seen by other users. More information is here.

To make exceptions in the list of ignored files, see this question.

Create an ArrayList with multiple object types?

I am also newish to Java and just figured this out. You should create your own class which stores the string and integer, and then make a list of these objects. For instance (I am sure this code is imperfect, but better than arrayList):

class Stuff {
    private String label;
    private Integer value;

    // Constructor or setter
    public void Stuff(String label, Integer value) {
        if (label == null || value == null) {
            return;
        }
        this.label = label;
        this.value = value;
    }

    // getters

    public String getLabel() {
        return this.label;
    }

    public Integer getValue() {
        return this.value;
    }
}

Then in your code:

private ArrayList<Stuff> items = new ArrayList<Stuff>();
items.add(new Stuff(label, value));

for (Stuff item: items) {
     doSomething(item.getLabel()); // returns String
     doSomething(item.getValue()); // returns Integer
}

How to send a POST request using volley with string body?

You can refer to the following code (of course you can customize to get more details of the network response):

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("Title", "Android Volley Demo");
    jsonBody.put("Author", "BNK");
    final String requestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {
                responseString = String.valueOf(response.statusCode);
                // can get more details such as response.headers
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

compression and decompression of string data in java

You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?

creating custom tableview cells in swift

[1] First Design your tableview cell in StoryBoard.

[2] Put below table view delegate method

//MARK: - Tableview Delegate Methods

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

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

    return <“Your Array”>
}


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{

    var totalHeight : CGFloat = <cell name>.<label name>.frame.origin.y    

    totalHeight +=   UpdateRowHeight(<cell name>.<label name>, textToAdd: <your array>[indexPath.row])    

    return totalHeight
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{


    var cell : <cell name>! = tableView.dequeueReusableCellWithIdentifier(“<cell identifire>”, forIndexPath: indexPath) as! CCell_VideoCall

    if(cell == nil)
    {
        cell = NSBundle.mainBundle().loadNibNamed("<cell identifire>", owner: self, options: nil)[0] as! <cell name>;
    }


    <cell name>.<label name>.text = <your array>[indexPath.row] as? String



    return cell as <cell name>
}

//MARK: - Custom Methods

func UpdateRowHeight ( ViewToAdd : UILabel , textToAdd : AnyObject  ) -> CGFloat{


    var actualHeight : CGFloat = ViewToAdd.frame.size.height

    if let strName : String? = (textToAdd as? String)
        where !strName!.isEmpty
    {

        actualHeight = heightForView1(strName!, font: ViewToAdd.font, width: ViewToAdd.frame.size.width, DesignTimeHeight: actualHeight )

    }
    return actualHeight
}

SQL update trigger only when column is modified

Whenever a record has updated a record is "deleted". Here is my example:

ALTER TRIGGER [dbo].[UpdatePhyDate]
   ON  [dbo].[M_ContractDT1]
   AFTER UPDATE
AS 
BEGIN
    -- on ContarctDT1 PhyQty is updated 
    -- I want system date in Phytate automatically saved
    SET NOCOUNT ON;

    declare @dt1ky as int   

    if(update(Phyqty))
    begin
        select @dt1ky = dt1ky from deleted

        update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky=  @dt1ky     

    end

END

It works fine

'if' in prolog?

I found this helpful for using an if statement in a rule.

max(X,Y,Z) :-
    (  X =< Y
    -> Z = Y
    ;  Z = X
    ).

Thanks to http://cs.union.edu/~striegnk/learn-prolog-now/html/node89.html

send bold & italic text on telegram bot with html

For JS:

First, if you haven't installed telegram bot just install with the command

npm i messaging-api-telegram

Now, initialize its client with

const client = new TelegramClient({
    accessToken: process.env.<TELEGRAM_ACCESS_TOKEN>
});

Then, to send message use sendMessage() async function like below -

    const resp = await client.sendMessage(chatId, msg, {
        disableWebPagePreview: false,
        disableNotification: false,
        parseMode: "HTML"
    });

Here parse mode by default would be plain text but with parseOptions parseMode we can do 1. "HTML" and "MARKDOWN" to let use send messages in stylish way. Also get your access token of bot from telegram page and chatId or group chat Id from same.

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

SET NAMES utf8 in MySQL?

Not only PDO. If sql answer like '????' symbols, preset of you charset (hope UTF-8) really recommended:

if (!$mysqli->set_charset("utf8")) 
 { printf("Can't set utf8: %s\n", $mysqli->error); }

or via procedure style mysqli_set_charset($db,"utf8")

Difference between margin and padding?

margin = space around (outside) the element from border outwards.

padding = space around (inside) the element from text to border.

see here: http://jsfiddle.net/robx/GaMpq/

Any free WPF themes?

We use the Assergs Application Framework themes:

http://www.codeplex.com/appfx

They have a nice office look and feel to it :)

Install specific version using laravel installer

you can find all version install code here by changing the version of laravel doc

composer create-project --prefer-dist laravel/laravel yourProjectName "5.1.*"

above code for creating laravel 5.1 version project. see more in laravel doc. happy coding!!

Intellij Cannot resolve symbol on import

IntelliJ has issues in resolving the dependencies. Try the following:

  1. Right click on pom.xml -> Maven -> Reimport
  2. Again Right click on pom.xml -> Maven -> Generate sources and update folders

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

I am in ubuntu 14.04 and mongod is registered as an upstart service. The answers in this post sent me in the right direction. The only adaptation I had to do to make things work with the upstart service was to edit /etc/mongod.conf. Look for the lines that read:

# Enable the HTTP interface (Defaults to port 28017).
# httpinterface = true

Just remove the # in front of httpinterface and restart the mongod service:

sudo restart mongod

Note: You can also enable the rest interface by adding a line that reads rest=true right below the httpinterface line mentioned above.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Wanted to share what caused the error in my case. Spend couple hours to figure this out, so hopefully it will help to save someone some time.

Strangely enough, the error was raised with the Enable drop directory quota setting being enabled for the domain.

enter image description here

I am not the expert and don't know the technical explanation, but unticking the mentioned setting sorted the problem.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

if your application accepts errors raise from Oracle, then you can use it. we have an application, each time when an error happens, we call raise_application_error, the application will popup a red box to show the error message we provide through this method.

When using dotnet code, I just use "raise", dotnet exception mechanisim will automatically capture the error passed by Oracle ODP and shown inside my catch exception code.

No shadow by default on Toolbar?

If you are seting the ToolBar as ActionBar then just call:

getSupportActionBar().setElevation(YOUR_ELEVATION);

Note: This must be called after setSupportActionBar(toolbar);

Best way to check if a URL is valid

Given issues with filter_var() needing http://, I use:

$is_url = filter_var($filename, FILTER_VALIDATE_URL) || array_key_exists('scheme', parse_url($filename));

How to create a numeric vector of zero length in R

If you read the help for vector (or numeric or logical or character or integer or double, 'raw' or complex etc ) then you will see that they all have a length (or length.out argument which defaults to 0

Therefore

numeric()
logical()
character()
integer()
double()
raw()
complex() 
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')

All return 0 length vectors of the appropriate atomic modes.

# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')

Does java.util.List.isEmpty() check if the list itself is null?

No java.util.List.isEmpty() doesn't check if a list is null.

If you are using Spring framework you can use the CollectionUtils class to check if a list is empty or not. It also takes care of the null references. Following is the code snippet from Spring framework's CollectionUtils class.

public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

Even if you are not using Spring, you can go on and tweak this code to add in your AppUtil class.

django admin - add custom form fields that are not part of the model

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)

    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)

        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:
            instance.save()

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

how can I enable PHP Extension intl?

All you need to do is go to php.ini in your xampp folder (xampp\php\php.ini) and remove ; from ;extension=php_intl.dll

;extension=php_intl.dll

TO

extension=php_intl.dll

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

I have got the same issue when tried to get users information without auth.

Check if you have loggen in before any request.

 $uid = $facebook->getUser();

 if ($uid){
      $me = $facebook->api('/me');
 }

The code above should solve your issue.

How to remove all options from a dropdown using jQuery / JavaScript

You didn't say on which event.Just use below on your event listener.Or in your page load

$('#models').empty()

Then to repopulate

$.getJSON('@Url.Action("YourAction","YourController")',function(data){
 var dropdown=$('#models');
dropdown.empty();  
$.each(data, function (index, item) {
    dropdown.append(
        $('<option>', {
            value: item.valueField,
            text: item.DisplayField
        }, '</option>'))
      }
     )});

Efficient way to remove ALL whitespace from String?

I have found different results to be true. I am trying to replace all whitespace with a single space and the regex was extremely slow.

return( Regex::Replace( text, L"\s+", L" " ) );

What worked the most optimally for me (in C++ cli) was:

String^ ReduceWhitespace( String^ text )
{
  String^ newText;
  bool    inWhitespace = false;
  Int32   posStart = 0;
  Int32   pos      = 0;
  for( pos = 0; pos < text->Length; ++pos )
  {
    wchar_t cc = text[pos];
    if( Char::IsWhiteSpace( cc ) )
    {
      if( !inWhitespace )
      {
        if( pos > posStart ) newText += text->Substring( posStart, pos - posStart );
        inWhitespace = true;
        newText += L' ';
      }
      posStart = pos + 1;
    }
    else
    {
      if( inWhitespace )
      {
        inWhitespace = false;
        posStart = pos;
      }
    }
  }

  if( pos > posStart ) newText += text->Substring( posStart, pos - posStart );

  return( newText );
}

I tried the above routine first by replacing each character separately, but had to switch to doing substrings for the non-space sections. When applying to a 1,200,000 character string:

  • the above routine gets it done in 25 seconds
  • the above routine + separate character replacement in 95 seconds
  • the regex aborted after 15 minutes.

Printing PDFs from Windows Command Line

I had two problems with using Acrobat Reader for this task.

  1. The command line API is not officially supported, so it could change or be removed without warning.
  2. Send a print command to Reader loads up the GUI, with seemingly no way to prevent it. I needed the process to be transparent to the user.

I stumbled across this blog, that suggests using Foxit Reader. Foxit Reader is free, the API is almost identical to Acrobat Reader, but crucially is documented and does not load the GUI for print jobs.

A word of warning, don't just click through the install process without paying attention, it tries to install unrelated software as well. Why are software vendors still doing this???

Best way to remove from NSMutableArray while iterating?

Why don't you add the objects to be removed to another NSMutableArray. When you are finished iterating, you can remove the objects that you have collected.

How to edit CSS style of a div using C# in .NET

To expand on Peri's post & why we may not want to use viewstate the following code:

style="<%= _myCSS %>"

Protected _myCSS As String = "display: none"
Is the approach to look at if you're using AJAX, it allows for manipulating the display via asp.net back end code rather than jquery/jscript.

'Syntax Error: invalid syntax' for no apparent reason

I encountered a similar problem, with a syntax error that I knew should not be a syntax error. In my case it turned out that a Python 2 interpreter was trying to run Python 3 code, or vice versa; I think that my shell had a PYTHONPATH with a mixture of Python 2 and Python 3.

Linq to Sql: Multiple left outer joins

Don't have access to VisualStudio (I'm on my Mac), but using the information from http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx it looks like you may be able to do something like this:

var query = from o in dc.Orders
            join v in dc.Vendors on o.VendorId equals v.Id into ov
            from x in ov.DefaultIfEmpty()
            join s in dc.Status on o.StatusId equals s.Id into os
            from y in os.DefaultIfEmpty()
            select new { o.OrderNumber, x.VendorName, y.StatusName }

What is a serialVersionUID and why should I use it?

If you want to amend a huge number of classes which had no serialVersionUID set in the first place while maintain the compatibility with the old classes, tools like IntelliJ Idea, Eclipse fall short as they generate random numbers and does not work on a bunch of files in one go. I come up the following bash script(I'm sorry for Windows users, consider buy a Mac or convert to Linux) to make amending serialVersionUID issue with ease:

base_dir=$(pwd)                                                                  
src_dir=$base_dir/src/main/java                                                  
ic_api_cp=$base_dir/target/classes                                               

while read f                                                                     
do                                                                               
    clazz=${f//\//.}                                                             
    clazz=${clazz/%.java/}                                                       
    seruidstr=$(serialver -classpath $ic_api_cp $clazz | cut -d ':' -f 2 | sed -e 's/^\s\+//')
    perl -ni.bak -e "print $_; printf qq{%s\n}, q{    private $seruidstr} if /public class/" $src_dir/$f
done

you save the this script, say add_serialVersionUID.sh to you ~/bin. Then you run it in the root directory of your Maven or Gradle project like:

add_serialVersionUID.sh < myJavaToAmend.lst

This .lst includes the list of java files to add the serialVersionUID in the following format:

com/abc/ic/api/model/domain/item/BizOrderTransDO.java
com/abc/ic/api/model/domain/item/CardPassFeature.java
com/abc/ic/api/model/domain/item/CategoryFeature.java
com/abc/ic/api/model/domain/item/GoodsFeature.java
com/abc/ic/api/model/domain/item/ItemFeature.java
com/abc/ic/api/model/domain/item/ItemPicUrls.java
com/abc/ic/api/model/domain/item/ItemSkuDO.java
com/abc/ic/api/model/domain/serve/ServeCategoryFeature.java
com/abc/ic/api/model/domain/serve/ServeFeature.java
com/abc/ic/api/model/param/depot/DepotItemDTO.java
com/abc/ic/api/model/param/depot/DepotItemQueryDTO.java
com/abc/ic/api/model/param/depot/InDepotDTO.java
com/abc/ic/api/model/param/depot/OutDepotDTO.java

This script uses the JDK serialVer tool under hood. So make sure your $JAVA_HOME/bin is in the PATH.

makefile:4: *** missing separator. Stop

Your version of Linux doesn't support this kind of functionality please go for another suitable version i.e. Kali Linux or Red Hat.

CSS to make table 100% of max-width

I have a very well working solution for tables of max-width: 100%. Just use word-break: break-all; for the table cells (except heading cells) to break all long text into several lines:

<!DOCTYPE html>
<html>
<head>
<style>

table {
  max-width: 100%; 
}
table td {
  word-break: break-all;
}

</style>
</head>
<body>

<table border="1">
  <tr>
    <th><strong>Input</strong></th>
    <th><strong>Output</strong></th>
  </tr>
  <tr>
    <td>some text</td>
    <td>12b6459fc6b4cabb4b1990be1a78e4dc5fa79c3a0fe9aa9f0386d673cfb762171a4aaa363b8dac4c33e0ad23e4830888</td>
  </tr>
</table>

</body>
</html>

This will render like this (when the screen width is limited):

Getting the WordPress Post ID of current post

Try using this:

$id = get_the_ID();

LINQ Orderby Descending Query

I think the second one should be

var itemList = (from t in ctn.Items
                where !t.Items && t.DeliverySelection
                select t).OrderByDescending(c => c.Delivery.SubmissionDate);

How to set session timeout dynamically in Java web applications?

Is there a way to set the session timeout programatically

There are basically three ways to set the session timeout value:

  • by using the session-timeout in the standard web.xml file ~or~
  • in the absence of this element, by getting the server's default session-timeout value (and thus configuring it at the server level) ~or~
  • programmatically by using the HttpSession. setMaxInactiveInterval(int seconds) method in your Servlet or JSP.

But note that the later option sets the timeout value for the current session, this is not a global setting.

/exclude in xcopy just for a file type

The /EXCLUDE: argument expects a file containing a list of excluded files.

So create a file called excludedfileslist.txt containing:

.cs\

Then a command like this:

xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan

Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe to the machines.

Update

An anonymous comment edit which simply stated "This Solution exclude also css file!"

This is true creating a excludedfileslist.txt file contain just:

.cs

(note no backslash on the end)

Will also exclude all of the following:

  • file1.cs
  • file2.css
  • dir1.cs\file3.txt
  • dir2\anyfile.cs.something.txt

Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:

Using /exclude

  • List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp or dir.obj.output\example2.txt.

There is a way around .css files being excluded also, change the excludedfileslist.txt file to contain just:

.cs\

(note the backslash on the end).

Here is a complete test sequence for your reference:

C:\test1>ver

Microsoft Windows [Version 6.1.7601]

C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt

C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied

C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied

C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied

This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".

Note that the last example does exclude .\src\dir2.cs\file5.txt which may or may not be unexpected for you.

Cron and virtualenv

The only correct way to run python cron jobs when using a virtualenv is to activate the environment and then execute the environment's python to run your code.

One way to do this is use virtualenv's activate_this in your python script, see: http://virtualenv.readthedocs.org/en/latest/userguide.html#using-virtualenv-without-bin-python

Another solution is echoing the complete command including activating the environment and piping it into /bin/bash. Consider this for your /etc/crontab:

***** root echo 'source /env/bin/activate; python /your/script' | /bin/bash

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Format in other syntax is possible in this way

[DateTime]::Today.AddDays(-1).ToString("yyyyMMdd")

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

$(window).width() not the same as media query

try this

getData(){
    if(window.innerWidth <= 768) {
      alert('mobile view')
      return;
    }

   //else function will work

    let body= {
      "key" : 'keyValue'
    }
    this.dataService.getData(body).subscribe(
      (data: any) => {
        this.myData = data
      }
    )
}

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

Getting number of elements in an iterator in Python

def count_iter(iter):
    sum = 0
    for _ in iter: sum += 1
    return sum

How to concatenate string variables in Bash

I prefer to use curly brackets ${} for expanding variable in string:

foo="Hello"
foo="${foo} World"
echo $foo
> Hello World

Curly brackets will fit to Continuous string usage:

foo="Hello"
foo="${foo}World"
echo $foo
> HelloWorld

Otherwise using foo = "$fooWorld" will not work.

Static class initializer in PHP

NOTE: This is exactly what OP said they did. (But didn't show code for.) I show the details here, so that you can compare it to the accepted answer. My point is that OP's original instinct was, IMHO, better than the answer he accepted.


Given how highly upvoted the accepted answer is, I'd like to point out the "naive" answer to one-time initialization of static methods, is hardly more code than that implementation of Singleton -- and has an essential advantage.

final class MyClass  {
    public static function someMethod1() {
        MyClass::init();
        // whatever
    }

    public static function someMethod2() {
        MyClass::init();
        // whatever
    }


    private static $didInit = false;

    private static function init() {
        if (!self::$didInit) {
            self::$didInit = true;
            // one-time init code.
        }
    }

    // private, so can't create an instance.
    private function __construct() {
        // Nothing to do - there are no instances.
    }
}

The advantage of this approach, is that you get to call with the straightforward static function syntax:

MyClass::someMethod1();

Contrast it to the calls required by the accepted answer:

MyClass::getInstance->someMethod1();

As a general principle, it is best to pay the coding price once, when you code a class, to keep callers simpler.


If you are NOT using PHP 7.4's opcode.cache, then use Victor Nicollet's answer. Simple. No extra coding required. No "advanced" coding to understand. (I recommend including FrancescoMM's comment, to make sure "init" will never execute twice.) See Szczepan's explanation of why Victor's technique won't work with opcode.cache.

If you ARE using opcode.cache, then AFAIK my answer is as clean as you can get. The cost is simply adding the line MyClass::init(); at start of every public method. NOTE: If you want public properties, code them as a get / set pair of methods, so that you have a place to add that init call.

(Private members do NOT need that init call, as they are not reachable from the outside - so some public method has already been called, by the time execution reaches the private member.)

How to fix HTTP 404 on Github Pages?

Yet another scenario:

  • using an Organization Page (not a Project page) that has a repository named <orgname>.github.io
  • source documents as markup in master branch (asciidoc)
  • Travis CI pulling source doc files from master and pushing generated html files to gh-pages branch

The gh-pages branch is updated with the generated html pages. The GitHub Environment tab provides the link to the organization page. Clicking it results in a 404.

According to https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/

User and Organization Pages that have this type of repository name are only published from the master branch

If I understand this correctly, GitHub Pages will not be published from the gh-pages branch if you are creating a User or Organization site rather than a Project site.

I renamed my repo to make it a Project site rather than Organization site and then the gh-pages branch was published as expected.

linux script to kill java process

pkill -f for whatever reason does not work for me. Whatever that does, it seems very finicky about actually grepping through what ps aux shows me clearly is there.

After an afternoon of swearing I went for putting the following in my start script:

(ps aux | grep -v -e 'grep ' | grep MainApp | tr -s " " | cut -d " " -f 2 | xargs kill -9 ) || true

How do I crop an image in Java?

The solution I found most useful for cropping a buffered image uses the getSubImage(x,y,w,h);

My cropping routine ended up looking like this:

  private BufferedImage cropImage(BufferedImage src, Rectangle rect) {
      BufferedImage dest = src.getSubimage(0, 0, rect.width, rect.height);
      return dest; 
   }

How do you change the datatype of a column in SQL Server?

Don't forget nullability.

ALTER TABLE <schemaName>.<tableName>
ALTER COLUMN <columnName> nvarchar(200) [NULL|NOT NULL]

Finding even or odd ID values

In oracle,

select num from table where MOD (num, 2) = 0;

Remove Style on Element

You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to '' instead of null (see comments).

var element = document.getElementById('sample_id');

element.style.width = null;
element.style.height = null;

For more information, you can refer to HTMLElement.style documentation on MDN.

Reimport a module in python while interactive

In python 3, reload is no longer a built in function.

If you are using python 3.4+ you should use reload from the importlib library instead:

import importlib
importlib.reload(some_module)

If you are using python 3.2 or 3.3 you should:

import imp  
imp.reload(module)  

instead. See http://docs.python.org/3.0/library/imp.html#imp.reload

If you are using ipython, definitely consider using the autoreload extension:

%load_ext autoreload
%autoreload 2

How to find EOF through fscanf?

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Hide div if screen is smaller than a certain width

The problem with your code seems to be the elseif-statement which should be else if (Notice the space).

I rewrote and simplyfied the code to this:

$(document).ready(function () {

    if (screen.width < 1024) {
        $(".yourClass").hide();
    }
    else {

        $(".yourClass").show();
    }

});

JavaScript Promises - reject vs. throw

Yes, the biggest difference is that reject is a callback function that gets carried out after the promise is rejected, whereas throw cannot be used asynchronously. If you chose to use reject, your code will continue to run normally in asynchronous fashion whereas throw will prioritize completing the resolver function (this function will run immediately).

An example I've seen that helped clarify the issue for me was that you could set a Timeout function with reject, for example:

_x000D_
_x000D_
new Promise((resolve, reject) => {
  setTimeout(()=>{reject('err msg');console.log('finished')}, 1000);
  return resolve('ret val')
})
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));
_x000D_
_x000D_
_x000D_

The above could would not be possible to write with throw.

_x000D_
_x000D_
try{
  new Promise((resolve, reject) => {
    setTimeout(()=>{throw new Error('err msg')}, 1000);
    return resolve('ret val')
  })
  .then((o) => console.log("RESOLVED", o))
  .catch((o) => console.log("REJECTED", o));
}catch(o){
  console.log("IGNORED", o)
}
_x000D_
_x000D_
_x000D_

In the OP's small example the difference in indistinguishable but when dealing with more complicated asynchronous concept the difference between the two can be drastic.

Conversion of System.Array to List

There is also a constructor overload for List that will work... But I guess this would required a strong typed array.

//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);

... for Array class

var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
    intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);

Get list of JSON objects with Spring RestTemplate

If you would prefer a List of POJOs, one way to do it is like this:

class SomeObject {
    private int id;
    private String name;
}

public <T> List<T> getApi(final String path, final HttpMethod method) {     
    final RestTemplate restTemplate = new RestTemplate();
    final ResponseEntity<List<T>> response = restTemplate.exchange(
      path,
      method,
      null,
      new ParameterizedTypeReference<List<T>>(){});
    List<T> list = response.getBody();
    return list;
}

And use it like so:

 List<SomeObject> list = someService.getApi("http://localhost:8080/some/api",HttpMethod.GET);

Explanation for the above can be found here (https://www.baeldung.com/spring-rest-template-list) and is paraphrased below.

"There are a couple of things happening in the code above. First, we use ResponseEntity as our return type, using it to wrap the list of objects we really want. Second, we are calling RestTemplate.exchange() instead of getForObject().

This is the most generic way to use RestTemplate. It requires us to specify the HTTP method, optional request body, and a response type. In this case, we use an anonymous subclass of ParameterizedTypeReference for the response type.

This last part is what allows us to convert the JSON response into a list of objects that are the appropriate type. When we create an anonymous subclass of ParameterizedTypeReference, it uses reflection to capture information about the class type we want to convert our response to.

It holds on to this information using Java’s Type object, and we no longer have to worry about type erasure."

Convert DateTime to String PHP

echo date_format($date,"Y/m/d H:i:s");

Redirect non-www to www in .htaccess

If possible, add this to the main Apache configuration file. It is a lighter-weight solution, less processing required.

<VirtualHost 64.65.66.67>
        ServerName example.com
        Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost 64.65.66.67>
   ServerAdmin [email protected]
   ServerName www.example.com
   DocumentRoot /var/www/example
   .
   .
   . etc

So, the separate VirtualHost for "example.com" captures those requests and then permanently redirects them to your main VirtualHost. So there's no REGEX parsing with every request, and your client browsers will cache the redirect so they'll never (or rarely) request the "wrong" url again, saving you on server load.

Note, the trailing slash in Redirect permanent / http://www.example.com/. Without it, a redirect from example.com/asdf would redirect to http://www.example.comasdf instead of http://www.example.com/asdf.

Scrolling to element using webdriver?

You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions are reflected in ActionChains class:

from selenium.webdriver.common.action_chains import ActionChains

element = driver.find_element_by_id("my-id")

actions = ActionChains(driver)
actions.move_to_element(element).perform()

Or, you can also "scroll into view" via scrollIntoView():

driver.execute_script("arguments[0].scrollIntoView();", element)

If you are interested in the differences:

New line in JavaScript alert box

As of ECMAScript 2015 you can use back-ticks (` `) to enclose Template Literals for multi-line strings like this:

_x000D_
_x000D_
alert(`Line1_x000D_
Line2`);
_x000D_
_x000D_
_x000D_

Outputs:

Line1
Line2

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Disable Pinch Zoom on Mobile Web

Unfortunately, the offered solution doesn't work in Safari 10+, since Apple has decided to ignore user-scalable=no. This thread has more details and some JS hacks: disable viewport zooming iOS 10+ safari?

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

Wait for shell command to complete

Save the bat file on "C:\WINDOWS\system32" and use below code it is working

   Dim wsh As Object
   Set wsh = VBA.CreateObject("WScript.Shell")
   Dim waitOnReturn As Boolean: waitOnReturn = True
   Dim windowStyle As Integer: windowStyle = 1
   Dim errorCode As Integer

   errorCode = wsh.Run("runbat.bat", windowStyle, waitOnReturn)

If errorCode = 0 Then
    'Insert your code here
Else
    MsgBox "Program exited with error code " & errorCode & "."
End If   

Sass calculate percent minus px

$var:25%;
$foo:5px;
.selector {
    height:unquote("calc( #{$var} - #{$foo} )");
}

Checking if a key exists in a JS object

the simplest way is

_x000D_
_x000D_
const obj = {_x000D_
  a: 'value of a',_x000D_
  b: 'value of b',_x000D_
  c: 'value of c'_x000D_
};_x000D_
_x000D_
if(obj.a){_x000D_
  console.log(obj.a);_x000D_
}else{_x000D_
  console.log('obj.a does not exist');_x000D_
}
_x000D_
_x000D_
_x000D_

How to import local packages in go?

Local package is a annoying problem in go.

For some projects in our company we decide not use sub packages at all.

  • $ glide install
  • $ go get
  • $ go install

All work.

For some projects we use sub packages, and import local packages with full path:

import "xxxx.gitlab.xx/xxgroup/xxproject/xxsubpackage

But if we fork this project, then the subpackages still refer the original one.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

This is not a problem. If you wrap your .findElement call in a try-catch block and catch the StaleElementReferenceException , then you can loop and retry as many times as you need until it succeeds.

Here are some examples I wrote.

Another example from Selenide project:

public static final Condition hidden = new Condition("hidden", true) {
    @Override
    public boolean apply(WebElement element) {
      try {
        return !element.isDisplayed();
      } catch (StaleElementReferenceException elementHasDisappeared) {
        return true;
      }
    }
  };

Docker error response from daemon: "Conflict ... already in use by container"

It looks like a container with the name qgis-desktop-2-4 already exists in the system. You can check the output of the below command to confirm if it indeed exists:

$ docker ps -a

The last column in the above command's output is for names.

If the container exists, remove it using:

$ docker rm qgis-desktop-2-4

Or forcefully using,

$ docker rm -f qgis-desktop-2-4

And then try creating a new container.

Can we make unsigned byte in Java

I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter

This is not substantially different from a function accepting an integer to which you want to pass a value larger than 2^32-1.

That sounds like it depends on how the function is defined and documented; I can see three possibilities:

  1. It may explicitly document that the function treats the byte as an unsigned value, in which case the function probably should do what you expect but would seem to be implemented wrong. For the integer case, the function would probably declare the parameter as an unsigned integer, but that is not possible for the byte case.

  2. It may document that the value for this argument must be greater than (or perhaps equal to) zero, in which case you are misusing the function (passing an out-of-range parameter), expecting it to do more than it was designed to do. With some level of debugging support you might expect the function to throw an exception or fail an assertion.

  3. The documentation may say nothing, in which case a negative parameter is, well, a negative parameter and whether that has any meaning depends on what the function does. If this is meaningless then perhaps the function should really be defined/documented as (2). If this is meaningful in an nonobvious manner (e.g. non-negative values are used to index into an array, and negative values are used to index back from the end of the array so -1 means the last element) the documentation should say what it means and I would expect that it isn't what you want it to do anyway.

Foreign key referring to primary keys across multiple tables?

You can probably add two foreign key constraints (honestly: I've never tried it), but it'd then insist the parent row exist in both tables.

Instead you probably want to create a supertype for your two employee subtypes, and then point the foreign key there instead. (Assuming you have a good reason to split the two types of employees, of course).

                 employee       
employees_ce     ————————       employees_sn
————————————     type           ————————————
empid —————————> empid <——————— empid
name               /|\          name
                    |  
                    |  
      deductions    |  
      ——————————    |  
      empid ————————+  
      name

type in the employee table would be ce or sn.

In bash, how to store a return value in a variable?

It is easy you need to echo the value you need to return and then capture it like below

demofunc(){
    local variable="hellow"
    echo $variable    
}

val=$(demofunc)
echo $val

How to set the JDK Netbeans runs on?

For those not using Windows the file to change is netbeans-8.0/etc/netbeans.conf

and the line(s) to change is:

netbeans_jdkhome="/usr/lib/jvm/java-8-oracle"

commenting out the old value and inserting the new value

Linq select object from list depending on objects attribute

First, Single throws an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if the Correct property is true. Right now, you are checking if a is equal to a.Correct (which will not even compile).

You should use First (which will throw if there are no such elements), or FirstOrDefault (which will return null for a reference type if there isn't such element):

// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct); 

// this will return the first correct answer, 
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct); 

// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();

How to override trait function and call it from the overridden function?

If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}

class MyChildClass extends MyClass{
}

class MyTraitChildClass extends MyClass{
    use A;
}

print (new MyChildClass())->calc(2); // will print 4

print (new MyTraitChildClass())->calc(2); // will print 3

Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.

If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.

trait A {
    function calc($v) {
        return parent::calc($v*3);
    }
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)

You can also provide for ways to override, but still access the trait method as follows:

trait A {
    function trait_calc($v) {
        return $v*3;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}


class MyTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }
}


class MySecondTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }

    public function calc($v) {
      return $this->trait_calc($v)+.5;
    }
}


print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5

You can see it work at http://sandbox.onlinephpfunctions.com/code/e53f6e8f9834aea5e038aec4766ac7e1c19cc2b5

Getting error "No such module" using Xcode, but the framework is there

Surprised this even worked. My solution was to go to ...

Build Settings -> Framework Search Paths -> highlight debug -> press delete -> it should automatically fill out a path. -> Do the same for release

Result: enter image description here

Android - Dynamically Add Views into View

Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

You may have to adjust the index where you want to insert the view.

Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

Why is the time complexity of both DFS and BFS O( V + E )

An intuitive explanation to this is by simply analysing a single loop:

  1. visit a vertex -> O(1)
  2. a for loop on all the incident edges -> O(e) where e is a number of edges incident on a given vertex v.

So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives

For every V
=> 

    O(1)
    +

    O(e)

=> O(V) + O(E)

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

According to the HTML standard, the content model of the HTML element is:

A head element followed by a body element.

You can either define the BODY element in the source code:

<html>
    <body>
        ... web-page ...
    </body>
</html>

or you can omit the BODY element:

<html>
    ... web-page ...
</html>

However, it is invalid to place the BODY element inside the web-page content (in-between other elements or text content), like so:

<html>
    ... content ...
    <body>
        ... content ...
    </body>
    ... content ...
</html>

Why can I not create a wheel in python?

I tried everything said here without any luck, but found a workaround. After running this command (and failing) : bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

Go to the temporary directory the tool made (given in the output of the last command), then execute python setup.py bdist_wheel. The .whl file is in the dist folder.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I simply set Copy Local = true on the missing assembly and that worked. This of course happens by right clicking on the missing reference (which is stated in the error message) and selecting properties; as below:

enter image description here

This should then solve one problem as there might be more than one assembly causing the issue - what I did is I selected all assemblies and right click on them; selected properties; and set them all to Copy Local = true; and then republish.

break out of if and foreach

foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;
        break;
    }
}

Simply use break. That will do it.

What does "javax.naming.NoInitialContextException" mean?

It basically means that the application wants to perform some "naming operations" (e.g. JNDI or LDAP lookups), and it didn't have sufficient information available to be able to create a connection to the directory server. As the docs for the exception state,

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

And if you dutifully have a look at the javadocs for InitialContext, they describe quite well how the initial context is constructed, and what your options are for supplying the address/credentials/etc.

If you have a go at creating the context and get stuck somewhere else, please post back explaining what you've done so far and where you're running aground.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

pip install from git repo branch

Prepend the url prefix git+ (See VCS Support):

pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6

And specify the branch name without the leading /.

How can I temporarily disable a foreign key constraint in MySQL?

I normally only disable foreign key constraints when I want to truncate a table, and since I keep coming back to this answer this is for future me:

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table;
SET FOREIGN_KEY_CHECKS=1;

How do you count the lines of code in a Visual Studio solution?

You can use free tool SourceMonitor

Gives a lot of measures: Lines of Code, Statement Count, Complexity, Block Depth

Has graphical outputs via charts

How to copy to clipboard using Access/VBA?

VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.

If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.

However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.

For example, to place some text on the clipboard, you could use the following code:

Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard

Or, to copy text from the clipboard into a string variable:

Dim clipboard As MSForms.DataObject
Dim strContents As String

Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

Center text in div?

I believe you want the text to be vertically centered inside your div, not (only) horizontally. The only reliable way I know of doing this is using:

display: table-cell;
vertical-align: middle;

on your div, and it works with any number of lines. You can see a test here: http://jsfiddle.net/qMtZV/1/

Be sure to check browser support of this property, as it is not supported — for example — in IE7 or earlier.

UPDATE 02/10/2016

Five years later this technique is still valid, but I believe there are better and more solid solutions to this problem. Since Flexbox support is good nowadays, you might want to do something along these lines: http://codepen.io/michelegera/pen/gPZpqE.

Iterate a certain number of times without storing the iteration number anywhere

Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _, a convention for "discarding" the value assigned. Though the _ reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:

for _ in range(2):
    print('Hello')

How to copy data from another workbook (excel)?

I was in need of copying the data from one workbook to another using VBA. The requirement was as mentioned below 1. On pressing an Active X button open the dialogue to select the file from which the data needs to be copied. 2. On clicking OK the value should get copied from a cell / range to currently working workbook.

I did not want to use the open function because it opens the workbook which will be annoying

Below is the code that I wrote in the VBA. Any improvement or new alternative is welcome.

Code: Here I am copying the A1:C4 content from a workbook to the A1:C4 of current workbook

    Private Sub CommandButton1_Click()
        Dim BackUp As String
        Dim cellCollection As New Collection
        Dim strSourceSheetName As String
        Dim strDestinationSheetName As String
        strSourceSheetName = "Sheet1" 'Mention the Source Sheet Name of Source Workbook
        strDestinationSheetName = "Sheet2" 'Mention the Destination Sheet Name of Destination Workbook


        Set cellCollection = GetCellsFromRange("A1:C4") 'Mention the Range you want to copy data from Source Workbook

        With Application.FileDialog(msoFileDialogOpen)
            .AllowMultiSelect = False
            .Show
            '.Filters.Add "Macro Enabled Xl", "*.xlsm;", 1

            For intWorkBookCount = 1 To .SelectedItems.Count
                Dim strWorkBookName As String
                strWorkBookName = .SelectedItems(intWorkBookCount)
                For cellCount = 1 To cellCollection.Count
                    On Error GoTo ErrorHandler
                    BackUp = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount))
                    Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = GetData(strWorkBookName, strSourceSheetName, cellCollection.Item(cellCount))
                    Dim strTempValue As String
                    strTempValue = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)).Value
                    If (strTempValue = "0") Then
                        strTempValue = BackUp
                    End If
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = strTempValue 
ErrorHandler:
                    If (Err.Number <> 0) Then
                            Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = BackUp
                        Exit For
                    End If
                Next cellCount
            Next intWorkBookCount
        End With

    End Sub

    Function GetCellsFromRange(RangeInScope As String) As Collection
        Dim startCell As String
        Dim endCell As String
        Dim intStartColumn As Integer
        Dim intEndColumn As Integer
        Dim intStartRow As Integer
        Dim intEndRow As Integer
        Dim coll As New Collection

        startCell = Left(RangeInScope, InStr(RangeInScope, ":") - 1)
        endCell = Right(RangeInScope, Len(RangeInScope) - InStr(RangeInScope, ":"))
        intStartColumn = Range(startCell).Column
        intEndColumn = Range(endCell).Column
        intStartRow = Range(startCell).Row
        intEndRow = Range(endCell).Row

        For lngColumnCount = intStartColumn To intEndColumn
            For lngRowCount = intStartRow To intEndRow
                coll.Add (Cells(lngRowCount, lngColumnCount).Address(RowAbsolute:=False, ColumnAbsolute:=False))
            Next lngRowCount
        Next lngColumnCount

        Set GetCellsFromRange = coll
    End Function

    Function GetData(FileFullPath As String, SheetName As String, CellInScope As String) As String
        Dim Path As String
        Dim FileName As String
        Dim strFinalValue As String
        Dim doesSheetExist As Boolean

        Path = FileFullPath
        Path = StrReverse(Path)
        FileName = StrReverse(Left(Path, InStr(Path, "\") - 1))
        Path = StrReverse(Right(Path, Len(Path) - InStr(Path, "\") + 1))

        strFinalValue = "='" & Path & "[" & FileName & "]" & SheetName & "'!" & CellInScope
        GetData = strFinalValue
    End Function

iPhone and WireShark

You can proceed as follow:

  1. Install Charles Web Proxy.
  2. Disable SSL proxying (uncheck the flag in Proxy->Proxy Settings...->SSL
  3. Connect your iDevice to the Charles proxy, as explained here
  4. Sniff the packets via Wireshark or Charles

HTTP GET in VBS

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.

What is a loop invariant?

Beside all of the good answers, I guess a great example from How to Think About Algorithms, by Jeff Edmonds can illustrate the concept very well:

EXAMPLE 1.2.1 "The Find-Max Two-Finger Algorithm"

1) Specifications: An input instance consists of a list L(1..n) of elements. The output consists of an index i such that L(i) has maximum value. If there are multiple entries with this same value, then any one of them is returned.

2) Basic Steps: You decide on the two-finger method. Your right finger runs down the list.

3) Measure of Progress: The measure of progress is how far along the list your right finger is.

4) The Loop Invariant: The loop invariant states that your left finger points to one of the largest entries encountered so far by your right finger.

5) Main Steps: Each iteration, you move your right finger down one entry in the list. If your right finger is now pointing at an entry that is larger then the left finger’s entry, then move your left finger to be with your right finger.

6) Make Progress: You make progress because your right finger moves one entry.

7) Maintain Loop Invariant: You know that the loop invariant has been maintained as follows. For each step, the new left finger element is Max(old left finger element, new element). By the loop invariant, this is Max(Max(shorter list), new element). Mathe- matically, this is Max(longer list).

8) Establishing the Loop Invariant: You initially establish the loop invariant by point- ing both fingers to the first element.

9) Exit Condition: You are done when your right finger has finished traversing the list.

10) Ending: In the end, we know the problem is solved as follows. By the exit condi- tion, your right finger has encountered all of the entries. By the loop invariant, your left finger points at the maximum of these. Return this entry.

11) Termination and Running Time: The time required is some constant times the length of the list.

12) Special Cases: Check what happens when there are multiple entries with the same value or when n = 0 or n = 1.

13) Coding and Implementation Details: ...

14) Formal Proof: The correctness of the algorithm follows from the above steps.

HTTP Error 500.19 and error code : 0x80070021

I got Error Code 0x80070021 when migration IIS7 to IIS 10 in win 2016 box . . Below steps helped me to fix it . source

manually change value from "Deny" to "Allow" for below settings in

%windir%\system32\inetsrv\config\ applicationHost.config

under section:system.webServer

<section name="handlers" overrideModeDefault="Deny" />

String format currency

decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();

Output console screen:

Running code in main thread from another thread

So most handy is to do sort of:

import android.os.AsyncTask
import android.os.Handler
import android.os.Looper

object Dispatch {
    fun asyncOnBackground(call: ()->Unit) {
        AsyncTask.execute {
            call()
        }
    }

    fun asyncOnMain(call: ()->Unit) {
        Handler(Looper.getMainLooper()).post {
            call()
        }
    }
}

And after:

Dispatch.asyncOnBackground {
    val value = ...// super processing
    Dispatch.asyncOnMain { completion(value)}
}

Is it possible to open developer tools console in Chrome on Android phone?

Please do yourself a favor and just hit the easy button:

download Web Inspector (Open Source) from the Play store.

A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:

console.log('one', 'two', 'three');

you will only see

one

logged to the console. You'll need to manually wrap the params in an Array and join, like so:

console.log([ 'one', 'two', 'three' ].join(' '));

to see the expected output.

But the app is open source! A patch may be imminent! The patcher could even be you!

C++ - struct vs. class

POD classes are Plain-Old data classes that have only data members and nothing else. There are a few questions on stackoverflow about the same. Find one here.

Also, you can have functions as members of structs in C++ but not in C. You need to have pointers to functions as members in structs in C.

Why is width: 100% not working on div {display: table-cell}?

Welcome to 2017 these days will using vW and vH do the trick

_x000D_
_x000D_
html, body {_x000D_
    margin: 0; padding: 0;_x000D_
    width: 100%; height: 100%;_x000D_
}_x000D_
_x000D_
ul {_x000D_
    background: #CCC;_x000D_
    height: 100%;_x000D_
    width: 100%;_x000D_
    list-style-position: outside;_x000D_
    margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
li {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
}_x000D_
_x000D_
img {_x000D_
    width: 100%;_x000D_
    height: 410px;_x000D_
}_x000D_
_x000D_
.outer-wrapper {_x000D_
    position: absolute;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    top: 0;_x000D_
    margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
.inner-wrapper {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    text-align: center;_x000D_
    width: 100vw; /* only change is here "%" to "vw" ! */_x000D_
    height: 100vh; /* only change is here "%" to "vh" ! */_x000D_
}
_x000D_
<ul>_x000D_
    <li>_x000D_
        <img src="#">_x000D_
        <div class="outer-wrapper">_x000D_
            <div class="inner-wrapper">_x000D_
                <h1>My Title</h1>_x000D_
                <h5>Subtitle</h5>_x000D_
            </div>_x000D_
        </div>_x000D_
    </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The name 'ConfigurationManager' does not exist in the current context

To Solve this problem go to Solution Explorer And right click reference and click add reference and chose .net and find system.configuration select an click ok

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

Checking if an object is a number in C#

Assuming your input is a string...

There are 2 ways:

use Double.TryParse()

double temp;
bool isNumber = Double.TryParse(input, out temp);

use Regex

 bool isNumber = Regex.IsMatch(input,@"-?\d+(\.\d+)?");

How to remove certain characters from a string in C++?

   string str("(555) 555-5555");

   char chars[] = "()-";

   for (unsigned int i = 0; i < strlen(chars); ++i)
   {
      // you need include <algorithm> to use general algorithms like std::remove()
      str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
   }

   // output: 555 5555555
   cout << str << endl;

To use as function:

void removeCharsFromString( string &str, char* charsToRemove ) {
   for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
      str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
   }
}
//example of usage:
removeCharsFromString( str, "()-" );

How to draw a circle with text in the middle?

Draw a circle with text in middle with HTML Tag and without CSS

HTML having SVG tag for this. You can follow this standard approach if you don't want to go for CSS.

 <svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="white" />
     Sorry, your browser does not support inline SVG.
   <text fill="#000000" font-size="18" font-family="Verdana"
     x="15" y="60">ASHISH</text>
 </svg>

enter image description here

Can anyone explain me StandardScaler?

We apply StandardScalar() on a row basis.

So, for each row in a column (I am assuming that you are working with a Pandas DataFrame):

x_new = (x_original - mean_of_distribution) / std_of_distribution

Few points -

  1. It is called Standard Scalar as we are dividing it by the standard deviation of the distribution (distr. of the feature). Similarly, you can guess for MinMaxScalar().

  2. The original distribution remains the same after applying StandardScalar(). It is a common misconception that the distribution gets changed to a Normal Distribution. We are just squashing the range into [0, 1].

How to set default vim colorscheme

You can just use the one-liner

echo colorscheme koehler >> ~/.vimrc

and replace koehler with any other available colorscheme. Imho, all of them are better than default.

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

Here is another solution you could have used. It is working in my app.

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        android.support.v7.app.ActionBar actionBar =getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);            
        setContentView(R.layout.activity_main)

Then you can get rid of that import for the one line ActionBar use.

Android Studio: Module won't show up in "Edit Configuration"

It was fixed for me after removing and re-adding the Android and Android-Gradle Facets in the Module Settings dialog.

HTML "overlay" which allows clicks to fall through to elements behind it

For the record an alternative approach might be to make the clickable layer the overlay: you make it semi-transparent and then place the "overlay" image behind it (somewhat counterintuitively, the "overlay" image could then be opaque). Depending on what you're trying to do, you might well be able to get the exact same visual effect (of an image and a clickable layer semi-transparently superimposed on top of each other), while avoiding clickability problems (because the "overlay" is in fact in the background).

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

run command prompt as administrator and use '--user' flag eg. pip install --user --upgrade pandas

Change color of Button when Mouse is over

<Button Background="#FF4148" BorderThickness="0" BorderBrush="Transparent">
     <Border HorizontalAlignment="Right" BorderBrush="#FF6A6A" BorderThickness="0>
     <Border.Style>
         <Style TargetType="Border">
             <Style.Triggers>
                 <Trigger Property="IsMouseOver" Value="True">
                     <Setter Property="Background" Value="#FF6A6A" />
                 </Trigger>
             </Style.Triggers>
         </Style>
      </Border.Style>
      <StackPanel Orientation="Horizontal">
           <Image  RenderOptions.BitmapScalingMode="HighQuality"   Source="//ImageName.png"   />
      </StackPanel>
      </Border>
  </Button>

Difference Between One-to-Many, Many-to-One and Many-to-Many?

this would probably call for a many-to-many relation ship as follows



public class Person{

    private Long personId;
    @manytomany

    private Set skills;
    //Getters and setters
}

public class Skill{
    private Long skillId;
    private String skillName;
    @manyToMany(MappedBy="skills,targetClass="Person")
    private Set persons; // (people would not be a good convenion)
    //Getters and setters
}

you may need to define a joinTable + JoinColumn but it will possible work also without...

Docker is installed but Docker Compose is not ? why?

Refered to the answers given above (I do not have enough reputation to refer separately to individual solutions, hence I do this collectively in this place), I want to supplement them with some important suggestions:

  1. docker-compose you can install from the repository (if you have this package in the repository, if not you can adding to system a repository with this package) or download binary with use curl - totourial on the official website of the project - src: https://docs.docker.com/compose/install /

  2. docker-compose from the repository is in version 1.8.0 (at least at me). This docker-compose version does not support configuration files in version 3. It only has version = <2 support. Inthe official site of the project is a recommendation to use container configuration in version 3 - src: https://docs.docker.com/compose/compose-file / compose-versioning /. From my own experience with work in the docker I recommend using container configurations in version 3 - there are more configuration options to use than in versions <3. If you want to use the configurations configurations in version 3 you have to do update / install docker-compose to the version of at least 1.17 - preferably the latest stable. The official site of the project is toturial how to do this process - src: https://docs.docker.com/compose/install/

  3. when you try to manually remove the old docker-compose binaries, you can have information about the missing file in the default path /usr/local/bin/docker-compose. At my case, docker-compose was in the default path /usr/bin/docker-compose. In this case, I suggest you use the find tool in your system to find binary file docker-compose - example syntax: sudo find / -name 'docker-compose'. It helped me. Thanks to this, I removed the old docker-compose version and added the stable to the system - I use the curl tool to download binary file docker-compose, putting it in the right path and giving it the right permissions - all this process has been described in the posts above.

Regards, Adam

MVC which submit button has been pressed

This post is not going to answer to Coppermill, because he have been answered long time ago. My post will be helpful for who will seeking for solution like this. First of all , I have to say " WDuffy's solution is totally correct" and it works fine, but my solution (not actually mine) will be used in other elements and it makes the presentation layer more independent from controller (because your controller depend on "value" which is used for showing label of the button, this feature is important for other languages.).

Here is my solution, give them different names:

<input type="submit" name="buttonSave" value="Save"/>
<input type="submit" name="buttonProcess" value="Process"/>
<input type="submit" name="buttonCancel" value="Cancel"/>

And you must specify the names of buttons as arguments in the action like below:

public ActionResult Register(string buttonSave, string buttonProcess, string buttonCancel)
{
    if (buttonSave!= null)
    {
        //save is pressed
    }
    if (buttonProcess!= null)
    {
        //Process is pressed
    }
    if (buttonCancel!= null)
    {
        //Cancel is pressed
    }
}

when user submits the page using one of the buttons, only one of the arguments will have value. I guess this will be helpful for others.

Update

This answer is quite old and I actually reconsider my opinion . maybe above solution is good for situation which passing parameter to model's properties. don't bother yourselves and take best solution for your project.

PG::ConnectionBad - could not connect to server: Connection refused

Locate your postgres file it could be in /usr/local/var/postgres/ or in /usr/var/postgres/ and then delete the postmaster.pid file present in that folder.

How can I get the error message for the mail() function?

In my case, I couldn't get the error message in my PHP script no matter what I do (error_get_last(), or ini_set('display_errors',1);) don't show the error message

according to this post

The return value from $mail refers only to whether or not your server's mailing system accepted the message for delivery, and does not and can not in any way know whether or not you are providing valid arguments. For example, the return value would be false if sendmail failed to load (e.g. if it wasn't installed properly), but would return true if sendmail loaded properly but the recipient address doesn't exist.

I confirm this because after some failed attempts to use mail() in my PHP scripts, it turns that sendmail was not installed on my machine, however the php.ini variable sendmail_path was /usr/sbin/sendmail -t -i

1- I installed sendmail from my package manager shell> dnf install sendmail

2- I started it shell> service sendmail start

3- Now if any PHP mail() function fails I find the errors of the sendmail program logged under /var/mail/ directory. 1 file per user

For example this snippet is taken from my /var/mail/root file

The original message was received at Sun, 29 Jul 2018 22:37:51 +0200
from localhost [127.0.0.1]
   ----- The following addresses had permanent fatal errors -----
<[email protected]>
    (reason: 550 Host unknown)

My system is linux Fedora 28 with apache2.4 and PHP 7.2

Stopping an Android app from console

The clean way of stopping the app is:

adb shell am force-stop com.my.app.package

This way you don't have to figure out the process ID.

PHP max_input_vars

Just had the same problem adding menu items to Wordpress. I am using Wordpress 4.9.9 on Ubuntu 18.04, PHP 7.0. I simply uncommented the following line and increased it to 1500 in /etc/php/7.0/apache2/php.ini

; How many GET/POST/COOKIE input variables may be accepted<br>
max_input_vars = 1500

Then used the following to effect the change:

sudo apache2ctl configtest  #(if it does not return ok Apache will not start)
sudo service apache2 reload

Hope that helps.

How to replace existing value of ArrayList element in Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

How is Java platform-independent when it needs a JVM to run?

Just a side note to the discussion about JVM and JIT Compilation. This is the same principle as with C# and the CLR and to some extent in Python, and when somebody says that the code runs "directly on hardware" that is actually true in that instructions that is already compiled will be able to take advantage of optimization on the machine/cpu it's being run on. So even if the initial compilation of a module is rather slow, the next time this module is run, the code being executed runs at native speed and thus runs directly on hardware so to say.

How to create javascript delay function

You can create a delay using the following example

setInterval(function(){alert("Hello")},3000);

Replace 3000 with # of milliseconds

You can place the content of what you want executed inside the function.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Facebook Callback appends '#_=_' to Return URL

TL;DR

if (window.location.hash === "#_=_"){
    history.replaceState 
        ? history.replaceState(null, null, window.location.href.split("#")[0])
        : window.location.hash = "";
}

Full version with step by step instructions

// Test for the ugliness.
if (window.location.hash === "#_=_"){

    // Check if the browser supports history.replaceState.
    if (history.replaceState) {

        // Keep the exact URL up to the hash.
        var cleanHref = window.location.href.split("#")[0];

        // Replace the URL in the address bar without messing with the back button.
        history.replaceState(null, null, cleanHref);

    } else {

        // Well, you're on an old browser, we can get rid of the _=_ but not the #.
        window.location.hash = "";

    }

}

Step by step:

  1. We'll only get into the code block if the fragment is #_=_.
  2. Check if the browser supports the HTML5 window.replaceState method.
    1. Clean the URL by splitting on # and taking only the first part.
    2. Tell history to replace the current page state with the clean URL. This modifies the current history entry instead of creating a new one. What this means is the back and forward buttons will work just the way you want. ;-)
  3. If the browser does not support the awesome HTML 5 history methods then just clean up the URL as best you can by setting the hash to empty string. This is a poor fallback because it still leaves a trailing hash (example.com/#) and also it adds a history entry, so the back button will take you back to #_-_.

Learn more about history.replaceState.

Learn more about window.location.

error: RPC failed; curl transfer closed with outstanding read data remaining

These steps worked for me:using git:// instead of https://

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

Java - Writing strings to a CSV file

    String filepath="/tmp/employee.csv";
    FileWriter sw = new FileWriter(new File(filepath));
    CSVWriter writer = new CSVWriter(sw);
    writer.writeAll(allRows);

    String[] header= new String[]{"ErrorMessage"};
    writer.writeNext(header);

    List<String[]> errorData = new ArrayList<String[]>();
    for(int i=0;i<1;i++){
        String[] data = new String[]{"ErrorMessage"+i};
        errorData.add(data);
    }
    writer.writeAll(errorData);

    writer.close();

Google Colab: how to read data from my google drive?

I wrote a class that downloads all of the data to the '.' location in the colab server

The whole thing can be pulled from here https://github.com/brianmanderson/Copy-Shared-Google-to-Colab

!pip install PyDrive


from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
import os

class download_data_from_folder(object):
    def __init__(self,path):
        path_id = path[path.find('id=')+3:]
        self.file_list = self.get_files_in_location(path_id)
        self.unwrap_data(self.file_list)
    def get_files_in_location(self,folder_id):
        file_list = drive.ListFile({'q': "'{}' in parents and trashed=false".format(folder_id)}).GetList()
        return file_list
    def unwrap_data(self,file_list,directory='.'):
        for i, file in enumerate(file_list):
            print(str((i + 1) / len(file_list) * 100) + '% done copying')
            if file['mimeType'].find('folder') != -1:
                if not os.path.exists(os.path.join(directory, file['title'])):
                    os.makedirs(os.path.join(directory, file['title']))
                print('Copying folder ' + os.path.join(directory, file['title']))
                self.unwrap_data(self.get_files_in_location(file['id']), os.path.join(directory, file['title']))
            else:
                if not os.path.exists(os.path.join(directory, file['title'])):
                    downloaded = drive.CreateFile({'id': file['id']})
                    downloaded.GetContentFile(os.path.join(directory, file['title']))
        return None
data_path = 'shared_path_location'
download_data_from_folder(data_path)

Search and replace a line in a file in Python

Here's another example that was tested, and will match search & replace patterns:

import fileinput
import sys

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

Example use:

replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.")

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

How do I change the root directory of an Apache server?

This is for Ubunutu 14.04:

In file /etc/apache2/apache2.conf it should be as below without the directory name:

<Directory /home/username>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

And in file /etc/apache2/sites-available/000-default.conf you should include the custom directory name, i.e., www:

DocumentRoot /home/username/www

If it is not as above, it will give you an error when loading the server:

Forbidden You don't have permission to access / on this server

When to use dynamic vs. static libraries

Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run.

Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the original one that shipped with your code if the update is considered binary compatible with the original version.

Additionally dynamic libraries aren't necessarily loaded -- they're usually loaded when first called -- and can be shared among components that use the same library (multiple data loads, one code load).

Dynamic libraries were considered to be the better approach most of the time, but originally they had a major flaw (google DLL hell), which has all but been eliminated by more recent Windows OSes (Windows XP in particular).

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

This error comes when there's incompatibility between node version and angular/cli version. therefore use below command to update the cli version to latest

npm install -g @angular/cli@latest

How to tell if a string is not defined in a Bash shell script

call set without any arguments.. it outputs all the vars defined..
the last ones on the list would be the ones defined in your script..
so you could pipe its output to something that could figure out what things are defined and whats not

form serialize javascript (no framework)

I could be crazy but I'm finding these answers seriously bloated. Here's my solution

function serialiseForm(form) {
  var input = form.getElementsByTagName("input");
  var formData = {};
  for (var i = 0; i < input.length; i++) {
    formData[input[i].name] = input[i].value;
  }
  return formData = JSON.stringify(formData);
}

C++ Calling a function from another class

Here's my solution to the issue. Tried to keep it straight and simple.

#include <iostream>
using namespace std;

class Game{
public:
  void init(){
    cout << "Hi" << endl;
  }
}g;

class b : Game{  //class b uses/imports class Game
public:
  void h(){
    init(); //Use function from class Game
  }
}A;

int main()
{
  A.h();
  return 0;
}

VB.NET - Click Submit Button on Webbrowser page

This seems to work easily.


Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
        Dim MyDoc As New mshtml.HTMLDocument
        Dim DocElements As mshtml.IHTMLElementCollection = Nothing
        Dim LoginForm As mshtml.HTMLFormElement = Nothing

        ASPComplete = 0
        WB.Navigate(VitecLoginURI)
        BrowserLoop()

        MyDoc = WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each i As mshtml.IHTMLElement In DocElements

            Select Case i.name
                Case "seLogin$UserName"
                    i.value = UserID
                Case "seLogin$Password"
                    i.value = Pass
                Case Else
                    Exit Select
            End Select

            frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
        Next i

        'Old Method for Clicking submit
        'WB.Document.Forms("form1").InvokeMember("submit")


        'Better Method to click submit
        LoginForm = MyDoc.forms.item("form1")
        LoginForm.item("seLogin$LoginButton").click()
        ASPComplete = 0
        BrowserLoop()



        MyDoc= WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each j As mshtml.IHTMLElement In DocElements
            frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf

        Next j

        frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
        Return 1
End Function

Where can I find the Java SDK in Linux after installing it?

on OpenSUSE 13.1/13.2 its: /usr/lib64/jvm/java-1.6.0-openjdk-(version-number)
version-number can be 1.7.x 1.8.x etc. check software manager witch version you have installed...

André

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Start with the triangle...

    *
   **
  ***
 ****

representing 1+2+3+4 so far. Cut the triangle in half along one dimension...

     *
    **
  * **
 ** **

Rotate the smaller part 180 degrees, and stick it on top of the bigger part...

    **
    * 

     *
    **
    **
    **

Close the gap to get a rectangle.

At first sight this only works if the base of the rectangle has an even length - but if it has an odd length, you just cut the middle column in half - it still works with a half-unit-wide twice-as-tall (still integer area) strip on one side of your rectangle.

Whatever the base of the triangle, the width of your rectangle is (base / 2) and the height is (base + 1), giving ((base + 1) * base) / 2.

However, my base is your n-1, since the bubble sort compares a pair of items at a time, and therefore iterates over only (n-1) positions for the first loop.

What USB driver should we use for the Nexus 5?

I had the same problem too. In the Device Manager all drivers were OK, but Eclipse couldn't find the device. Even after updating the Google USB drivers with the SDK Manager.

The problem was that I didn't have the developer options enabled. For that I came here, How to Enable Developer Options on the Nexus 5 & KitKat.

Then I had to manualy update the Google USB drivers, see Download and Install Google Nexus 5 USB Drivers (ADB / Fastboot).

After that, my installation of Eclipse recognized my device.

How to enable multidexing with the new Android Multidex support library

Step 1: Change build.grade

defaultConfig {
    ...
    // Enabling multidex support.
    multiDexEnabled true
}

dependencies {
    ...
    compile 'com.android.support:multidex:1.0.0'
}

Step 2: Setting on the Application class

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        MultiDex.install(this);
    }
}

Step 3: Change grade.properties

org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

It will work!. Thanks.

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

How to loop and render elements in React.js without an array of objects to map?

You can still use map if you can afford to create a makeshift array:

{
    new Array(this.props.level).fill(0).map((_, index) => (
        <span className='indent' key={index}></span>
    ))
}

This works because new Array(n).fill(x) creates an array of size n filled with x, which can then aid map.

array-fill

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

no, you can't do that, but you can use event handlers to change the title:

<img src="foo.jpg" onmouseover="this.title='it is now ' + new Date()" /> 

What's the use of ob_start() in php?

I use this so I can break out of PHP with a lot of HTML but not render it. It saves me from storing it as a string which disables IDE color-coding.

<?php
ob_start();
?>
<div>
    <span>text</span>
    <a href="#">link</a>
</div>
<?php
$content = ob_get_clean();
?>

Instead of:

<?php
$content = '<div>
    <span>text</span>
    <a href="#">link</a>
</div>';
?>

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Create space at the beginning of a UITextField

I prefer to use IBDesignable class and IBInspectable properties to allow me to set the padding via Xcode storyboards and keep it reusable. I've also updated the code to work in Swift 4.

import Foundation
import UIKit

@IBDesignable
class PaddableTextField: UITextField {

    var padding = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)

    @IBInspectable var left: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    @IBInspectable var right: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    @IBInspectable var top: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    @IBInspectable var bottom: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    func adjustPadding() {
         padding = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)

    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
         return bounds.inset(by: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
    }
}

Listen for key press in .NET console app

According to my experience, in console apps the easiest way to read the last key pressed is as follows (Example with arrow keys):

ConsoleKey readKey = Console.ReadKey ().Key;
if (readKey == ConsoleKey.LeftArrow) {
    <Method1> ();  //Do something
} else if (readKey == ConsoleKey.RightArrow) {
    <Method2> ();  //Do something
}

I use to avoid loops, instead I write the code above within a method, and I call it at the end of both "Method1" and "Method2", so, after executing "Method1" or "Method2", Console.ReadKey().Key is ready to read the keys again.

How do I remove a file from the FileList

There might be a more elegant way to do this but here is my solution. With Jquery

fileEle.value = "";
var parEle = $(fileEle).parent();
var newEle = $(fileEle).clone()
$(fileEle).remove();
parEle.append(newEle);

Basically you cleat the value of the input. Clone it and put the clone in place of the old one.

What is a good alternative to using an image map generator?

This service is the best in online image map editing I found so far : http://www.image-maps.com/

... but it is in fact a bit weak and I personnaly don't use it anymore. I switched to GIMP and it is indeed pretty good.

The answer from mobius is not wrong but in some cases you must use imagemaps even if it seems a bit old and rusty. For instance, in a newsletter, where you can't use HTML/CSS to do what you want.

notifyDataSetChange not working from custom adapter

If adapter is set to AutoCompleteTextView then notifyDataSetChanged() doesn't work.

Need this to update adapter:

myAutoCompleteAdapter = new ArrayAdapter<String>(MainActivity.this, 
        android.R.layout.simple_dropdown_item_1line, myList);

myAutoComplete.setAdapter(myAutoCompleteAdapter);

Refer: http://android-er.blogspot.in/2012/10/autocompletetextview-with-dynamic.html

How to secure an ASP.NET Web API

Have you tried DevDefined.OAuth?

I have used it to secure my WebApi with 2-Legged OAuth. I have also successfully tested it with PHP clients.

It's quite easy to add support for OAuth using this library. Here's how you can implement the provider for ASP.NET MVC Web API:

1) Get the source code of DevDefined.OAuth: https://github.com/bittercoder/DevDefined.OAuth - the newest version allows for OAuthContextBuilder extensibility.

2) Build the library and reference it in your Web API project.

3) Create a custom context builder to support building a context from HttpRequestMessage:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;

using DevDefined.OAuth.Framework;

public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
    public WebApiOAuthContextBuilder()
        : base(UriAdjuster)
    {
    }

    public IOAuthContext FromHttpRequest(HttpRequestMessage request)
    {
        var context = new OAuthContext
            {
                RawUri = this.CleanUri(request.RequestUri), 
                Cookies = this.CollectCookies(request), 
                Headers = ExtractHeaders(request), 
                RequestMethod = request.Method.ToString(), 
                QueryParameters = request.GetQueryNameValuePairs()
                    .ToNameValueCollection(), 
            };

        if (request.Content != null)
        {
            var contentResult = request.Content.ReadAsByteArrayAsync();
            context.RawContent = contentResult.Result;

            try
            {
                // the following line can result in a NullReferenceException
                var contentType = 
                    request.Content.Headers.ContentType.MediaType;
                context.RawContentType = contentType;

                if (contentType.ToLower()
                    .Contains("application/x-www-form-urlencoded"))
                {
                    var stringContentResult = request.Content
                        .ReadAsStringAsync();
                    context.FormEncodedParameters = 
                        HttpUtility.ParseQueryString(stringContentResult.Result);
                }
            }
            catch (NullReferenceException)
            {
            }
        }

        this.ParseAuthorizationHeader(context.Headers, context);

        return context;
    }

    protected static NameValueCollection ExtractHeaders(
        HttpRequestMessage request)
    {
        var result = new NameValueCollection();

        foreach (var header in request.Headers)
        {
            var values = header.Value.ToArray();
            var value = string.Empty;

            if (values.Length > 0)
            {
                value = values[0];
            }

            result.Add(header.Key, value);
        }

        return result;
    }

    protected NameValueCollection CollectCookies(
        HttpRequestMessage request)
    {
        IEnumerable<string> values;

        if (!request.Headers.TryGetValues("Set-Cookie", out values))
        {
            return new NameValueCollection();
        }

        var header = values.FirstOrDefault();

        return this.CollectCookiesFromHeaderString(header);
    }

    /// <summary>
    /// Adjust the URI to match the RFC specification (no query string!!).
    /// </summary>
    /// <param name="uri">
    /// The original URI. 
    /// </param>
    /// <returns>
    /// The adjusted URI. 
    /// </returns>
    private static Uri UriAdjuster(Uri uri)
    {
        return
            new Uri(
                string.Format(
                    "{0}://{1}{2}{3}", 
                    uri.Scheme, 
                    uri.Host, 
                    uri.IsDefaultPort ?
                        string.Empty :
                        string.Format(":{0}", uri.Port), 
                    uri.AbsolutePath));
    }
}

4) Use this tutorial for creating an OAuth provider: http://code.google.com/p/devdefined-tools/wiki/OAuthProvider. In the last step (Accessing Protected Resource Example) you can use this code in your AuthorizationFilterAttribute attribute:

public override void OnAuthorization(HttpActionContext actionContext)
{
    // the only change I made is use the custom context builder from step 3:
    OAuthContext context = 
        new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);

    try
    {
        provider.AccessProtectedResourceRequest(context);

        // do nothing here
    }
    catch (OAuthException authEx)
    {
        // the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
        // implementation is overloaded to return a problem report string as per
        // the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
               RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
            };
    }
}

I have implemented my own provider so I haven't tested the above code (except of course the WebApiOAuthContextBuilder which I'm using in my provider) but it should work fine.

Radio Buttons "Checked" Attribute Not Working

Replace checked="checked" with checked={true}. Or you could even shorten it to just checked.

This is because the expected value type of the checked prop is a boolean. not a string.

SQL query to find record with ID not in another table

Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:

SELECT t1.ID, t1.Name 
FROM   Table1 t1
WHERE  NOT EXISTS (
    SELECT TOP 1 NULL
    FROM Table2 t2
    WHERE t1.ID = t2.ID
)

Is there any way to specify a suggested filename when using data: URI?

Using service workers, this is finally possible in the truest sense.

  1. Create a fake URL. For example /saveAs/myPrettyName.jpg
  2. Use URL in <a href, <img src, window.open( url ), absolutely anything that can be done with a "real" URL.
  3. Inside the worker, catch the fetch event, and respond with the correct data.

The browser will now suggest myPrettyName.jpg even if the user opens the file in a new tab, and tries to save it there. It will be exactly as if the file had come from the server.

// In the service worker
self.addEventListener( 'fetch', function(e)
{
    if( e.request.url.startsWith( '/blobUri/' ) )
    {
        // Logic to select correct dataUri, and return it as a Response
        e.respondWith( dataURLAsRequest );
    }
});

Excel VBA: AutoFill Multiple Cells with Formulas

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

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

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

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

End Sub

Screenshots:

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

enter image description here

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

enter image description here

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

Hope this helps!

How to return a string value from a Bash function

Like bstpierre above, I use and recommend the use of explicitly naming output variables:

function some_func() # OUTVAR ARG1
{
   local _outvar=$1
   local _result # Use some naming convention to avoid OUTVARs to clash
   ... some processing ....
   eval $_outvar=\$_result # Instead of just =$_result
}

Note the use of quoting the $. This will avoid interpreting content in $result as shell special characters. I have found that this is an order of magnitude faster than the result=$(some_func "arg1") idiom of capturing an echo. The speed difference seems even more notable using bash on MSYS where stdout capturing from function calls is almost catastrophic.

It's ok to send in a local variables since locals are dynamically scoped in bash:

function another_func() # ARG
{
   local result
   some_func result "$1"
   echo result is $result
}

Get the IP address of the machine

Don't hard code it: this is the sort of thing that can change. Many programs figure out what to bind to by reading in a config file, and doing whatever that says. This way, should your program sometime in the future need to bind to something that's not a public IP, it can do so.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name> drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

Maintain/Save/Restore scroll position when returning to a ListView

A very simple way:

/** Save the position **/
int currentPosition = listView.getFirstVisiblePosition();

//Here u should save the currentPosition anywhere

/** Restore the previus saved position **/
listView.setSelection(savedPosition);

The method setSelection will reset the list to the supplied item. If not in touch mode the item will actually be selected if in touch mode the item will only be positioned on screen.

A more complicated approach:

listView.setOnScrollListener(this);

//Implements the interface:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
    mCurrentX = view.getScrollX();
    mCurrentY = view.getScrollY();
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {

}

//Save anywere the x and the y

/** Restore: **/
listView.scrollTo(savedX, savedY);

How do I list the symbols in a .so file

You can use the nm -g tool from the binutils toolchain. However, their source is not always readily available. and I'm not actually even sure that this information can always be retrieved. Perhaps objcopy reveals further information.

/EDIT: The tool's name is of course nm. The flag -g is used to show only exported symbols.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.

Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.