Programs & Examples On #Watir

Watir (pronounced water) stands for Web Application Testing in Ruby. Watir is an open-source (BSD) family of Ruby libraries for automating web browsers. It is distributed as a Ruby GEM named 'Watir'. Watir was primarily developed by Bret Pettichord and Paul Rogers.

How to find out which JavaScript events fired?

Regarding Chrome, checkout the monitorEvents() via the command line API.

  • Open the console via Menu > Tools > JavaScript Console.

  • Enter monitorEvents(window);

  • View the console flooded with events

     ...
     mousemove MouseEvent {dataTransfer: ...}
     mouseout MouseEvent {dataTransfer: ...}
     mouseover MouseEvent {dataTransfer: ...}
     change Event {clipboardData: ...}
     ...
    

There are other examples in the documentation. I'm guessing this feature was added after the previous answer.

Get Absolute URL from Relative path (refactored method)

This one works for me...

new System.Uri(Page.Request.Url, ResolveClientUrl("~/mypage.aspx")).AbsoluteUri

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

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

HTML5 does not directly support requiring only one/at least one checkbox be checked in a checkbox group. Here is my solution using Javascript:

HTML

<input class='acb' type='checkbox' name='acheckbox[]' value='1' onclick='deRequire("acb")' required> One
<input class='acb' type='checkbox' name='acheckbox[]' value='2' onclick='deRequire("acb")' required> Two

JAVASCRIPT

       function deRequireCb(elClass) {
            el=document.getElementsByClassName(elClass);

            var atLeastOneChecked=false;//at least one cb is checked
            for (i=0; i<el.length; i++) {
                if (el[i].checked === true) {
                    atLeastOneChecked=true;
                }
            }

            if (atLeastOneChecked === true) {
                for (i=0; i<el.length; i++) {
                    el[i].required = false;
                }
            } else {
                for (i=0; i<el.length; i++) {
                    el[i].required = true;
                }
            }
        }

The javascript will ensure at least one checkbox is checked, then de-require the entire checkbox group. If the one checkbox that is checked becomes un-checked, then it will require all checkboxes, again!

How can I generate a list or array of sequential integers in Java?

This is the shortest I could find.

List version

public List<Integer> makeSequence(int begin, int end)
{
    List<Integer> ret = new ArrayList<Integer>(++end - begin);

    for (; begin < end; )
        ret.add(begin++);

    return ret;
}

Array Version

public int[] makeSequence(int begin, int end)
{
    if(end < begin)
        return null;

    int[] ret = new int[++end - begin];
    for (int i=0; begin < end; )
        ret[i++] = begin++;
    return ret;
}

Parallel foreach with asynchronous lambda

My lightweight implementation of ParallelForEach async.

Features:

  1. Throttling (max degree of parallelism).
  2. Exception handling (aggregation exception will be thrown at completion).
  3. Memory efficient (no need to store the list of tasks).

public static class AsyncEx
{
    public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
    {
        var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
        var tcs = new TaskCompletionSource<object>();
        var exceptions = new ConcurrentBag<Exception>();
        bool addingCompleted = false;

        foreach (T item in source)
        {
            await semaphoreSlim.WaitAsync();
            asyncAction(item).ContinueWith(t =>
            {
                semaphoreSlim.Release();

                if (t.Exception != null)
                {
                    exceptions.Add(t.Exception);
                }

                if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)
                {
                    tcs.TrySetResult(null);
                }
            });
        }

        Volatile.Write(ref addingCompleted, true);
        await tcs.Task;
        if (exceptions.Count > 0)
        {
            throw new AggregateException(exceptions);
        }
    }
}

Usage example:

await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
{
    var data = await GetData(i);
}, maxDegreeOfParallelism: 100);

How do I get a list of folders and sub folders without the files?

I used dir /s /b /o:n /a:d, and it worked perfectly, just make sure you let the file finish writing, or you'll have an incomplete list.

How to pass arguments to entrypoint in docker-compose.yml

The command clause does work as @Karthik says above.

As a simple example, the following service will have a -inMemory added to its ENTRYPOINT when docker-compose up is run.

version: '2'
services:
  local-dynamo:
    build: local-dynamo
    image: spud/dynamo
    command: -inMemory

What is correct media query for IPad Pro?

/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Portrait */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

I don't have an iPad Pro but this works for me in the Chrome simulator.

Pythonic way to print list items

I use this all the time :

#!/usr/bin/python

l = [1,2,3,7] 
print "".join([str(x) for x in l])

Google Chrome form autofill and its yellow background

Worked for me, only the css change required.

input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px #ffffff inset!important;
}

you can put any color in place of #ffffff.

submit form on click event using jquery

Do you need to post the the form to an URL or do you only need to detect the submit-event? Because you can detect the submit-event by adding onsubmit="javascript:alert('I do also submit');"

<form action="javascript:alert('submitted');" method="post" id="testForm" onsubmit="javascript:alert('I do also submit');">...</form>

Not sure that this is what you are looking for though.

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

Tomcat is not deploying my web project from Eclipse

Drop server.......... Window -> Show View -> Servers. Click right - > Delete

Click right in the Project Run Configuration

and add Server again......

Left align and right align within div in Bootstrap

We can achieve by Bootstrap 4 Flexbox:

<div class="d-flex justify-content-between w-100">
<p>TotalCost</p> <p>$42</p>
</div>

d-flex // Display Flex
justify-content-between // justify-content:space-between
w-100 // width:100%

Example: JSFiddle

SQL Server - How to lock a table until a stored procedure finishes

Needed this answer myself and from the link provided by David Moye, decided on this and thought it might be of use to others with the same question:

CREATE PROCEDURE ...
AS
BEGIN
  BEGIN TRANSACTION

  -- lock table "a" till end of transaction
  SELECT ...
  FROM a
  WITH (TABLOCK, HOLDLOCK)
  WHERE ...

  -- do some other stuff (including inserting/updating table "a")



  -- release lock
  COMMIT TRANSACTION
END

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

Add a duration to a moment (moment.js)

For people having a startTime (like 12h:30:30) and a duration (value in minutes like 120), you can guess the endTime like so:

const startTime = '12:30:00';
const durationInMinutes = '120';

const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');

// endTime is equal to "14:30"

How to "log in" to a website using Python's Requests module?

Some pages may require more than login/pass. There may even be hidden fields. The most reliable way is to use inspect tool and look at the network tab while logging in, to see what data is being passed on.

Autoreload of modules in IPython

You can use:

  import ipy_autoreload
  %autoreload 2 
  %aimport your_mod

.NET: Simplest way to send POST with data and read response

Given other answers are a few years old, currently here are my thoughts that may be helpful:

Simplest way

private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
    var client = new HttpClient();
    var response = await client.PostAsync(uri, dataOut);
    return await response.Content.ReadAsStringAsync();
    // For non strings you can use other Content.ReadAs...() method variations
}

A More Practical Example

Often we are dealing with known types and JSON, so you can further extend this idea with any number of implementations, such as:

public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
    var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

    var results = await PostAsync(uri, content); // from previous block of code

    return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}

An example of how this could be called:

var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);

How do I write a correct micro-benchmark in Java?

Tips about writing micro benchmarks from the creators of Java HotSpot:

Rule 0: Read a reputable paper on JVMs and micro-benchmarking. A good one is Brian Goetz, 2005. Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.

Rule 1: Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)

Rule 2: Always run with -XX:+PrintCompilation, -verbose:gc, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.

Rule 2.1: Print messages at the beginning and end of timing and warmup phases, so you can verify that there is no output from Rule 2 during the timing phase.

Rule 3: Be aware of the difference between -client and -server, and OSR and regular compilations. The -XX:+PrintCompilation flag reports OSR compilations with an at-sign to denote the non-initial entry point, for example: Trouble$1::run @ 2 (41 bytes). Prefer server to client, and regular to OSR, if you are after best performance.

Rule 4: Be aware of initialization effects. Do not print for the first time during your timing phase, since printing loads and initializes classes. Do not load new classes outside of the warmup phase (or final reporting phase), unless you are testing class loading specifically (and in that case load only the test classes). Rule 2 is your first line of defense against such effects.

Rule 5: Be aware of deoptimization and recompilation effects. Do not take any code path for the first time in the timing phase, because the compiler may junk and recompile the code, based on an earlier optimistic assumption that the path was not going to be used at all. Rule 2 is your first line of defense against such effects.

Rule 6: Use appropriate tools to read the compiler's mind, and expect to be surprised by the code it produces. Inspect the code yourself before forming theories about what makes something faster or slower.

Rule 7: Reduce noise in your measurements. Run your benchmark on a quiet machine, and run it several times, discarding outliers. Use -Xbatch to serialize the compiler with the application, and consider setting -XX:CICompilerCount=1 to prevent the compiler from running in parallel with itself. Try your best to reduce GC overhead, set Xmx(large enough) equals Xms and use UseEpsilonGC if it is available.

Rule 8: Use a library for your benchmark as it is probably more efficient and was already debugged for this sole purpose. Such as JMH, Caliper or Bill and Paul's Excellent UCSD Benchmarks for Java.

How to download a file from a URL in C#?

Complete class to download a file while printing status to console.

using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;

class FileDownloader
{
    private readonly string _url;
    private readonly string _fullPathWhereToSave;
    private bool _result = false;
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);

    public FileDownloader(string url, string fullPathWhereToSave)
    {
        if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
        if (string.IsNullOrEmpty(fullPathWhereToSave)) throw new ArgumentNullException("fullPathWhereToSave");

        this._url = url;
        this._fullPathWhereToSave = fullPathWhereToSave;
    }

    public bool StartDownload(int timeout)
    {
        try
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWhereToSave));

            if (File.Exists(_fullPathWhereToSave))
            {
                File.Delete(_fullPathWhereToSave);
            }
            using (WebClient client = new WebClient())
            {
                var ur = new Uri(_url);
                // client.Credentials = new NetworkCredential("username", "password");
                client.DownloadProgressChanged += WebClientDownloadProgressChanged;
                client.DownloadFileCompleted += WebClientDownloadCompleted;
                Console.WriteLine(@"Downloading file:");
                client.DownloadFileAsync(ur, _fullPathWhereToSave);
                _semaphore.Wait(timeout);
                return _result && File.Exists(_fullPathWhereToSave);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Was not able to download file!");
            Console.Write(e);
            return false;
        }
        finally
        {
            this._semaphore.Dispose();
        }
    }

    private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Console.Write("\r     -->    {0}%.", e.ProgressPercentage);
    }

    private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
    {
        _result = !args.Cancelled;
        if (!_result)
        {
            Console.Write(args.Error.ToString());
        }
        Console.WriteLine(Environment.NewLine + "Download finished!");
        _semaphore.Release();
    }

    public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
    {
        return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
    }
}

Usage:

static void Main(string[] args)
{
    var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
    Console.WriteLine("Done  - success: " + success);
    Console.ReadLine();
}

SQL Server String Concatenation with Null

Use COALESCE. Instead of your_column use COALESCE(your_column, ''). This will return the empty string instead of NULL.

Can I run HTML files directly from GitHub, instead of just viewing their source?

You can do this easily by Modifying Response Headers which can be done with Chrome and Firefox extension like Requestly.

In Chrome and Firefox:

  1. Install Requestly for Chrome and Requestly for Firefox

  2. Add the following Headers Modification Rules:

    enter image description here

    a) Content-Type:

    • Modify
    • Response
    • Header: Content-Type
    • Value: text/html
    • Source Url Matches: /raw\.githubusercontent\.com/.*\.html/


    b) Content-Security-Policy:

    • Modify
    • Response
    • Header: Content-Security-Policy
    • Value: default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src * 'unsafe-eval';
    • Source Url Matches: /raw\.githubusercontent\.com/.*\.html/

Get current working directory in a Qt application

To add on to KaZ answer, Whenever I am making a QML application I tend to add this to the main c++

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStandardPaths>

int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;

// get the applications dir path and expose it to QML 

QUrl appPath(QString("%1").arg(app.applicationDirPath()));
engine.rootContext()->setContextProperty("appPath", appPath);


// Get the QStandardPaths home location and expose it to QML 
QUrl userPath;
   const QStringList usersLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
   if (usersLocation.isEmpty())
       userPath = appPath.resolved(QUrl("/home/"));
   else
      userPath = QString("%1").arg(usersLocation.first());
   engine.rootContext()->setContextProperty("userPath", userPath);

   QUrl imagePath;
      const QStringList picturesLocation = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
      if (picturesLocation.isEmpty())
          imagePath = appPath.resolved(QUrl("images"));
      else
          imagePath = QString("%1").arg(picturesLocation.first());
      engine.rootContext()->setContextProperty("imagePath", imagePath);

      QUrl videoPath;
      const QStringList moviesLocation = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
      if (moviesLocation.isEmpty())
          videoPath = appPath.resolved(QUrl("./"));
      else
          videoPath = QString("%1").arg(moviesLocation.first());
      engine.rootContext()->setContextProperty("videoPath", videoPath);

      QUrl homePath;
      const QStringList homesLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
      if (homesLocation.isEmpty())
          homePath = appPath.resolved(QUrl("/"));
      else
          homePath = QString("%1").arg(homesLocation.first());
      engine.rootContext()->setContextProperty("homePath", homePath);

      QUrl desktopPath;
      const QStringList desktopsLocation = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
      if (desktopsLocation.isEmpty())
          desktopPath = appPath.resolved(QUrl("/"));
      else
          desktopPath = QString("%1").arg(desktopsLocation.first());
      engine.rootContext()->setContextProperty("desktopPath", desktopPath);

      QUrl docPath;
      const QStringList docsLocation = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
      if (docsLocation.isEmpty())
          docPath = appPath.resolved(QUrl("/"));
      else
          docPath = QString("%1").arg(docsLocation.first());
      engine.rootContext()->setContextProperty("docPath", docPath);


      QUrl tempPath;
      const QStringList tempsLocation = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
      if (tempsLocation.isEmpty())
          tempPath = appPath.resolved(QUrl("/"));
      else
          tempPath = QString("%1").arg(tempsLocation.first());
      engine.rootContext()->setContextProperty("tempPath", tempPath);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}

Using it in QML

....
........
............
Text{
text:"This is the applications path: " + appPath
+ "\nThis is the users home directory: " + homePath
+ "\nThis is the Desktop path: " desktopPath;
}

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

Nested rows with bootstrap grid system?

Bootstrap Version 3.x

As always, read Bootstrap's great documentation:

3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting

Make sure the parent level row is inside of a .container element. Whenever you'd like to nest rows, just open up a new .row inside of your column.

Here's a simple layout to work from:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <div class="big-box">image</div>
        </div>
        <div class="col-xs-6">
            <div class="row">
                <div class="col-xs-6"><div class="mini-box">1</div></div>
                <div class="col-xs-6"><div class="mini-box">2</div></div>
                <div class="col-xs-6"><div class="mini-box">3</div></div>
                <div class="col-xs-6"><div class="mini-box">4</div></div>
            </div>
        </div>
    </div>
</div>

Bootstrap Version 4.0

4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting

Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature

<div class="container">
  <div class="row">
    <div class="col big-box">
      image
    </div>

    <div class="col">
      <div class="row">
        <div class="col mini-box">1</div>
        <div class="col mini-box">2</div>
      </div>
      <div class="row">
        <div class="col mini-box">3</div>
        <div class="col mini-box">4</div>
      </div>
    </div>

  </div>
</div>

Demo in Fiddle jsFiddle 3.x | jsFiddle 4.0

Which will look like this (with a little bit of added styling):

screenshot

Javascript reduce() on Object

If you can use an array, do use an array, the length and order of an array are half its worth.

function reducer(obj, fun, temp){
    if(typeof fun=== 'function'){
        if(temp== undefined) temp= '';
        for(var p in obj){
            if(obj.hasOwnProperty(p)){
                temp= fun(obj[p], temp, p, obj);
            }
        }
    }
    return temp;
}
var O={a:{value:1},b:{value:2},c:{value:3}}

reducer(O, function(a, b){return a.value+b;},0);

/* returned value: (Number) 6 */

Android Button click go to another xml page

Change your FirstyActivity to:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
            btn_go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  Log.i("clicks","You Clicked B1");
              Intent i=new Intent(
                     MainActivity.this,
                     MainActivity2.class);
              startActivity(i);
            }
        }
    });

}

Hope it will help you.

Build .NET Core console application to output an EXE

For debugging purposes, you can use the DLL file. You can run it using dotnet ConsoleApp2.dll. If you want to generate an EXE file, you have to generate a self-contained application.

To generate a self-contained application (EXE in Windows), you must specify the target runtime (which is specific to the operating system you target).

Pre-.NET Core 2.0 only: First, add the runtime identifier of the target runtimes in the .csproj file (list of supported RIDs):

<PropertyGroup>
    <RuntimeIdentifiers>win10-x64;ubuntu.16.10-x64</RuntimeIdentifiers>
</PropertyGroup>

The above step is no longer required starting with .NET Core 2.0.

Then, set the desired runtime when you publish your application:

dotnet publish -c Release -r win10-x64
dotnet publish -c Release -r ubuntu.16.10-x64

how to stop a loop arduino

Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.

If that's the case, there are several solutions:

  1. If you want to generate the signal with the input of a button you could do the following

    int speakerOut = A0;
    int buttonPin = 13;
    
    void setup() {
        pinMode(speakerOut, OUTPUT);
        pinMode(buttonPin, INPUT_PULLUP);
    }
    
    int a = 0;
    
    void loop() {
        if(digitalRead(buttonPin) == LOW) {
            a ++;
            Serial.println(a);
            analogWrite(speakerOut, NULL);
    
            if(a > 50 && a < 300) {
                analogWrite(speakerOut, 200);
            }
    
            if(a <= 49) {
                analogWrite(speakerOut, NULL);
            }
    
            if(a >= 300 && a <= 2499) {
                analogWrite(speakerOut, NULL);
            }
        }
    }
    

    In this case we're using a button pin as an INPUT_PULLUP. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors. Note: This will invert the levels of the button, LOW will be pressed and HIGH will be released.

  2. The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.

jQuery selector regular expressions

James Padolsey created a wonderful filter that allows regex to be used for selection.

Say you have the following div:

<div class="asdf">

Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)")

Also, check the official documentation on selectors.

UPDATE: : syntax Deprecation JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
});

Firefox "ssl_error_no_cypher_overlap" error

Given what you've tried and the error messages, I'd say this was more to do with the exact cipher algorithm used rather than the TLS/SSL version. Are you using a non-Sun JRE by any chance, or a different vendor's security implementation? Try a different JRE/OS to test your server if you can. Failing that you might just be able to see what's going on with Wireshark (with a filter of 'tcp.port == 443').

In Python, how do I index a list with another list?

I wasn't happy with any of these approaches, so I came up with a Flexlist class that allows for flexible indexing, either by integer, slice or index-list:

class Flexlist(list):
    def __getitem__(self, keys):
        if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
        return [self[k] for k in keys]

Which, for your example, you would use as:

L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
Idx = [0, 3, 7]
T = L[ Idx ]

print(T)  # ['a', 'd', 'h']

How to switch position of two items in a Python list?

I am not an expert in python but you could try: say

i = (1,2)

res = lambda i: (i[1],i[0])
print 'res(1, 2) = {0}'.format(res(1, 2)) 

above would give o/p as:

res(1, 2) = (2,1)

python pandas convert index to datetime

Doing

df.index = pd.to_datetime(df.index, errors='coerce')

the data type of the index has changed to

dataframe information

How to unzip files programmatically in Android?

Minimal example I used to unzip a specific file from my zipfile into my applications cache folder. I then read the manifest file using a different method.

private void unzipUpdateToCache() {
    ZipInputStream zipIs = new ZipInputStream(context.getResources().openRawResource(R.raw.update));
    ZipEntry ze = null;

    try {

        while ((ze = zipIs.getNextEntry()) != null) {
            if (ze.getName().equals("update/manifest.json")) {
                FileOutputStream fout = new FileOutputStream(context.getCacheDir().getAbsolutePath() + "/manifest.json");

                byte[] buffer = new byte[1024];
                int length = 0;

                while ((length = zipIs.read(buffer))>0) {
                    fout.write(buffer, 0, length);
                }
                zipIs .closeEntry();
                fout.close();
            }
        }
        zipIs .close();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

How to insert newline in string literal?

Well, simple options are:

  • string.Format:

    string x = string.Format("first line{0}second line", Environment.NewLine);
    
  • String concatenation:

    string x = "first line" + Environment.NewLine + "second line";
    
  • String interpolation (in C#6 and above):

    string x = $"first line{Environment.NewLine}second line";
    

You could also use \n everywhere, and replace:

string x = "first line\nsecond line\nthird line".Replace("\n",
                                                         Environment.NewLine);

Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.

Use JAXB to create Object from XML String

There is no unmarshal(String) method. You should use a Reader:

Person person = (Person) unmarshaller.unmarshal(new StringReader("xml string"));

But usually you are getting that string from somewhere, for example a file. If that's the case, better pass the FileReader itself.

How to check if a registry value exists using C#?

Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.

For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.

foreach (var strServer in listServer)
{
    try
    {
        RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
        if (regCurrentUser == null)
            throw new ApplicationException("Not found registry SubKey ...");
        if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
            throw new ApplicationException("Not found value in SubKey ...");
    }
    catch (ApplicationException appEx)
    {
        Console.WriteLine(appEx);
        try
        {
            RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
            RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
            newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{ex} Pipec kakoito ...");
        }
    }
}

How to export data as CSV format from SQL Server using sqlcmd?

You can do it in a hackish way. Careful using the sqlcmd hack. If the data has double quotes or commas you will run into trouble.

You can use a simple script to do it properly:

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Data Exporter                                                 '
'                                                               '
' Description: Allows the output of data to CSV file from a SQL '
'       statement to either Oracle, SQL Server, or MySQL        '
' Author: C. Peter Chen, http://dev-notes.com                   '
' Version Tracker:                                              '
'       1.0   20080414 Original version                         '
'   1.1   20080807 Added email functionality                '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
option explicit
dim dbType, dbHost, dbName, dbUser, dbPass, outputFile, email, subj, body, smtp, smtpPort, sqlstr

'''''''''''''''''
' Configuration '
'''''''''''''''''
dbType = "oracle"                 ' Valid values: "oracle", "sqlserver", "mysql"
dbHost = "dbhost"                 ' Hostname of the database server
dbName = "dbname"                 ' Name of the database/SID
dbUser = "username"               ' Name of the user
dbPass = "password"               ' Password of the above-named user
outputFile = "c:\output.csv"      ' Path and file name of the output CSV file
email = "[email protected]"           ' Enter email here should you wish to email the CSV file (as attachment); if no email, leave it as empty string ""
  subj = "Email Subject"          ' The subject of your email; required only if you send the CSV over email
  body = "Put a message here!"    ' The body of your email; required only if you send the CSV over email
  smtp = "mail.server.com"        ' Name of your SMTP server; required only if you send the CSV over email
  smtpPort = 25                   ' SMTP port used by your server, usually 25; required only if you send the CSV over email
sqlStr = "select user from dual"  ' SQL statement you wish to execute
'''''''''''''''''''''
' End Configuration '
'''''''''''''''''''''



dim fso, conn

'Create filesystem object 
set fso = CreateObject("Scripting.FileSystemObject")

'Database connection info
set Conn = CreateObject("ADODB.connection")
Conn.ConnectionTimeout = 30
Conn.CommandTimeout = 30
if dbType = "oracle" then
    conn.open("Provider=MSDAORA.1;User ID=" & dbUser & ";Password=" & dbPass & ";Data Source=" & dbName & ";Persist Security Info=False")
elseif dbType = "sqlserver" then
    conn.open("Driver={SQL Server};Server=" & dbHost & ";Database=" & dbName & ";Uid=" & dbUser & ";Pwd=" & dbPass & ";")
elseif dbType = "mysql" then
    conn.open("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" & dbHost & ";PORT=3306;DATABASE=" & dbName & "; UID=" & dbUser & "; PASSWORD=" & dbPass & "; OPTION=3")
end if

' Subprocedure to generate data.  Two parameters:
'   1. fPath=where to create the file
'   2. sqlstr=the database query
sub MakeDataFile(fPath, sqlstr)
    dim a, showList, intcount
    set a = fso.createtextfile(fPath)

    set showList = conn.execute(sqlstr)
    for intcount = 0 to showList.fields.count -1
        if intcount <> showList.fields.count-1 then
            a.write """" & showList.fields(intcount).name & ""","
        else
            a.write """" & showList.fields(intcount).name & """"
        end if
    next
    a.writeline ""

    do while not showList.eof
        for intcount = 0 to showList.fields.count - 1
            if intcount <> showList.fields.count - 1 then
                a.write """" & showList.fields(intcount).value & ""","
            else
                a.write """" & showList.fields(intcount).value & """"
            end if
        next
        a.writeline ""
        showList.movenext
    loop
    showList.close
    set showList = nothing

    set a = nothing
end sub

' Call the subprocedure
call MakeDataFile(outputFile,sqlstr)

' Close
set fso = nothing
conn.close
set conn = nothing

if email <> "" then
    dim objMessage
    Set objMessage = CreateObject("CDO.Message")
    objMessage.Subject = "Test Email from vbs"
    objMessage.From = email
    objMessage.To = email
    objMessage.TextBody = "Please see attached file."
    objMessage.AddAttachment outputFile

    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
    objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = smtpPort

objMessage.Configuration.Fields.Update

    objMessage.Send
end if

'You're all done!!  Enjoy the file created.
msgbox("Data Writer Done!")

Source: Writing SQL output to CSV with VBScript.

JPG vs. JPEG image formats

They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.

jQuery UI 1.10: dialog and zIndex option

To sandwich an my element between the modal screen and a dialog, I need to lift my element above the modal-screen, and then lift the dialog above my element.

I had a small success by doing the following after creating the dialog on element $dlg.

$dlg.closest('.ui-dialog').css('zIndex',adjustment);

Since each dialog has a different starting z-index (they incrementally get larger) I make adjustment a string with a boost value, like this:

const adjustment = "+=99";

However, jQuery just keeps increasing the zIndex value on the modal screen, so by the second dialog, the sandwich no longer worked. I gave up on ui-dialog "modal", made it "false", and just created my own modal. It imitates jQueryUI exactly. Here it is:

CoverAll = {};
CoverAll.modalDiv = null;

CoverAll.modalCloak = function(zIndex) {
  var div = CoverAll.modalDiv;
  if(!CoverAll.modalDiv) {
    div = CoverAll.modalDiv = document.createElement('div');
    div.style.background = '#aaaaaa';
    div.style.opacity    = '0.3';
    div.style.position   = 'fixed';
    div.style.top        = '0';
    div.style.left       = '0';
    div.style.width      = '100%';
    div.style.height     = '100%';
  }
  if(!div.parentElement) {
    document.body.appendChild(div);
  }
  if(zIndex == null)
    zIndex = 100;
  div.style.zIndex  = zIndex;
  return div;
}

CoverAll.modalUncloak = function() {
  var div = CoverAll.modalDiv;
  if(div && div.parentElement) {
    document.body.removeChild(div);
  }
  return div;
}

Pure Javascript listen to input value change

As a basic example...

HTML:

<input type="text" name="Thing" value="" />

Script:

/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);

/* function */
function doThing(){
   alert('Horray! Someone wrote "' + this.value + '"!');
}

Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/

undefined offset PHP error

Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.

example:

<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>

error: Undefined offset 2

It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.

How to implement a property in an interface

  • but i already assigned values such that irp.WrmVersion = "10.4";

J.Random Coder's answer and initialize version field.


private string version = "10.4';

Android Studio doesn't recognize my device

In addition to the above configurations, I had to set deployment target to "Open Select Deployment Target Dialog", run once (choosing my device from the options listed), and from then on Android Studio was able to see my device even after changing the deployment setting back to "USB Device". My SWAG is that since Android Studio uses its own internal cache to find your device, it has to be initialized first.

How to view table contents in Mysql Workbench GUI?

To get the convenient list of tables on the left panel below each database you have to click the tiny icon on the top right of the left panel. At least in MySQL Workbench 6.3 CE on Win7 this worked to get the full list of tables.

See my screenshot to explain.enter image description here

Sadly this icon not even has a mouseover title attribute, so it was a lucky guess that I found it.

What's the difference between utf8_general_ci and utf8_unicode_ci?

There are two big difference the sorting and the character matching:

Sorting:

  • utf8mb4_general_ci removes all accents and sorts one by one which may create incorrect sort results.
  • utf8mb4_unicode_ci sorts accurate.

Character Matching

They match characters differently.

For example, in utf8mb4_unicode_ci you have i != i, but in utf8mb4_general_ci it holds i=i.

For example, imagine you have a row with name="Yilmaz". Then

select id from users where name='Yilmaz';

would return the row if collocation is utf8mb4_general_ci, but if it is collocated with utf8mb4_unicode_ci it would not return the row!

On the other hand we have that a=ª and ß=ss in utf8mb4_unicode_ci which is not the case in utf8mb4_general_ci. So imagine you have a row with name="ªßi", then

select id from users where name='assi';

would return the row if collocation is utf8mb4_unicode_ci, but would not return a row if collocation is set to utf8mb4_general_ci.

A full list of matches for each collocation may be found here.

When is the finalize() method called in Java?

finalize will print out the count for class creation.

protected void finalize() throws Throwable {
    System.out.println("Run F" );
    if ( checkedOut)
        System.out.println("Error: Checked out");
        System.out.println("Class Create Count: " + classCreate);
}

main

while ( true) {
    Book novel=new Book(true);
    //System.out.println(novel.checkedOut);
    //Runtime.getRuntime().runFinalization();
    novel.checkIn();
    new Book(true);
    //System.runFinalization();
    System.gc();

As you can see. The following out put show the gc got executed first time when the class count is 36.

C:\javaCode\firstClass>java TerminationCondition
Run F
Error: Checked out
Class Create Count: 36
Run F
Error: Checked out
Class Create Count: 48
Run F

Converting string to date in mongodb

In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })

Curl : connection refused

Make sure you have a service started and listening on the port.

netstat -ln | grep 8080

and

sudo netstat -tulpn

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

How to find row number of a value in R code

I would be tempted to use grepl, which should give all the lines with matches and can be generalised for arbitrary strings.

mydata_2 <- read.table(textConnection("
sex age height_seca1 height_chad1 height_DL weight_alog1
1 F 19 1800 1797 180 70.0
2 F 19 1682 1670 167 69.0
3 F 21 1765 1765 178 80.0
4 F 21 1829 1833 181 74.0
5 F 21 1706 1705 170 103.0
6 F 18 1607 1606 160 76.0
7 F 19 1578 1576 156 50.0
8 F 19 1577 1575 156 61.0
9 F 21 1666 1665 166 52.0
10 F 17 1710 1716 172 65.0
11 F 28 1616 1619 161 65.5
12 F 22 1648 1644 165 57.5
13 F 19 1569 1570 155 55.0
14 F 19 1779 1777 177 55.0
15 M 18 1773 1772 179 70.0
16 M 18 1816 1809 181 81.0
17 M 19 1766 1765 178 77.0
18 M 19 1745 1741 174 76.0
19 M 18 1716 1714 170 71.0
20 M 21 1785 1783 179 64.0
21 M 19 1850 1854 185 71.0
22 M 31 1875 1880 188 95.0
23 M 26 1877 1877 186 105.5
24 M 19 1836 1837 185 100.0
25 M 18 1825 1823 182 85.0
26 M 19 1755 1754 174 79.0
27 M 26 1658 1658 165 69.0
28 M 20 1816 1818 183 84.0
29 M 18 1755 1755 175 67.0"),
                       sep = " ", header = TRUE)

which(grepl(1578, mydata_2$height_seca1))

The output is:

> which(grepl(1578, mydata_2$height_seca1))
[1] 7
> 

[Edit] However, as pointed out in the comments, this will capture much more than the string 1578 (e.g. it also matches for 21578 etc) and thus should be used only if you are certain that you the length of the values you are searching will not be larger than the four characters or digits shown here.

And subsetting as per the other answer also works fine:

mydata_2[mydata_2$height_seca1 == 1578, ]
  sex age height_seca1 height_chad1 height_DL weight_alog1
7   F  19         1578         1576       156           50
> 

If you're looking for several different values, you could put them in a vector and then use the %in% operator:

look.for <- c(1578, 1658, 1616)
> mydata_2[mydata_2$height_seca1 %in% look.for, ]
   sex age height_seca1 height_chad1 height_DL weight_alog1
7    F  19         1578         1576       156         50.0
11   F  28         1616         1619       161         65.5
27   M  26         1658         1658       165         69.0
> 

Can I use git diff on untracked files?

With recent git versions you can git add -N the file (or --intent-to-add), which adds a zero-length blob to the index at that location. The upshot is that your "untracked" file now becomes a modification to add all the content to this zero-length file, and that shows up in the "git diff" output.

git diff

echo "this is a new file" > new.txt
git diff

git add -N new.txt
git diff
diff --git a/new.txt b/new.txt
index e69de29..3b2aed8 100644
--- a/new.txt
+++ b/new.txt
@@ -0,0 +1 @@
+this is a new file

Sadly, as pointed out, you can't git stash while you have an --intent-to-add file pending like this. Although if you need to stash, you just add the new files and then stash them. Or you can use the emulation workaround:

git update-index --add --cacheinfo \
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 new.txt

(setting up an alias is your friend here).

How to smooth a curve in the right way?

If you are plotting time series graph and if you have used mtplotlib for drawing graphs then use median method to smooth-en the graph

smotDeriv = timeseries.rolling(window=20, min_periods=5, center=True).median()

where timeseries is your set of data passed you can alter windowsize for more smoothining.

How to send string from one activity to another?

Say there is EditText et1 in ur MainActivity and u wanna pass this to SecondActivity

String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);

now in Second Activity, say u wanna put the string passed from EditText et1 to TextView txt1 of SecondActivity

Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);

How can I parse a YAML file in Python

I use ruamel.yaml. Details & debate here.

from ruamel import yaml

with open(filename, 'r') as fp:
    read_data = yaml.load(fp)

Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use

from ruamel import yaml

instead of

import yaml

and it will fix most of your problems.

EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.

Hibernate Criteria Query to get specific columns

You can use multiselect function for this.

   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }
            

This is supported by hibernate 5. createCriteria is deprecated in further version of hibernate. So you can use criteria builder instead.

Simulate user input in bash script

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"

Android getText from EditText field

You can simply get the text in editText by applying below code:

EditText editText=(EditText)findViewById(R.id.vnosZadeve);
String text=editText.getText().toString();

then you can toast string text!

Happy coding!

Should I use the Reply-To header when sending emails as a service to others?

Here is worked for me:

Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

It could be hardware. It could be something complicated...but I'd take a stab at suggesting that somewhere your threading code is not protecting some collection (such as a dictionary) with an appropriate lock.

What OS and service pack are you running?

Why SpringMVC Request method 'GET' not supported?

I also had the same issue. I changed it to the following and it worked.

Java :

@RequestMapping(value = "/test", method = RequestMethod.GET)

HTML code:

  <form action="<%=request.getContextPath() %>/test" method="GET">
    <input type="submit" value="submit"> 
    </form>

By default if you do not specify http method in a form it uses GET. To use POST method you need specifically state it.

Hope this helps.

What is the difference between visibility:hidden and display:none?

display: none; 

It will not be available on the page and does not occupy any space.

visibility: hidden; 

it hides an element, but it will still take up the same space as before. The element will be hidden, but still, affect the layout.

visibility: hidden preserve the space, whereas display: none doesn't preserve the space.

Display None Example:https://www.w3schools.com/css/tryit.asp?filename=trycss_display_none

Visibility Hidden Example : https://www.w3schools.com/cssref/tryit.asp?filename=trycss_visibility

How do I get the "id" after INSERT into MySQL database with Python?

Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.

converting CSV/XLS to JSON?

See if this helps: Back to CSV - Convert CSV text to Objects; via JSON

This is a blog post published in November 2008 that includes C# code to provide a solution.

From the intro on the blog post:

As Json is easier to read and write then Xml. It follows that CSV (comma seperated values) is easier to read and write then Json. CSV also has tools such as Excel and others that make it easy to work with and create. So if you ever want to create a config or data file for your next app, here is some code to convert CSV to JSON to POCO objects

Returning http 200 OK with error within response body

I think people have put too much weight into the application logic versus protocol matter. The important thing is that the response should make sense. What if you have an API that serves a dynamic resource and a request is made for X which is derived from template Y with data Z and either Y or Z isn't currently available? Is that a business logic error or a technical error? The correct answer is, "who cares?"

Your API and your responses need to be intelligible and consistent. It should conform to some kind of spec, and that spec should define what a valid response is. Something that conforms to a valid response should yield a 200 code. Something that does not conform to a valid response should yield a 4xx or 5xx code indicative of why a valid response couldn't be generated.

If your spec's definition of a valid response permits { "error": "invalid ID" }, then it's a successful response. If your spec doesn't make that accommodation, it would be a poor decision to return that response with a 200 code.

I'd draw an analogy to calling a function parseFoo. What happens when you call parseFoo("invalid data")? Does it return an error result (maybe null)? Or does it throw an exception? Many will take a near-religious position on whether one approach or the other is correct, but ultimately it's up to the API specification.

"The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request"

Obviously there's a difference of opinion with regards to whether "successfully returning an error" constitutes an HTTP success or error. I see different people interpreting the same specs different ways. So pick a side, sure, but also accept that either way the whole world isn't going to agree with you. Me? I find myself somewhere in the middle, but I'll offer some commonsense considerations.

  1. If your server-side code catches an unexpected exception when dispatching a request, that sounds like the very definition of a 500 Internal Server Error. This seems to be OP's situation. The application should not return a 200 for unexpected errors, but also see point 3.
  2. If your server-side code should be able to gracefully handle a given invalid input, and it doesn't constitute an "exceptional" error condition, your spec should accommodate HTTP 200 responses that provide meaningful diagnostic information.
  3. Above all: Have a spec. Make it consistent. Stick to it.

In OP's situation, it sounds like you have a de-facto standard that unhandled exceptions yield a 200 with a distinguishable response body. It's not ideal, but if it's not breaking things and actively causing problems, you probably have bigger, more important problems to solve.

How do I get the number of elements in a list?

In terms of how len() actually works, this is its C implementation:

static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
    Py_ssize_t res;

    res = PyObject_Size(obj);
    if (res < 0) {
        assert(PyErr_Occurred());
        return NULL;
    }
    return PyLong_FromSsize_t(res);
}

Py_ssize_t is the maximum length that the object can have. PyObject_Size() is a function that returns the size of an object. If it cannot determine the size of an object, it returns -1. In that case, this code block will be executed:

    if (res < 0) {
        assert(PyErr_Occurred());
        return NULL;
    }

And an exception is raised as a result. Otherwise, this code block will be executed:

    return PyLong_FromSsize_t(res);

res which is a C integer, is converted into a Python int (which is still called a "Long" in the C code because Python 2 had two types for storing integers) and returned.

What is com.sun.proxy.$Proxy

  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

expand/collapse table rows with JQuery

I expanded one of the answers, however my functionality is a bit different. In my version, different rows form different groups. And "header" row triggers collapsing/expanding of that particular group. Also, each individual subgroup memorizes state that its in. It might sound a bit confusing, you can test drive my version using jsfiddle. Hope this code snippets will be helpful to someone out there!

HTML

<table border="0">
  <tr>
      <th>Header 1</th>
      <th>Header 2</th>
  </tr>
  <tr>
    <td class='group1'>Group 1</td>
    <td>data 2</td>
  </tr>
  <tr class='group1'>
    <td>data 3</td>
    <td>data 4</td>
  </tr>
  <tr>
    <td class='group2'>Group 2</td>
    <td>data 2</td>
  </tr>
  <tr class='group2'>
    <td>data 3</td>
    <td>data 4</td>
  </tr>
  <tr class='group2'>
    <td class='sub_group1'>Sub Group 1</td>
    <td>data 6</td>
  </tr>
  <tr class='group2 sub_group1'>
    <td>data 7</td>
    <td>data 8</td>
  </tr>
  <tr class='group2 sub_group1'>
    <td>data 9</td>
    <td>data 10</td>
  </tr>
  <tr class='group2 sub_group1'>
    <td class='sub_sub_group1'>Sub Sub Group 1</td>
    <td>data 11</td>
  </tr>
  <tr class='group2 sub_group1 sub_sub_group1'>
    <td>data 12</td>
    <td>data 13</td>
  </tr>
  <tr class='group2 sub_group1 sub_sub_group1'>
    <td>data 14</td>
    <td>data 15</td>
  </tr>
  <tr class='group2'>
    <td class='sub_group2'>Sub Group 2</td>
    <td>data 11</td>
  </tr>
  <tr class='group2 sub_group2'>
    <td>data 12</td>
    <td>data 13</td>
  </tr>
  <tr class='group2 sub_group2'>
    <td>data 14</td>
    <td>data 15</td>
  </tr>
</table>

CSS

table, tr, td, th
{
    border: 1px solid black;
    border-collapse:collapse;
}

img.button_open{
  content:url('http://code.stephenmorley.org/javascript/collapsible-lists/button-open.png');
  cursor:pointer;
}

img.button_closed{
  content: url('http://code.stephenmorley.org/javascript/collapsible-lists/button-closed.png');
  cursor:pointer;
}

JS

function CreateGroup(group_name)
{
    // Create Button(Image)
    $('td.' + group_name).prepend("<img class='" + group_name + " button_closed'> ");
    // Add Padding to Data
    $('tr.' + group_name).each(function () {
        var first_td = $(this).children('td').first();
        var padding_left = parseInt($(first_td).css('padding-left'));
        $(first_td).css('padding-left', String(padding_left + 25) + 'px');
    });
    RestoreGroup(group_name);

    // Tie toggle function to the button
    $('img.' + group_name).click(function(){
        ToggleGroup(group_name);
    });
}

function ToggleGroup(group_name)
{
    ToggleButton($('img.' + group_name));
    RestoreGroup(group_name);
}

function RestoreGroup(group_name)
{
    if ($('img.' + group_name).hasClass('button_open'))
    {
        // Open everything
        $('tr.' + group_name).show();

        // Close subgroups that been closed
        $('tr.' + group_name).find('img.button_closed').each(function () {
            sub_group_name = $(this).attr('class').split(/\s+/)[0];
            //console.log(sub_group_name);
            RestoreGroup(sub_group_name);
        });
    }

    if ($('img.' + group_name).hasClass('button_closed'))
    {
        // Close everything
        $('tr.' + group_name).hide();
    }
}

function ToggleButton(button)
{
    $(button).toggleClass('button_open');
    $(button).toggleClass('button_closed');
}

CreateGroup('group1');
CreateGroup('group2');
CreateGroup('sub_group1');
CreateGroup('sub_group2');
CreateGroup('sub_sub_group1');

DEMO

Setting the character encoding in form submit for Internet Explorer

For Russian symbols 'windows-1251'

<form action="yourProcessPage.php" method="POST" accept-charset="utf-8">
<input name="string" value="string" />
...
</form>

When simply convert string to cp1251

$string = $_POST['string'];
$string = mb_convert_encoding($string, "CP1251", "UTF-8");

Switch statement: must default be the last case?

One scenario where I would consider it appropriate to have a 'default' located somewhere other than the end of a case statement is in a state machine where an invalid state should reset the machine and proceed as though it were the initial state. For example:

switch(widget_state)
{
  default:  /* Fell off the rails--reset and continue */
    widget_state = WIDGET_START;
    /* Fall through */
  case WIDGET_START:
    ...
    break;
  case WIDGET_WHATEVER:
    ...
    break;
}

an alternative arrangement, if an invalid state should not reset the machine but should be readily identifiable as an invalid state:

switch(widget_state) { case WIDGET_IDLE: widget_ready = 0; widget_hardware_off(); break; case WIDGET_START: ... break; case WIDGET_WHATEVER: ... break; default: widget_state = WIDGET_INVALID_STATE; /* Fall through */ case WIDGET_INVALID_STATE: widget_ready = 0; widget_hardware_off(); ... do whatever else is necessary to establish a "safe" condition }

Code elsewhere may then check for (widget_state == WIDGET_INVALID_STATE) and provide whatever error-reporting or state-reset behavior seems appropriate. For example, the status-bar code could show an error icon, and the "start widget" menu option which is disabled in most non-idle states could be enabled for WIDGET_INVALID_STATE as well as WIDGET_IDLE.

Generate HTML table from 2D JavaScript array

Generate table and support HTML as input.

Inspired by @spiny-norman https://stackoverflow.com/a/15164796/2326672

And @bornd https://stackoverflow.com/a/6234804/2326672

function escapeHtml(unsafe) {
    return String(unsafe)
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

function makeTableHTML(myArray) {
    var result = "<table border=1>";
    for(var i=0; i<myArray.length; i++) {
        result += "<tr>";
        for(var j=0; j<myArray[i].length; j++){
            k = escapeHtml((myArray[i][j]));
            result += "<td>"+k+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";

    return result;
}

Test here with JSFIDDLE - Paste directly from Microsoft Excel to get table

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

Writing Python lists to columns in csv

I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.

 writer.writerow(("ColName1", "ColName2", "ColName"))
                 for i in range(len(first_col_list)):
                     writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))

How do I convert a String to an int in Java?

You could use any of the following:

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)

How to add border around linear layout except at the bottom?

Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.

Here is a quick sample code for you to see how easy it is, but you will find more information on the link.

<com.khandelwal.library.view.BorderFrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:leftBorderColor="#00F0F0"
            app:leftBorderWidth="10dp"
            app:topBorderColor="#F0F000"
            app:topBorderWidth="15dp"
            app:rightBorderColor="#F000F0"
            app:rightBorderWidth="20dp"
            app:bottomBorderColor="#000000"
            app:bottomBorderWidth="25dp" >
    </com.khandelwal.library.view.BorderFrameLayout>

So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.

And no, I'm neither the author of this library nor one of his friend ;-)

How do I update the element at a certain position in an ArrayList?

 arrList.set(5,newValue);

and if u want to update it then add this line also

 youradapater.NotifyDataSetChanged();

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

how to convert milliseconds to date format in android?

Short and effective:

DateFormat.getDateTimeInstance().format(new Date(myMillisValue))

Center form submit buttons HTML / CSS

/* here is what works for me - set up as a class */

.button {
    text-align: center;
    display: block;
    margin: 0 auto;
}

/* you can set padding and width to whatever works best */

How to use std::sort to sort an array in C++

You can sort it std::sort(v, v + 2000)

Meaning of "referencing" and "dereferencing" in C

The context that * is in, confuses the meaning sometimes.

  // when declaring a function
int function(int*); // This function is being declared as a function that takes in an 'address' that holds a number (so int*), it's asking for a 'reference', interchangeably called 'address'. When I 'call'(use) this function later, I better give it a variable-address! So instead of var, or q, or w, or p, I give it the address of var so &var, or &q, or &w, or &p.   

//even though the symbol ' * ' is typically used to mean 'dereferenced variable'(meaning: to use the value at the address of a variable)--despite it's common use, in this case, the symbol means a 'reference', again, in THIS context. (context here being the declaration of a 'prototype'.) 


    //when calling a function
int main(){ 
    function(&var);  // we are giving the function a 'reference', we are giving it an 'address'
  }

So, in the context of declaring a type such as int or char, we would use the dereferencer ' * ' to actually mean the reference (the address), which makes it confusing if you see an error message from the compiler saying: 'expecting char*' which is asking for an address.

In that case, when the * is after a type (int, char, etc.) the compiler is expecting a variable's address. We give it this by using a reference operator, alos called the address-of operator ' & ' before a variable. Even further, in the case I just made up above, the compiler is expecting the address to hold a character value, not a number. (type char * == address of a value that has a character)

int* p;
int *a;   // both are 'pointer' declarations. We are telling the compiler that we will soon give these variables an address (with &).

int c = 10;  //declare and initialize a random variable
//assign the variable to a pointer, we do this so that we can modify the value of c from a different function regardless of the scope of that function (elaboration in a second)

p = c; //ERROR, we assigned a 'value' to this 'pointer'. We need to assign an 'address', a 'reference'.
p = &c; // instead of a value such as: 'q',5,'t', or 2.1 we gave the pointer an 'address', which we could actually print with printf(), and would be something like
//so
p = 0xab33d111; //the address of c, (not specifically this value for the address, it'll look like this though, with the 0x in the beggining, the computer treats these different from regular numbers)
*p = 10; // the value of c

a = &c; // I can still give c another pointer, even though it already has the pointer variable "p"

*a = 10;
 a = 0xab33d111;

Think of each variable as having a position (or an index value if you are familiar with arrays) and a value. It might take some getting used-to to think of each variable having two values to it, one value being it's position, physically stored with electricity in your computer, and a value representing whatever quantity or letter(s) the programmer wants to store.

//Why it's used
int function(b){
    b = b + 1; // we just want to add one to any variable that this function operates on.
} 

int main(){

    int c = 1;  // I want this variable to be 3.

    function(c); 
    function(c);// I call the function I made above twice, because I want c to be 3.

     // this will return c as 1. Even though I called it twice.
     // when you call a function it makes a copy of the variable.
     // so the function that I call "function", made a copy of c, and that function is only changing the "copy" of c, so it doesn't affect the original
}
  //let's redo this whole thing, and use pointers

int function(int* b){ // this time, the function is 'asking' (won't run without) for a variable that 'points' to a number-value (int). So it wants an integer pointer--an address that holds a number.
*b = *b + 1; //grab the value of the address, and add one to the value stored at that address
}

int main(){
    int c = 1; //again, I want this to be three at the end of the program
    int *p = &c; // on the left, I'm declaring a pointer, I'm telling the compiler that I'm about to have this letter point to an certain spot in my computer. Immediately after I used the assignment operator (the ' = ') to assign the address of c to this variable (pointer in this case) p. I do this using the address-of operator (referencer)' & '.
    function(p); // not *p, because that will dereference. which would give an integer, not an integer pointer ( function wants a reference to an int called int*, we aren't going to use *p because that will give the function an int instead of an address that stores an int.

    function(&c); // this is giving the same thing as above, p = the address of c, so we can pass the 'pointer' or we can pass the 'address' that the pointer(variable) is 'pointing','referencing' to. Which is &c. 0xaabbcc1122...


      //now, the function is making a copy of c's address, but it doesn't matter if it's a copy or not, because it's going to point the computer to the exact same spot (hence, The Address), and it will be changed for main's version of c as well.

}

Inside each and every block, it copies the variables (if any) that are passed into (via parameters within "()"s). Within those blocks, the changes to a variable are made to a copy of that variable, the variable uses the same letters but is at a different address (from the original). By using the address "reference" of the original, we can change a variable using a block outside of main, or inside a child of main.

How can I use Helvetica Neue Condensed Bold in CSS?

In case anyone is still looking for Helvetica Neue Condensed Bold, you essentially have two options.

  1. fonts.com: License the real font as a webfont from fonts.com. Free (with a badge), $10/month for 250k pageviews and $100/month for 2.5M pageviews. You can download the font to your desktop with the most expensive plan (but if you're on a Mac you already have it).
  2. myfonts.com / fontspring.com: Buy a pretty close alternative like Nimbus Sans Novus D from MyFont ($160 for unlimited pageviews), or Franklin Gothic FS Demi Condensed, from fontspring.com (about $21.95, flat one time fee with unlimited pageviews). In both cases you also get to download the font for your desktop so you can use it in Photoshop for comps.

A very cheap compromise is to buy Franklin from fontspring and then use "HelveticaNeue-CondensedBold" as the preferred font in your CSS.

h2 {"HelveticaNeue-CondensedBold", "FranklinGothicFSDemiCondensed", Arial, sans-serif;}

Then if a Mac user loads your site they see Helvetica Neue, but if they're on another platform they see Franklin.

UPDATE: I discovered a much closer match to Helvetica Neue Condensed Bold is Nimbus Sans Novus D Condensed bold. In fact, it is also derived from Helvetica. You can get it at MyFonts.com for $20 (desktop) and $20 (web, 10k pageviews). Web with unlimited pageviews is $160. I have used this font throughout (i.e. NOT exploiting the Mac's built in "NimbusSansNovusDBoldCondensed" at all) because it leads to a design that is more uniform across browsers. Built in HN and Nimbus Sans are very similar in all respects but point size. Nimbus needs a few extra points to get an identical size match.

How do you change the size of figures drawn with matplotlib?

In case you're looking for a way to change the figure size in Pandas, you could do e.g.:

df['some_column'].plot(figsize=(10, 5))

where df is a Pandas dataframe. Or, to use existing figure or axes

fig, ax = plt.subplots(figsize=(10,5))
df['some_column'].plot(ax=ax)

If you want to change the default settings, you could do the following:

import matplotlib

matplotlib.rc('figure', figsize=(10, 5))

Best way to parse command line arguments in C#?

I would strongly suggest using NDesk.Options (Documentation) and/or Mono.Options (same API, different namespace). An example from the documentation:

bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;

var p = new OptionSet () {
    { "n|name=", "the {NAME} of someone to greet.",
       v => names.Add (v) },
    { "r|repeat=", 
       "the number of {TIMES} to repeat the greeting.\n" + 
          "this must be an integer.",
        (int v) => repeat = v },
    { "v", "increase debug message verbosity",
       v => { if (v != null) ++verbosity; } },
    { "h|help",  "show this message and exit", 
       v => show_help = v != null },
};

List<string> extra;
try {
    extra = p.Parse (args);
}
catch (OptionException e) {
    Console.Write ("greet: ");
    Console.WriteLine (e.Message);
    Console.WriteLine ("Try `greet --help' for more information.");
    return;
}

Compute row average in pandas

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

How to increase application heap size in Eclipse?

Open eclipse.ini

Search for -Xmx512m or maybe more size it is.

Just change it to a required size such as I changed it to -Xmx1024m

How to use the 'main' parameter in package.json?

For OpenShift, you only get one PORT and IP pair to bind to (per application). It sounds like you should be able to serve both services from a single nodejs instance by adding internal routes for each service endpoint.

I have some info on how OpenShift uses your project's package.json to start your application here: https://www.openshift.com/blogs/run-your-nodejs-projects-on-openshift-in-two-simple-steps#package_json

Angular2: custom pipe could not be found

see this is working for me.

ActStatus.pipe.ts First this is my pipe

import {Pipe,PipeTransform} from "@angular/core";

@Pipe({
  name:'actStatusPipe'
})
export class ActStatusPipe implements PipeTransform{
  transform(status:any):any{
    switch (status) {
      case 1:
        return "UN_PUBLISH";
      case 2:
        return "PUBLISH";
      default:
        return status
    }
  }
}

main-pipe.module.ts in pipe module, i need to declare my pipe/s and export it.

import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";

import {ActStatusPipe} from "./ActStatusPipe.pipe"; // <---

@NgModule({
  declarations:[ActStatusPipe], // <---
  imports:[CommonModule],
  exports:[ActStatusPipe] // <---
})

export class MainPipe{}

app.module.ts user this pipe module in any module.

@NgModule({
  declarations: [...],
  imports: [..., MainPipe], // <---
  providers: [...],
  bootstrap: [AppComponent]
})

you can directly user pipe in this module. but if you feel that your pipe is used with in more than one component i suggest you to follow my approach.

  1. create pipe .
  2. create separate module and declare and export one or more pipe.
  3. user that pipe module.

How to use pipe totally depends on your project complexity and requirement. you might have just one pipe which used only once in the whole project. in that case you can directly use it without creating a pipe/s module (module approach).

What's the difference between console.dir and console.log?

I think Firebug does it differently than Chrome's dev tools. It looks like Firebug gives you a stringified version of the object while console.dir gives you an expandable object. Both give you the expandable object in Chrome, and I think that's where the confusion might come from. Or it's just a bug in Chrome.

In Chrome, both do the same thing. Expanding on your test, I have noticed that Chrome gets the current value of the object when you expand it.

> o = { foo: 1 }
> console.log(o)
Expand now, o.foo = 1
> o.foo = 2
o.foo is still displayed as 1 from previous lines

> o = { foo: 1 }
> console.log(o)
> o.foo = 2
Expand now, o.foo = 2

You can use the following to get a stringified version of an object if that's what you want to see. This will show you what the object is at the time this line is called, not when you expand it.

console.log(JSON.stringify(o));

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

Return list from async/await method

You need to correct your code to wait for the list to be downloaded:

List<Item> list = await GetListAsync();

Also, make sure that the method, where this code is located, has async modifier.

The reason why you get this error is that GetListAsync method returns a Task<T> which is not a completed result. As your list is downloaded asynchronously (because of Task.Run()) you need to "extract" the value from the task using the await keyword.

If you remove Task.Run(), you list will be downloaded synchronously and you don't need to use Task, async or await.

One more suggestion: you don't need to await in GetListAsync method if the only thing you do is just delegating the operation to a different thread, so you can shorten your code to the following:

private Task<List<Item>> GetListAsync(){
    return Task.Run(() => manager.GetList());
}

How to iterate for loop in reverse order in swift?

Apply the reverse function to the range to iterate backwards:

For Swift 1.2 and earlier:

// Print 10 through 1
for i in reverse(1...10) {
    println(i)
}

It also works with half-open ranges:

// Print 9 through 1
for i in reverse(1..<10) {
    println(i)
}

Note: reverse(1...10) creates an array of type [Int], so while this might be fine for small ranges, it would be wise to use lazy as shown below or consider the accepted stride answer if your range is large.


To avoid creating a large array, use lazy along with reverse(). The following test runs efficiently in a Playground showing it is not creating an array with one trillion Ints!

Test:

var count = 0
for i in lazy(1...1_000_000_000_000).reverse() {
    if ++count > 5 {
        break
    }
    println(i)
}

For Swift 2.0 in Xcode 7:

for i in (1...10).reverse() {
    print(i)
}

Note that in Swift 2.0, (1...1_000_000_000_000).reverse() is of type ReverseRandomAccessCollection<(Range<Int>)>, so this works fine:

var count = 0
for i in (1...1_000_000_000_000).reverse() {
    count += 1
    if count > 5 {
        break
    }
    print(i)
}

For Swift 3.0 reverse() has been renamed to reversed():

for i in (1...10).reversed() {
    print(i) // prints 10 through 1
}

How to extend an existing JavaScript array with another array, without creating a new array

The .push method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push:

>>> a.push(...b)

If your browser does not support ECMAScript 6, you can use .apply instead:

>>> a.push.apply(a, b)

Or perhaps, if you think it's clearer:

>>> Array.prototype.push.apply(a,b)

Please note that all these solutions will fail with a stack overflow error if array b is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that b is short enough, you should use a standard loop-based technique described in the other answer.

Call a Vue.js component method from outside the component

Here is a simple one

this.$children[indexOfComponent].childsMethodName();

How to convert a command-line argument to int?

Like that we can do....

int main(int argc, char *argv[]) {

    int a, b, c;
    *// Converting string type to integer type
    // using function "atoi( argument)"* 

    a = atoi(argv[1]);     
    b = atoi(argv[2]);
    c = atoi(argv[3]);

 }

How to convert JSON string into List of Java object?

Try this. It works with me. Hope you too!

_x000D_
_x000D_
List<YOUR_OBJECT> testList = new ArrayList<>();_x000D_
testList.add(test1);_x000D_
_x000D_
Gson gson = new Gson();_x000D_
_x000D_
String json = gson.toJson(testList);_x000D_
_x000D_
Type type = new TypeToken<ArrayList<YOUR_OBJECT>>(){}.getType();_x000D_
_x000D_
ArrayList<YOUR_OBJECT> array = gson.fromJson(json, type);
_x000D_
_x000D_
_x000D_

Is there an equivalent of CSS max-width that works in HTML emails?

Bit late to the party, but this will get it done. I left the example at 600, as that is what most people will use:

Similar to Shay's example except this also includes max-width to work on the rest of the clients that do have support, as well as a second method to prevent the expansion (media query) which is needed for Outlook '11.

In the head:

  <style type="text/css">
    @media only screen and (min-width: 600px) { .maxW { width:600px !important; } }
  </style>

In the body:

<!--[if (gte mso 9)|(IE)]><table width="600" align="center" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
<div class="maxW" style="max-width:600px;">

<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
  <tr>
    <td>
main content here
    </td>
  </tr>
</table>

</div>
<!--[if (gte mso 9)|(IE)]></td></tr></table><![endif]-->

Here is another example of this in use: Responsive order confirmation emails for mobile devices?

Is nested function a good approach when required by only one function?

>>> def sum(x, y):
...     def do_it():
...             return x + y
...     return do_it
... 
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()
4

Is this what you were looking for? It's called a closure.

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

Unknown URL content://downloads/my_downloads

I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.

else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }

This the method used to get the filepath

   public static String getFilePath(Context context, Uri uri) {

    Cursor cursor = null;
    final String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

ALTER table - adding AUTOINCREMENT in MySQL

Basic syntax for adding an AUTO_INCREMENT PRIMARY KEY to the OP's existing table:

ALTER TABLE allitems
MODIFY itemid INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY;

Or for a new table, here's the syntax example from the docs:

CREATE TABLE animals (
     id MEDIUMINT NOT NULL AUTO_INCREMENT,
     name CHAR(30) NOT NULL,
     PRIMARY KEY (id)
);

Traps and things to note:

  • An AUTO_INCREMENT column must have an index on it. (Usually, you'll want it to be the PRIMARY KEY, but MySQL does not require this.)
  • It's usually a good idea to make your AUTO_INCREMENT columns UNSIGNED. From the docs:

    Use the UNSIGNED attribute if possible to allow a greater range.

  • When using a CHANGE or MODIFY clause to make a column AUTO_INCREMENT (or indeed whenever you use a CHANGE or MODIFY clause) you should be careful to include all modifiers for the column, like NOT NULL or UNSIGNED, that show up in the table definition when you call SHOW CREATE TABLE yourtable. These modifiers will be lost otherwise.

What is the largest Safe UDP Packet Size on the Internet

512 is your best bet. It's used elsewhere and is a nice even number (half of 1024).

JSONException: Value of type java.lang.String cannot be converted to JSONObject

This worked for me

json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));

C# : Out of Memory exception

.Net4.5 does not have a 2GB limitation for objects any more. Add this lines to App.config

<runtime>
    <gcAllowVeryLargeObjects enabled="true" />    
</runtime>

and it will be possible to create very large objects without getting OutOfMemoryException

Please note it will work only on x64 OS's!

What is the use of BindingResult interface in spring MVC?

From the official Spring documentation:

General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building.

Serves as result holder for a DataBinder, obtained via the DataBinder.getBindingResult() method. BindingResult implementations can also be used directly, for example to invoke a Validator on it (e.g. as part of a unit test).

Encrypt and Decrypt in Java

Symmetric Key Cryptography : Symmetric key uses the same key for encryption and decryption. The main challenge with this type of cryptography is the exchange of the secret key between the two parties sender and receiver.

Example : The following example uses symmetric key for encryption and decryption algorithm available as part of the Sun's JCE(Java Cryptography Extension). Sun JCE is has two layers, the crypto API layer and the provider layer.

DES (Data Encryption Standard) was a popular symmetric key algorithm. Presently DES is outdated and considered insecure. Triple DES and a stronger variant of DES. It is a symmetric-key block cipher. There are other algorithms like Blowfish, Twofish and AES(Advanced Encryption Standard). AES is the latest encryption standard over the DES.

Steps :

  1. Add the Security Provider : We are using the SunJCE Provider that is available with the JDK.
  2. Generate Secret Key : Use KeyGenerator and an algorithm to generate a secret key. We are using DESede.
  3. Encode Text : For consistency across platform encode the plain text as byte using UTF-8 encoding.
  4. Encrypt Text : Instantiate Cipher with ENCRYPT_MODE, use the secret key and encrypt the bytes.
  5. Decrypt Text : Instantiate Cipher with DECRYPT_MODE, use the same secret key and decrypt the bytes.

All the above given steps and concept are same, we just replace algorithms.

import java.util.Base64;    
import javax.crypto.Cipher;  
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;  
public class EncryptionDecryptionAES {  
    static Cipher cipher;  

    public static void main(String[] args) throws Exception {
        /* 
         create key 
         If we need to generate a new key use a KeyGenerator
         If we have existing plaintext key use a SecretKeyFactory
        */ 
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // block size is 128bits
        SecretKey secretKey = keyGenerator.generateKey();

        /*
          Cipher Info
          Algorithm : for the encryption of electronic data
          mode of operation : to avoid repeated blocks encrypt to the same values.
          padding: ensuring messages are the proper length necessary for certain ciphers 
          mode/padding are not used with stream cyphers.  
         */
        cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)  

        String plainText = "AES Symmetric Encryption Decryption";
        System.out.println("Plain Text Before Encryption: " + plainText);

        String encryptedText = encrypt(plainText, secretKey);
        System.out.println("Encrypted Text After Encryption: " + encryptedText);

        String decryptedText = decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text After Decryption: " + decryptedText);
    }

    public static String encrypt(String plainText, SecretKey secretKey)
            throws Exception {
        byte[] plainTextByte = plainText.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedByte = cipher.doFinal(plainTextByte);
        Base64.Encoder encoder = Base64.getEncoder();
        String encryptedText = encoder.encodeToString(encryptedByte);
        return encryptedText;
    }

    public static String decrypt(String encryptedText, SecretKey secretKey)
            throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedTextByte = decoder.decode(encryptedText);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
        String decryptedText = new String(decryptedByte);
        return decryptedText;
    }
}

Output:

Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
Decrypted Text After Decryption: AES Symmetric Encryption Decryption

Source

Example: Cipher with two modes, they are encrypt and decrypt. we have to start every time after setting mode to encrypt or decrypt a text. enter image description here

How can I detect whether an iframe is loaded?

You may try this (using jQuery)

_x000D_
_x000D_
$(function(){_x000D_
    $('#MainPopupIframe').load(function(){_x000D_
        $(this).show();_x000D_
        console.log('iframe loaded successfully')_x000D_
    });_x000D_
        _x000D_
    $('#click').on('click', function(){_x000D_
        $('#MainPopupIframe').attr('src', 'https://heera.it');    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Using plain javascript

_x000D_
_x000D_
window.onload=function(){_x000D_
    var ifr=document.getElementById('MainPopupIframe');_x000D_
    ifr.onload=function(){_x000D_
        this.style.display='block';_x000D_
        console.log('laod the iframe')_x000D_
    };_x000D_
    var btn=document.getElementById('click');    _x000D_
    btn.onclick=function(){_x000D_
        ifr.src='https://heera.it';    _x000D_
    };_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Also you can try this (dynamic iframe)

_x000D_
_x000D_
$(function(){_x000D_
    $('#click').on('click', function(){_x000D_
        var ifr=$('<iframe/>', {_x000D_
            id:'MainPopupIframe',_x000D_
            src:'https://heera.it',_x000D_
            style:'display:none;width:320px;height:400px',_x000D_
            load:function(){_x000D_
                $(this).show();_x000D_
                alert('iframe loaded !');_x000D_
            }_x000D_
        });_x000D_
        $('body').append(ifr);    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

How does "FOR" work in cmd batch file?

Here is a good guide:

FOR /F - Loop command: against a set of files.

FOR /F - Loop command: against the results of another command.

FOR - Loop command: all options Files, Directory, List.

[The whole guide (Windows XP commands):

http://www.ss64.com/nt/index.html

Edit: Sorry, didn't see that the link was already in the OP, as it appeared to me as a part of the Amazon link.

What are all the possible values for HTTP "Content-Type" header?

As is defined in RFC 1341:

In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:

Content-Type := type "/" subtype *[";" parameter]

type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token

x-token := < The two characters "X-" followed, with no intervening white space, by any token >

subtype := token

parameter := attribute "=" value

attribute := token

value := token / quoted-string

token := 1*

tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values

And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).

As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).

Also note the comment above:

If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.

You'll notice that a lot of HTTP requests/responses include an X- header of some sort which are self defined, keep this in mind when validating the types.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.

You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.

Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

I had mixed c++/cli mfc extension dlls, that were optimised even if debug configuration (seen from VS 2017 Modules window). As previous answer suggested I changed "In VS2013 go to: Tools -> Options -> Debugging -> General and enable 'Use managed compatibility mode'. This disables the new function evaluation behavior." That settings find also in VS 2017.

But that was not enough, so I also copied the UseDebugLibraries setting from another MFC app's project file to extension dll project file.

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
      ...
      <UseDebugLibraries>true</UseDebugLibraries>

Then rebuild and that fixed the problem.

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

There are a couple of commonly quoted solutions to this problem. Unfortunately neither of these are entirely satisfactory:

  • Install the unlimited strength policy files. While this is probably the right solution for your development workstation, it quickly becomes a major hassle (if not a roadblock) to have non-technical users install the files on every computer. There is no way to distribute the files with your program; they must be installed in the JRE directory (which may even be read-only due to permissions).
  • Skip the JCE API and use another cryptography library such as Bouncy Castle. This approach requires an extra 1MB library, which may be a significant burden depending on the application. It also feels silly to duplicate functionality included in the standard libraries. Obviously, the API is also completely different from the usual JCE interface. (BC does implement a JCE provider, but that doesn't help because the key strength restrictions are applied before handing over to the implementation.) This solution also won't let you use 256-bit TLS (SSL) cipher suites, because the standard TLS libraries call the JCE internally to determine any restrictions.

But then there's reflection. Is there anything you can't do using reflection?

private static void removeCryptographyRestrictions() {
    if (!isRestrictedCryptography()) {
        logger.fine("Cryptography restrictions removal not needed");
        return;
    }
    try {
        /*
         * Do the following, but with reflection to bypass access checks:
         *
         * JceSecurity.isRestricted = false;
         * JceSecurity.defaultPolicy.perms.clear();
         * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
         */
        final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
        final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
        final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");

        final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        final Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        final Field perms = cryptoPermissions.getDeclaredField("perms");
        perms.setAccessible(true);
        ((Map<?, ?>) perms.get(defaultPolicy)).clear();

        final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
        instance.setAccessible(true);
        defaultPolicy.add((Permission) instance.get(null));

        logger.fine("Successfully removed cryptography restrictions");
    } catch (final Exception e) {
        logger.log(Level.WARNING, "Failed to remove cryptography restrictions", e);
    }
}

private static boolean isRestrictedCryptography() {
    // This matches Oracle Java 7 and 8, but not Java 9 or OpenJDK.
    final String name = System.getProperty("java.runtime.name");
    final String ver = System.getProperty("java.version");
    return name != null && name.equals("Java(TM) SE Runtime Environment")
            && ver != null && (ver.startsWith("1.7") || ver.startsWith("1.8"));
}

Simply call removeCryptographyRestrictions() from a static initializer or such before performing any cryptographic operations.

The JceSecurity.isRestricted = false part is all that is needed to use 256-bit ciphers directly; however, without the two other operations, Cipher.getMaxAllowedKeyLength() will still keep reporting 128, and 256-bit TLS cipher suites won't work.

This code works on Oracle Java 7 and 8, and automatically skips the process on Java 9 and OpenJDK where it's not needed. Being an ugly hack after all, it likely doesn't work on other vendors' VMs.

It also doesn't work on Oracle Java 6, because the private JCE classes are obfuscated there. The obfuscation does not change from version to version though, so it is still technically possible to support Java 6.

How to set page content to the middle of screen?

I'm guessing you want to center the box both vertically and horizontally, regardless of browser window size. Since you have a fixed width and height for the box, this should work:

Markup:

<div></div>

CSS:

div {
    height: 200px;
    width: 400px;
    background: black;

    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -200px;
}

The div should remain in the center of the screen even if you resize the browser. Just replace the margin-top and margin-left with half of the height and width of your table.

Edit: Credit goes to CSS-Tricks, where I got the original idea.

How to install MySQLi on MacOS

Since you are using a Mac, open a terminal, and

  • cd /etc

Find the php.ini, and sudo open it, for example, using the nano editor

  • nano php.ini

Find use control+w to search for "mysqli.default_socket", and change the line to

  • mysqli.default_socket = /tmp/mysql.sock

Use control+x and then hit "y" and "return" to save the file. Restart Aapche if necessary.

Now you should be able to run mysqli.

are there dictionaries in javascript like python?

An old question but I recently needed to do an AS3>JS port, and for the sake of speed I wrote a simple AS3-style Dictionary object for JS:

http://jsfiddle.net/MickMalone1983/VEpFf/2/

If you didn't know, the AS3 dictionary allows you to use any object as the key, as opposed to just strings. They come in very handy once you've found a use for them.

It's not as fast as a native object would be, but I've not found any significant problems with it in that respect.

API:

//Constructor
var dict = new Dict(overwrite:Boolean);

//If overwrite, allows over-writing of duplicate keys,
//otherwise, will not add duplicate keys to dictionary.

dict.put(key, value);//Add a pair
dict.get(key);//Get value from key
dict.remove(key);//Remove pair by key
dict.clearAll(value);//Remove all pairs with this value
dict.iterate(function(key, value){//Send all pairs as arguments to this function:
    console.log(key+' is key for '+value);
});


dict.get(key);//Get value from key

Portable way to check if directory exists [Windows/Linux, C]

With C++17 you can use std::filesystem::is_directory function (https://en.cppreference.com/w/cpp/filesystem/is_directory). It accepts a std::filesystem::path object which can be constructed with a unicode path.

WordPress asking for my FTP credentials to install plugins

From the first hit on Google:

WordPress asks for your FTP credentials when it can't access the files directly. This is usually caused by PHP running as the apache user (mod_php or CGI) rather than the user that owns your WordPress files.

This is rather normal in most shared hosting environments - the files are stored as the user, and Apache runs as user apache or httpd. This is actually a good security precaution so exploits and hacks cannot modify hosted files. You could circumvent this by setting all WP files to 777 security, but that means no security, so I would highly advise against that. Just use FTP, it's the automatically advised workaround with good reason.

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

For me, after I've removed Xcode, I have to switch active developer path as follows: sudo xcode-select -s /

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch

By adding #ifdef HAVE_CAMV4L around

#include <linux/videodev.h>

in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp and removing || defined (HAVE_CAMV4L2) from line 174 allowed me to compile.

How to get value of checked item from CheckedListBox?

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }

Is there a way to 'uniq' by column?

If you want to retain the last one of the duplicates you could use

 tac a.csv | sort -u -t, -r -k1,1 |tac

Which was my requirement

here

tac will reverse the file line by line

Uncaught ReferenceError: angular is not defined - AngularJS not working

You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular does not exist yet. This is an error (see your dev tools console).

In this line:

var app = angular.module(`

you are attempting to access a variable called angular. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.

  <h1>{{2+3}}</h1>

  <!-- In production use:
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  -->
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>

      <script>
        var app = angular.module('myApp',[]);

        app.directive('myDirective',function(){

            return function(scope, element,attrs) {
                element.bind('click',function() {alert('click')});
            };

        });
    </script>

For completeness, it is true that your directive is similar to the already existing directive ng-click, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.

Scanner vs. BufferedReader

In currently latest JDK6 release/build (b27), the Scanner has a smaller buffer (1024 chars) as opposed to the BufferedReader (8192 chars), but it's more than sufficient.

As to the choice, use the Scanner if you want to parse the file, use the BufferedReader if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.

  • Parsing = interpreting the given input as tokens (parts). It's able to give back you specific parts directly as int, string, decimal, etc. See also all those nextXxx() methods in Scanner class.
  • Reading = dumb streaming. It keeps giving back you all characters, which you in turn have to manually inspect if you'd like to match or compose something useful. But if you don't need to do that anyway, then reading is sufficient.

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

What's the best way to loop through a set of elements in JavaScript?

I had a very similar problem earlier with document.getElementsByClassName(). I didn't know what a nodelist was at the time.

var elements = document.getElementsByTagName('div');
for (var i=0; i<elements.length; i++) {
    doSomething(elements[i]);
}

My issue was that I expected that elements would be an array, but it isn't. The nodelist Document.getElementsByTagName() returns is iterable, but you can't call array.prototype methods on it.

You can however populate an array with nodelist elements like this:

var myElements = [];
for (var i=0; i<myNodeList.length; i++) {                               
    var element = myNodeList[i];
    myElements.push(element);
};

After that you can feel free to call .innerHTML or .style or something on the elements of your array.

Convert list to tuple in Python

I find many answers up to date and properly answered but will add something new to stack of answers.

In python there are infinite ways to do this, here are some instances
Normal way

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

smart way

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

Remember tuple is immutable ,used for storing something valuable. For example password,key or hashes are stored in tuples or dictionaries. If knife is needed why to use sword to cut apples. Use it wisely, it will also make your program efficient.

What does __FILE__ mean in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

In PHP __FILE__ is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:

File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")

I should note that in Ruby 1.9.1 __FILE__ contains the full path to the file, the above description was for when I used Ruby 1.8.7.

In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

An item with the same key has already been added

I would like to add an answer that I do not see here. It is very related to the accepted answer, however, I did not have duplicated properties on my model, it was an issue with my Javascript.

I was doing some Ajax save where I was rebuilding the model to send back to the server. When I had first initialized the page I set my original model to a variable:

var currentModel = result.Data;

My result.Data has a property: result.Data.Items

So, some time later, I do some things and want to save, via Ajax. Part of the process is to grab an array from some side process and set it to my currentModel.Items property and send currentModel to the server.

In my Javascript, however, I did this, instead:

currentModel.items = getData();

I didn't catch it, but in Visual Studio, it will auto lower case the first letter for Javascript properties (it could be a ReSharper thing too). Then, I got the exact error posted by OP when I tried to save because currentModel now has currentModel.items AND currentModel.Items

A simple change from "items" to "Items" fixed the problem.

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

How to get file_get_contents() to work with HTTPS?

I was stuck with non functional https on IIS. Solved with:

file_get_contents('https.. ) wouldn't load.

  • download https://curl.haxx.se/docs/caextract.html
  • install under ..phpN.N/extras/ssl
  • edit php.ini with:

    curl.cainfo = "C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem" openssl.cafile="C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem"

finally!

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

Also can use without parent

say router definition like:

{path:'/about',    name: 'About',   component: AboutComponent}

then can navigate by name instead of path

goToAboutPage() {
    this.router.navigate(['About']); // here "About" is name not path
}

Updated for V2.3.0

In Routing from v2.0 name property no more exist. route define without name property. so you should use path instead of name. this.router.navigate(['/path']) and no leading slash for path so use path: 'about' instead of path: '/about'

router definition like:

{path:'about', component: AboutComponent}

then can navigate by path

goToAboutPage() {
    this.router.navigate(['/about']); // here "About" is path
}

How do I reference a cell range from one worksheet to another using excel formulas?

I rewrote the code provided by Ninja2k because I didn't like that it looped through cells. For future reference here's a version using arrays instead which works noticeably faster over lots of ranges but has the same result:

Function concat2(useThis As Range, Optional delim As String) As String
    Dim tempValues
    Dim tempString
    Dim numValues As Long
    Dim i As Long, j As Long
    tempValues = useThis
    numValues = UBound(tempValues) * UBound(tempValues, 2)
    ReDim values(1 To numValues)
    For i = UBound(tempValues) To LBound(tempValues) Step -1
        For j = UBound(tempValues, 2) To LBound(tempValues, 2) Step -1
            values(numValues) = tempValues(i, j)
            numValues = numValues - 1
        Next j
    Next i
    concat2 = Join(values, delim)
End Function

I can't help but think there's definitely a better way...

Here are steps to do it manually without VBA which only works with 1d arrays and makes static values instead of retaining the references:

  1. Update cell formula to something like =Sheet2!A1:A15
  2. Hit F9
  3. Remove the curly braces { and }
  4. Place CONCATENATE( at the front of the formula after the = sign and ) at the end of the formula.
  5. Hit enter.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Here is what I typically do when a mysql slave gets out of sync. I have looked at mk-table-sync but thought the Risks section was scary looking.

On Master:

SHOW MASTER STATUS

The outputted columns (File, Position) will be of use to us in a bit.

On Slave:

STOP SLAVE

Then dump the master db and import it to the slave db.

Then run the following:

CHANGE MASTER TO
  MASTER_LOG_FILE='[File]',
  MASTER_LOG_POS=[Position];
START SLAVE;

Where [File] and [Position] are the values outputted from the "SHOW MASTER STATUS" ran above.

Hope this helps!

Remove an item from array using UnderscoreJS

or another handy way:

_.omit(arr, _.findWhere(arr, {id: 3}));

my 2 cents

How can I increment a date by one day in Java?

Something like this should do the trick:

String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date

Refresh/reload the content in Div using jquery/ajax

$("#mydiv").load(location.href + " #mydiv");

Always take note of the space just before the second # sign, otherwise the above code will return the whole page nested inside you intended DIV. Always put space.

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

" netsh wlan start hostednetwork " command not working no matter what I try

At first simply uninstall wifi drivers and softwares just keep wifi drivers + from device manager....network adapters...remove all virtual connections

then

Press the Windows + R key combination to bring up a run box, type ncpa.cpl and hit enter.

netsh wlan set hostednetwork mode=allow ssid=”How-To Geek” key=”Pa$$w0rd”

netsh wlan start hostednetwork

netsh wlan show hostednetwork

its working for me and on others PC.

Get Cell Value from a DataTable in C#

To get cell column name as well as cell value :

List<JObject> dataList = new List<JObject>();

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    JObject eachRowObj = new JObject();

    for (int j = 0; j < dataTable.Columns.Count; j++)
    {
        string key = Convert.ToString(dataTable.Columns[j]);
        string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);

        eachRowObj.Add(key, value);

    }

    dataList.Add(eachRowObj);

}

How do you use youtube-dl to download live streams (that are live)?

I have Written a small script to download the live youtube video, you may use as single command as well. script it can be invoked simply as,

~/ytdl_lv.sh <URL> <output file name>

e.g.

~/ytdl_lv.sh https://www.youtube.com/watch?v=BLIGxsYLyjc myfile.mp4

script is as simple as below,

#!/bin/bash 

# ytdl_lv.sh
# Author Prashant
# 

URL=$1 
OUTNAME=$2
streamlink --hls-live-restart -o ${OUTNAME} ${URL} best

here the best is the stream quality, it also can be 144p (worst), 240p, 360p, 480p, 720p (best)

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

YES!....always style textarea using CSS and avoid the attributes, unless you need to support some very old agent that does not support style sheets. Otherwise, you have full power to use CSS. Below is my default CSS formatting for textarea that looks beautiful in any website. Customize it as you like. Comments are included below so you can see why I chose those CSS properties and values:

textarea {
    display: inline-block;
    margin: 0;
    padding: .2em;
    width: auto;
    min-width: 30em;
    /* The max-width "100%" value fixes a weird issue where width is too wide by default and extends beyond 100% of the parent in some agents. */
    max-width: 100%;
    /* Height "auto" will allow the text area to expand vertically in size with a horizontal scrollbar if pre-existing content is added to the box before rendering. Remove this if you want a pre-set height. Use "em" to match the font size set in the website. */
    height: auto;
    /* Use "em" to define the height based on the text size set in your website and the text rows in the box, not a static pixel value. */
    min-height: 10em;
    /* Do not use "border" in textareas unless you want to remove the 3D box most browsers assign and flatten the box design. */
    /*border: 1px solid black;*/
    cursor: text;
    /* Some textareas have a light gray background by default anyway. */
    background-color: #eee;
    /* Overflow "auto" allows the box to start with no scrollbars but add them as content fills the box. */
    overflow: auto;
    /* Resize creates a tab in the lower right corner of textarea for most modern browsers and allows users to resize the box manually. Note: Resize isn't supported by most older agents and IE. */
    resize: both;
}

In my "reset" element style sheet I set these values as defaults for "textarea" by default, which give all your textareas a nice look and feel with scrolling when detected, a resizing tab (non-IE browsers), and fixes for dimensions, including a height that allows the box to size itself based on existing content you put in it for the user and a width that does not break out beyond its parent containers limitations.

How to block users from closing a window in Javascript?

This will pop a dialog asking the user if he really wants to close or stay, with a message.

var message = "You have not filled out the form.";
window.onbeforeunload = function(event) {
    var e = e || window.event;
    if (e) {
        e.returnValue = message;
    }
    return message;
};

You can then unset it before the form gets submitted or something else with

window.onbeforeunload = null;

Keep in mind that this is extremely annoying. If you are trying to force your users to fill out a form that they don't want to fill out, then you will fail: they will find a way to close the window and never come back to your mean website.

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

From io.Reader to string in Go

The most efficient way would be to always use []byte instead of string.

In case you need to print data received from the io.ReadCloser, the fmt package can handle []byte, but it isn't efficient because the fmt implementation will internally convert []byte to string. In order to avoid this conversion, you can implement the fmt.Formatter interface for a type like type ByteSlice []byte.

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

How can I solve equations in Python?

Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.

As a beginner you should probably not attempt to solve such a non-trivial problem.

Mysql select distinct

You can use group by instead of distinct. Because when you use distinct, you'll get struggle to select all values from table. Unlike when you use group by, you can get distinct values and also all fields in table.

multiple conditions for JavaScript .includes() method

Another one!

_x000D_
_x000D_
let result_x000D_
_x000D_
const givenStr = 'A, X' //values separated by comma or space._x000D_
_x000D_
const allowed  = ['A', 'B']_x000D_
const given    = givenStr.split(/[\s,]+/).filter(v => v)_x000D_
_x000D_
console.log('given (array):', given)_x000D_
_x000D_
// given contains none or only allowed values:_x000D_
_x000D_
result = given.reduce((acc, val) => {_x000D_
  return acc && allowed.includes(val)_x000D_
}, true)_x000D_
_x000D_
console.log('given contains none or only allowed values:', result)_x000D_
_x000D_
// given contains at least one allowed value:_x000D_
_x000D_
result = given.reduce((acc, val) => {_x000D_
  return acc || allowed.includes(val)_x000D_
}, false)_x000D_
_x000D_
console.log('given contains at least one allowed value:', result)
_x000D_
_x000D_
_x000D_

How to have an auto incrementing version number (Visual Studio)?

Use AssemblyInfo.cs

Create the file in App_Code: and fill out the following or use Google for other attribute/property possibilities.

AssemblyInfo.cs

using System.Reflection;

[assembly: AssemblyDescription("Very useful stuff here.")]
[assembly: AssemblyCompany("companyname")]
[assembly: AssemblyCopyright("Copyright © me 2009")]
[assembly: AssemblyProduct("NeatProduct")]
[assembly: AssemblyVersion("1.1.*")]

AssemblyVersion being the part you are really after.

Then if you are working on a website, in any aspx page, or control, you can add in the <Page> tag, the following:

CompilerOptions="<folderpath>\App_Code\AssemblyInfo.cs"

(replacing folderpath with appropriate variable of course).

I don't believe you need to add compiler options in any manner for other classes; all the ones in the App_Code should receive the version information when they are compiled.

Hope that helps.

How do I prevent Eclipse from hanging on startup?

Also look at http://www.lazylab.org/197/eclipse/eclipse-hanging-on-startup-repair-corrupt-workspace/

99% Recommended Solution works.... (i.e. Removing .snap file) But if it did not worked then we have to try to remove indexes folder and further workbench folder.

Get list of passed arguments in Windows batch script (.bat)

%1 ... %n and %* holds the arguments, but it can be tricky to access them, because the content will be interpreted.
Therefore it is impossible to handle something like this with normal statements

myBatch.bat "&"^&

Each line fails, as cmd.exe try to execute one of the ampersands (the content of %1 is "&"&)

set var=%1
set "var=%1"
set var=%~1
set "var=%~1"

But there exists a workaround with a temporary file

@echo off
SETLOCAL DisableDelayedExpansion

SETLOCAL
for %%a in (1) do (
    set "prompt=$_"
    echo on
    for %%b in (1) do rem * #%1#
    @echo off
) > param.txt
ENDLOCAL

for /F "delims=" %%L in (param.txt) do (
  set "param1=%%L"
)
SETLOCAL EnableDelayedExpansion
set "param1=!param1:*#=!"
set "param1=!param1:~0,-2!"
echo %%1 is '!param1!'

The trick is to enable echo on and expand the %1 after a rem statement (works also with %2 .. %*).
But to be able to redirect the output of echo on, you need the two FOR-LOOPS.

The extra characters * # are used to be safe against contents like /? (would show the help for REM).
Or a caret ^ at the line end could work as a multiline character.

The FOR /F should be work with delayed expansion off, else contents with "!" would be destroyed.
After removing the extra characters in param1 and you got it.

And to use param1 in a safe way, enable the delayed expansion.

Edit: One remark to %0

%0 contains the command used to call the batch, also preserving the case like in FoO.BaT
But after a call to a function %0 and also in %~0 contains the function name (or better the string that was used to call the function).
But with %~f0 you still can recall the filename.

@echo off
echo main %0, %~0, %~f0
call :myLabel+xyz
exit /b

:MYlabel
echo func %0, %~0, %~f0
exit /b

Output

main test.bat, test.bat, C:\temp\test.bat
func :myLabel+xyz, :myLabel+xyz, C:\temp\test.bat

Is there "\n" equivalent in VBscript?

As David and Remou pointed out, vbCrLf if you want a carriage-return-linefeed combination. Otherwise, Chr(13) and Chr(10) (although some VB-derivatives have vbCr and vbLf; VBScript may well have those, worth checking before using Chr).

Select All distinct values in a column using LINQ

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.

My (somewhat simple) code was:

public class Pair 
{ 
    public int id {get;set;}
    public string Arb {get;set;}
}

void Main()
{

    var theList = new List<Pair>();
    var randomiser = new Random();
    for (int count = 1; count < 10000; count++)
    {
        theList.Add(new Pair 
        {
            id = randomiser.Next(1, 50),
            Arb = "not used"
        });
    }

    var timer = new Stopwatch();
    timer.Start();
    var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);

    timer.Start();
    var otherDistinct = theList.Select(p => p.id).Distinct();
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);
}

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Converting dictionary to JSON

json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method

See json.dumps() as a save method and json.loads() as a retrieve method.

This is the code sample which might help you understand it more:

import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict

Angular 2: import external js file into component

Instead of including your js file extension in index.html, you can include it in .angular-cli-json file.

These are the steps I followed to get this working:

  1. First include your external js file in assets/js
  2. In .angular-cli.json - add the file path under scripts: [../app/assets/js/test.js]
  3. In the component where you want to use the functions of the js file.

Declare at the top where you want to import the files as

declare const Test:any;

After this you can access its functions as for example Test.add()

How to implement reCaptcha for ASP.NET MVC?

Extending Magpie's answer, here is the code for action filter which I use in my project.

It works with ASP Core RC2!

public class ReCaptchaAttribute : ActionFilterAttribute
{
    private readonly string CAPTCHA_URL = "https://www.google.com/recaptcha/api/siteverify";
    private readonly string SECRET = "your_secret";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        try
        {
            // Get recaptcha value
            var captchaResponse = filterContext.HttpContext.Request.Form["g-recaptcha-response"];

            using (var client = new HttpClient())
            {
                var values = new Dictionary<string, string>
                {
                    { "secret", SECRET },
                    { "response", captchaResponse },
                    { "remoteip", filterContext.HttpContext.Request.HttpContext.Connection.RemoteIpAddress.ToString() }
                };


                var content = new FormUrlEncodedContent(values);

                var result = client.PostAsync(CAPTCHA_URL, content).Result;

                if (result.IsSuccessStatusCode)
                {
                    string responseString = result.Content.ReadAsStringAsync().Result;

                    var captchaResult = JsonConvert.DeserializeObject<CaptchaResponseViewModel>(responseString);

                    if (!captchaResult.Success)
                    {
                        ((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha not solved");
                    }
                } else
                {
                    ((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha error");
                }
            }

        }
        catch (System.Exception)
        {
            ((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Unknown error");
        }
    }
}

And use it in your code like

[ReCaptcha]
    public IActionResult Authenticate()
    {

        if (!ModelState.IsValid)
        {
            return View(
                "Login",
                new ReturnUrlViewModel
                {
                    ReturnUrl = Request.Query["returnurl"],
                    IsError = true,
                    Error = "Wrong reCAPTCHA"
                }
            );
        }

How to uninstall a package installed with pip install --user

As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding --user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the --user option.

In my case:

antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip  pip2  pip2.7  pip3  pip3.5

And then just uninstall with the specific pip version.

How to set "value" to input web element using selenium?

As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");

How to delete a column from a table in MySQL

If you are running MySQL 5.6 onwards, you can make this operation online, allowing other sessions to read and write to your table while the operation is been performed:

ALTER TABLE tbl_Country DROP COLUMN IsDeleted, ALGORITHM=INPLACE, LOCK=NONE;

How do I pipe or redirect the output of curl -v?

If you need the output in a file you can use a redirect:

curl https://vi.stackexchange.com/ -vs >curl-output.txt 2>&1

Please be sure not to flip the >curl-output.txt and 2>&1, which will not work due to bash's redirection behavior.

How can I start PostgreSQL server on Mac OS X?

None of the previous answers fixed the issue for me, despite getting the same error messages.

I was able to get my instance back up and running by deleting the existing postmaster.pid file which was locked and was not allowing connections.

How do I horizontally center an absolute positioned element inside a 100% width div?

In my experience, the best way is right:0;, left:0; and margin:0 auto. This way if the div is wide then you aren't hindered by the left: 50%; that will offset your div which results in adding negative margins etc.

DEMO http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    margin:0 auto;
    right:0;
    left:0;
}

how to use a like with a join in sql?

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

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

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

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

This way I can control the join type.

Java sending and receiving file (byte[]) over sockets

To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];, instead we could do

    byte[] bytearray = new byte[1024*16];
    FileInputStream fis = null;
    try {

        fis = new FileInputStream(file);
        OutputStream output= socket.getOututStream();
        BufferedInputStream bis = new BufferedInputStream(fis);

        int readLength = -1;
        while ((readLength = bis.read(bytearray)) > 0) {
            output.write(bytearray, 0, readLength);

        }
        bis.close();
        output.close();
    }
    catch(Exception ex ){

        ex.printStackTrace();
    } //Excuse the poor exception handling...

Unexpected end of file error

Change the Platform of your C++ project to "x64" (or whichever platform you are targeting) instead of "Win32". This can be found in Visual Studio under Build -> Configuration Manager. Find your project in the list and change the Platform column. Don't forget to do this for all solution configurations.

how can I debug a jar at runtime?

Even though it is a runnable jar, you can still run it from a console -- open a terminal window, navigate to the directory containing the jar, and enter "java -jar yourJar.jar". It will run in that terminal window, and sysout and syserr output will appear there, including stack traces from uncaught exceptions. Be sure to have your debug set to true when you compile. And good luck.


Just thought of something else -- if you're on Win7, it often has permission problems with user applications writing files to specific directories. Make sure the directory to which you are writing your output file is one for which you have permissions.

In a future project, if it's big enough, you can use one of the standard logging facilities for 'debug' output; then it will be easy(ier) to redirect it to a file instead of depending on having a console. But for a smaller job like this, this should be fine.

Laravel - Eloquent or Fluent random row

You can easily Use this command:

// Question : name of Model
// take 10 rows from DB In shuffle records...

$questions = Question::orderByRaw('RAND()')->take(10)->get();

Insert all data of a datagridview to database at once

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
                        SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
                        cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
                        cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
                        cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
                        cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
                        cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
                        cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
                        cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        MessageBox.Show("Added successfully!");

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

You are having issue with newly MySQL version that came with "caching_sha2_password" plugin, follow the below command to get it resolved.

DROP USER 'your_user_name'@'%';
CREATE USER 'your_user_name'@'%' IDENTIFIED WITH mysql_native_password BY 'your_user_password';
GRANT ALL PRIVILEGES ON your_db_name.* TO 'your_user_name'@'%' identified by 'your_user_password';

Or you can just use the below command to keep your privileges as it is:

ALTER USER your_user_name IDENTIFIED WITH mysql_native_password;

How to listen for a WebView finishing loading a URL?

thanks for the answers. It helped me, but I had to improve it a bit for my needs. I had several pagestarts and finishes so I added a timer which checks if atfer the pagefinish is started a new pagestart. Okay, bad explanation. See the code :)

myWebView.setWebViewClient(new WebViewClient() {
        boolean loadingFinished = true;
        boolean redirect = false;

        long last_page_start;
        long now;

        // Load the url
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!loadingFinished) {
                redirect = true;
            }

            loadingFinished = false;
            view.loadUrl(url);
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.i("p","pagestart");
            loadingFinished = false;
            last_page_start = System.nanoTime();
            show_splash();
        }

        // When finish loading page
        public void onPageFinished(WebView view, String url) {
            Log.i("p","pagefinish");
            if(!redirect){
                loadingFinished = true;
            }
            //call remove_splash in 500 miSec
            if(loadingFinished && !redirect){
                now = System.nanoTime();
                new android.os.Handler().postDelayed(
                        new Runnable() {
                            public void run() {
                                remove_splash();
                            }
                        },
                        500);
            } else{
                redirect = false;
            }
        }
        private void show_splash() {
            if(myWebView.getVisibility() == View.VISIBLE) {
                myWebView.setVisibility(View.GONE);
                myWebView_splash.setVisibility(View.VISIBLE);
            }
        }
        //if a new "page start" was fired dont remove splash screen
        private void remove_splash() {
            if (last_page_start < now) {
                myWebView.setVisibility(View.VISIBLE);
                myWebView_splash.setVisibility(View.GONE);
            }
        }

});

How to execute an SSIS package from .NET?

Here's how do to it with the SSDB catalog that was introduced with SQL Server 2012...

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;

using Microsoft.SqlServer.Management.IntegrationServices;

public List<string> ExecutePackage(string folder, string project, string package)
{
    // Connection to the database server where the packages are located
    SqlConnection ssisConnection = new SqlConnection(@"Data Source=.\SQL2012;Initial Catalog=master;Integrated Security=SSPI;");

    // SSIS server object with connection
    IntegrationServices ssisServer = new IntegrationServices(ssisConnection);

    // The reference to the package which you want to execute
    PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders[folder].Projects[project].Packages[package];

    // Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
    Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();

    // Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "SYNCHRONIZED", ParameterValue = 1 });

    // Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 3 });

    // Add a project parameter (value) to fill a project parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "MyProjectParameter", ParameterValue = "some value" });

    // Add a project package (value) to fill a package parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "MyPackageParameter", ParameterValue = "some value" });

    // Get the identifier of the execution to get the log
    long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);

    // Loop through the log and do something with it like adding to a list
    var messages = new List<string>();
    foreach (OperationMessage message in ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier].Messages)
    {
        messages.Add(message.MessageType + ": " + message.Message);
    }

    return messages;
}

The code is a slight adaptation of http://social.technet.microsoft.com/wiki/contents/articles/21978.execute-ssis-2012-package-with-parameters-via-net.aspx?CommentPosted=true#commentmessage

There is also a similar article at http://domwritescode.com/2014/05/15/project-deployment-model-changes/

Force table column widths to always be fixed regardless of contents

Specify the width of the table:

table
{
    table-layout: fixed;
    width: 100px;
}

See jsFiddle

configure: error: C compiler cannot create executables

You have an old set of developer tools. gcc is reporting its version as 4.0.1. This may be left over from migrating from an older version of the OS. If you've installed Xcode 4.3.x, you need to launch it, go into its preferences, select the Downloads tab, and click "Install" next to the Command Line Tools package.

How do I prevent CSS inheritance?

Wrapping with iframe makes parent css obsolete.

How to update/modify an XML file in python?

You should read the XML file using specific XML modules. That way you can edit the XML document in memory and rewrite your changed XML document into the file.

Here is a quick start: http://docs.python.org/library/xml.dom.minidom.html

There are a lot of other XML utilities, which one is best depends on the nature of your XML file and in which way you want to edit it.

Setting initial values on load with Select2 with Ajax

Late :( but I think this will solve your problem.

 $("#controlId").val(SampleData [0].id).trigger("change");

After the data binding

 $("#controlId").select2({
        placeholder:"Select somthing",
        data: SampleData // data from ajax controll
    });
    $("#controlId").val(SampleData[0].id).trigger("change");

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

Performing user authentication in Java EE / JSF using j_security_check

I suppose you want form based authentication using deployment descriptors and j_security_check.

You can also do this in JSF by just using the same predefinied field names j_username and j_password as demonstrated in the tutorial.

E.g.

<form action="j_security_check" method="post">
    <h:outputLabel for="j_username" value="Username" />
    <h:inputText id="j_username" />
    <br />
    <h:outputLabel for="j_password" value="Password" />
    <h:inputSecret id="j_password" />
    <br />
    <h:commandButton value="Login" />
</form>

You could do lazy loading in the User getter to check if the User is already logged in and if not, then check if the Principal is present in the request and if so, then get the User associated with j_username.

package com.stackoverflow.q2206911;

import java.io.IOException;
import java.security.Principal;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Auth {

    private User user; // The JPA entity.

    @EJB
    private UserService userService;

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userService.find(principal.getName()); // Find User by j_username.
            }
        }
        return user;
    }

}

The User is obviously accessible in JSF EL by #{auth.user}.

To logout do a HttpServletRequest#logout() (and set User to null!). You can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You can also just invalidate the session altogether.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.


Update: you can also use the new Servlet 3.0 HttpServletRequest#login() to do a programmatic login instead of using j_security_check which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username and password properties and a login method which look like this:

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>

And this view scoped managed bean which also remembers the initially requested page:

@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURL += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}

This way the User is accessible in JSF EL by #{user}.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR is equivalent to wchar_t const *. It's a pointer to a wide character string that won't be modified by the function call.

You can assign to LPCWSTRs by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";

LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx is defined as FindWindowExA or FindWindowExW depending on this definition.

How to search for a part of a word with ElasticSearch

you can use regexp.

{ "_id" : "1", "name" : "John Doeman" , "function" : "Janitor"}
{ "_id" : "2", "name" : "Jane Doewoman","function" : "Teacher"  }
{ "_id" : "3", "name" : "Jimmy Jackal" ,"function" : "Student"  } 

if you use this query :

{
  "query": {
    "regexp": {
      "name": "J.*"
    }
  }
}

you will given all of data that their name start with "J".Consider you want to receive just the first two record that their name end with "man" so you can use this query :

{
  "query": { 
    "regexp": {
      "name": ".*man"
    }
  }
}

and if you want to receive all record that in their name exist "m" , you can use this query :

{
  "query": { 
    "regexp": {
      "name": ".*m.*"
    }
  }
}

This works for me .And I hope my answer be suitable for solve your problem.

How to check if a key exists in Json Object and get its value

JSONObject class has a method named "has". Returns true if this object has a mapping for name. The mapping may be NULL. http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

ActiveMQ or RabbitMQ or ZeroMQ or

Edit: My initial answer had a strong focus on AMQP. I decided to rewrite it to offer a wider view on the topic.

These 3 messaging technologies have different approaches on building distributed systems :

RabbitMQ is one of the leading implementation of the AMQP protocol (along with Apache Qpid). Therefore, it implements a broker architecture, meaning that messages are queued on a central node before being sent to clients. This approach makes RabbitMQ very easy to use and deploy, because advanced scenarios like routing, load balancing or persistent message queuing are supported in just a few lines of code. However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big.

ZeroMq is a very lightweight messaging system specially designed for high throughput/low latency scenarios like the one you can find in the financial world. Zmq supports many advanced messaging scenarios but contrary to RabbitMQ, you’ll have to implement most of them yourself by combining various pieces of the framework (e.g : sockets and devices). Zmq is very flexible but you’ll have to study the 80 pages or so of the guide (which I recommend reading for anybody writing distributed system, even if you don’t use Zmq) before being able to do anything more complicated than sending messages between 2 peers.

ActiveMQ is in the middle ground. Like Zmq, it can be deployed with both broker and P2P topologies. Like RabbitMQ, it’s easier to implement advanced scenarios but usually at the cost of raw performance. It’s the Swiss army knife of messaging :-).

Finally, all 3 products:

  • have client apis for the most common languages (C++, Java, .Net, Python, Php, Ruby, …)
  • have strong documentation
  • are actively supported

How to quietly remove a directory with content in PowerShell

This worked for me:

Remove-Item C:\folder_name -Force -Recurse

How to use AND in IF Statement

I think you should append .value in IF statement:

If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
    Cells(i, "C").Value = "BA"
End IF

Is it possible to append Series to rows of DataFrame without making a list first?

Maybe an easier way would be to add the pandas.Series into the pandas.DataFrame with ignore_index=True argument to DataFrame.append(). Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value)
    DF = DF.append(SR_row,ignore_index=True)

Demo -

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])

In [3]: df
Out[3]:
   A  B
0  1  2
1  3  4

In [5]: s = pd.Series([5,6],index=['A','B'])

In [6]: s
Out[6]:
A    5
B    6
dtype: int64

In [36]: df.append(s,ignore_index=True)
Out[36]:
   A  B
0  1  2
1  3  4
2  5  6

Another issue in your code is that DataFrame.append() is not in-place, it returns the appended dataframe, you would need to assign it back to your original dataframe for it to work. Example -

DF = DF.append(SR_row,ignore_index=True)

To preserve the labels, you can use your solution to include name for the series along with assigning the appended DataFrame back to DF. Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value,name=sample)
    DF = DF.append(SR_row)
DF.head()

How to jump to a particular line in a huge text file?

If you know in advance the position in the file (rather the line number), you can use file.seek() to go to that position.

Edit: you can use the linecache.getline(filename, lineno) function, which will return the contents of the line lineno, but only after reading the entire file into memory. Good if you're randomly accessing lines from within the file (as python itself might want to do to print a traceback) but not good for a 15MB file.

How to move from one fragment to another fragment on click of an ImageView in Android?

When you are inside an activity and need to go to a fragment use below

getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

But when you are inside a fragment and need to go to a fragment then just add a getActivity(). before, so it would become

getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

as simple as that.

The *TO_BE_REPLACED_LAYOUT_ID* can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout .

jQuery UI autocomplete with JSON

I use this script for autocomplete...

$('#custmoers_name').autocomplete({
    source: function (request, response) {

        // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
          $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
          console.log(data);
            response($.map(data, function (value, key) {
                console.log(value);
                return {
                    label: value.label,
                    value: value.value
                };
            }));
        });
    },
    minLength: 1,
    delay: 100
});

My json return :- [{"label":"Mahesh Arun Wani","value":"1"}] after search m

but it display in dropdown [object object]...

How do I get the directory that a program is running from?

You can not use argv[0] for that purpose, usually it does contain full path to the executable, but not nessesarily - process could be created with arbitrary value in the field.

Also mind you, the current directory and the directory with the executable are two different things, so getcwd() won't help you either.

On Windows use GetModuleFileName(), on Linux read /dev/proc/procID/.. files.

What is the difference between a strongly typed language and a statically typed language?

Answer is already given above. Trying to differentiate between strong vs week and static vs dynamic concept.

What is Strongly typed VS Weakly typed?

Strongly Typed: Will not be automatically converted from one type to another

In Go or Python like strongly typed languages "2" + 8 will raise a type error, because they don't allow for "type coercion".

Weakly (loosely) Typed: Will be automatically converted to one type to another: Weakly typed languages like JavaScript or Perl won't throw an error and in this case JavaScript will results '28' and perl will result 10.

Perl Example:

my $a = "2" + 8;
print $a,"\n";

Save it to main.pl and run perl main.pl and you will get output 10.

What is Static VS Dynamic type?

In programming, programmer define static typing and dynamic typing with respect to the point at which the variable types are checked. Static typed languages are those in which type checking is done at compile-time, whereas dynamic typed languages are those in which type checking is done at run-time.

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

What is this means?

In Go it checks typed before run-time (static check). This mean it not only translates and type-checks code it’s executing, but it will scan through all the code and type error would be thrown before the code is even run. For example,

package main

import "fmt"

func foo(a int) {
    if (a > 0) {
        fmt.Println("I am feeling lucky (maybe).")
    } else {
        fmt.Println("2" + 8)
    }
}

func main() {
    foo(2)
}

Save this file in main.go and run it, you will get compilation failed message for this.

go run main.go
# command-line-arguments
./main.go:9:25: cannot convert "2" (type untyped string) to type int
./main.go:9:25: invalid operation: "2" + 8 (mismatched types string and int)

But this case is not valid for Python. For example following block of code will execute for first foo(2) call and will fail for second foo(0) call. It's because Python is dynamically typed, it only translates and type-checks code it’s executing on. The else block never executes for foo(2), so "2" + 8 is never even looked at and for foo(0) call it will try to execute that block and failed.

def foo(a):
    if a > 0:
        print 'I am feeling lucky.'
    else:
        print "2" + 8
foo(2)
foo(0)

You will see following output

python main.py
I am feeling lucky.
Traceback (most recent call last):
  File "pyth.py", line 7, in <module>
    foo(0)
  File "pyth.py", line 5, in foo
    print "2" + 8
TypeError: cannot concatenate 'str' and 'int' objects

What is the significance of #pragma marks? Why do we need #pragma marks?

In simple word we can say that #pragma mark - is used for categorizing methods, so you can find your methods easily. It is very useful for long projects.

Insert line break inside placeholder attribute of a textarea?

Try this:

<textarea
placeholder="Line1&#x0a;&#x09;&#x09;&#x09;Line2"
cols="10"
rows="5"
style="resize:none">
</textarea>

http://jsfiddle.net/vr79B/