Programs & Examples On #Maximize window

This tag refers to the process of increasing the size of a UI window to its fullest, so that it takes up the entire screen.

Remove by _id in MongoDB console

Suppose we have this dummy collection:

{ "_id" : ObjectId("5ea53fedaa79db20d4e14284"), "item" : "planner", "qty" : 75 }

simply use:

db.inventory.deleteOne({ _id: ObjectId("5ea53fedaa79db20d4e14284") })

it will be deleted with this as a response:

{ "acknowledged" : true, "deletedCount" : 1 }

Thats it.

Media Queries - In between two widths

just wanted to leave my .scss example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.

Im looking forward for your feedback!

// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;

// Prepare your "function"
@mixin in-between {
     @media (min-width:$widthSmall) and (max-width:$widthMedium) {
        @content;
     }
}


// Apply your "function"
main {
   @include in-between {
      //Do something between two media queries
      padding-bottom: 20px;
   }
}

Recursive mkdir() system call on Unix

hmm I thought that mkdir -p does that?

mkdir -p this/is/a/full/path/of/stuff

How to load local html file into UIWebView

UIWebView *web=[[UIWebView alloc]initWithFrame:self.view.frame];
    //[self.view addSubview:web];
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"browser_demo" ofType:@"html" inDirectory:nil];
    [web loadRequest:[NSURLRequest requestWhttp://stackoverflow.com/review/first-postsithURL:[NSURL fileURLWithPath:filePath]]];

SQL Server CASE .. WHEN .. IN statement

Try this...

SELECT
    AlarmEventTransactionTableTable.TxnID,
    CASE
        WHEN DeviceID IN('7', '10', '62', '58', '60',
                 '46', '48', '50', '137', '139',
                 '142', '143', '164') THEN '01'
        WHEN DeviceID IN('8', '9', '63', '59', '61',
                 '47', '49', '51', '138', '140',
                 '141', '144', '165') THEN '02'
        ELSE 'NA' END AS clocking,
    AlarmEventTransactionTable.DateTimeOfTxn
 FROM
    multiMAXTxn.dbo.AlarmEventTransactionTable

Just remove highlighted string

SELECT AlarmEventTransactionTableTable.TxnID, CASE AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)

Make an html number input always display 2 decimal places

An even simpler solution would be this (IF you are targeting ALL number inputs in a particular form):

//limit number input decimal places to two
$(':input[type="number"]').change(function(){
     this.value = parseFloat(this.value).toFixed(2);
});

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Correct way of looping through C++ arrays

In C/C++ sizeof. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,

for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )

As for doing it the C++11 way, the best way to do it is probably

for(const string &text : texts)
    cout << "value of text: " << text << endl;

This lets the compiler figure out how many iterations you need.

EDIT: as others have pointed out, std::array is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof is failing the way it is, so I still think this is the better answer.

Run-time error '1004' - Method 'Range' of object'_Global' failed

Change

Range(DataImportColumn & DataImportRow).Offset(0, 2).Value

to

Cells(DataImportRow,DataImportColumn).Value

When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)

Also one more tip. You might want to fully qualify your Cells object. for example

ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

Converting Integer to String with comma for thousands

use Extension

import java.text.NumberFormat

val Int.commaString: String
  get() = NumberFormat.getInstance().format(this)

val String.commaString: String
  get() = NumberFormat.getNumberInstance().format(this.toDouble())

val Long.commaString: String
  get() = NumberFormat.getInstance().format(this)

val Double.commaString: String
  get() = NumberFormat.getInstance().format(this)

result

1234.commaString => 1,234
"1234.456".commaString => 1,234.456
1234567890123456789.commaString => 1,234,567,890,123,456,789
1234.456.commaString => 1,234.456

How do you reindex an array in PHP but with indexes starting from 1?

Simply do this:

<?php

array_push($array, '');
$array = array_reverse($array);
array_shift($array);

How to make exe files from a node.js app?

Try nexe which creates a single executable out of your node.js apps

https://github.com/nexe/nexe

Java - sending HTTP parameters via POST method easily

For those having trouble receiving the request on a php page using $_POST because you expect key-value pairs:

While all the answers where very helpful, I lacked some basic understanding on which string actually to post, since in the old apache HttpClient I used

new UrlEncodedFormEntity(nameValuePairs); (Java)

and then could use $_POST in php do get the key-value pairs.

To my understanding now one has build that string manually before posting. So the string needs to look like

val data = "key1=val1&key2=val2"

but instead just adding it to the url it is posted (in the header).

The alternative would be to use a json-string instead:

val data = "{\"key1\":\"val1\",\"key2\":\"val2\"}" // {"key1":"val1","key2":"val2"}

and pull it in php without $_POST:

$json_params = file_get_contents('php://input');
// echo_p("Data: $json_params");
$data = json_decode($json_params, true);

Here you find a sample code in Kotlin:

class TaskDownloadTest : AsyncTask<Void, Void, Void>() {
    override fun doInBackground(vararg params: Void): Void? {
        var urlConnection: HttpURLConnection? = null

        try {

            val postData = JsonObject()
            postData.addProperty("key1", "val1")
            postData.addProperty("key2", "val2")

            // reformat json to key1=value1&key2=value2
            // keeping json because I may change the php part to interpret json requests, could be a HashMap instead
            val keys = postData.keySet()
            var request = ""
            keys.forEach { key ->
                // Log.i("data", key)
                request += "$key=${postData.get(key)}&"
            }
            request = request.replace("\"", "").removeSuffix("&")
            val requestLength = request.toByteArray().size
            // Warning in Android 9 you need to add a line in the application part of the manifest: android:usesCleartextTraffic="true"
            // https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted
            val url = URL("http://10.0.2.2/getdata.php")
            urlConnection = url.openConnection() as HttpURLConnection
            // urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") // apparently default
            // Not sure what these are for, I do not use them
            // urlConnection.setRequestProperty("Content-Type", "application/json")
            // urlConnection.setRequestProperty("Key","Value")
            urlConnection.readTimeout = 5000
            urlConnection.connectTimeout = 5000
            urlConnection.requestMethod = "POST"
            urlConnection.doOutput = true
            // urlConnection.doInput = true
            urlConnection.useCaches = false
            urlConnection.setFixedLengthStreamingMode(requestLength)
            // urlConnection.setChunkedStreamingMode(0) // if you do not want to handle request length which is fine for small requests

            val out = urlConnection.outputStream
            val writer = BufferedWriter(
                OutputStreamWriter(
                    out, "UTF-8"
                )
            )
            writer.write(request)
            // writer.write("{\"key1\":\"val1\",\"key2\":\"val2\"}") // {"key1":"val1","key2":"val2"} JsonFormat or just postData.toString() for $json_params=file_get_contents('php://input'); json_decode($json_params, true); in php
            // writer.write("key1=val1&key2=val2") // key=value format for $_POST in php
            writer.flush()
            writer.close()
            out.close()

            val code = urlConnection.responseCode
            if (code != 200) {
                throw IOException("Invalid response from server: $code")
            }

            val rd = BufferedReader(
                InputStreamReader(
                    urlConnection.inputStream
                )
            )
            var line = rd.readLine()
            while (line != null) {
                Log.i("data", line)
                line = rd.readLine()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            urlConnection?.disconnect()
        }

        return null
    }
}

C# : 'is' keyword and checking for Not

While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.

MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}

Use of "this" keyword in C++

Yes. unless, there is an ambiguity.

Array vs. Object efficiency in JavaScript

  1. Indexed fields (fields with numerical keys) are stored as a holy array inside the object. Therefore lookup time is O(1)

  2. Same for a lookup array it's O(1)

  3. Iterating through an array of objects and testing their ids against the provided one is a O(n) operation.

Media query to detect if device is touchscreen

The CSS solutions don't appear to be widely available as of mid-2013. Instead...

  1. Nicholas Zakas explains that Modernizr applies a no-touch CSS class when the browser doesn’t support touch.

  2. Or detect in JavaScript with a simple piece of code, allowing you to implement your own Modernizr-like solution:

    <script>
        document.documentElement.className += 
        (("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
    </script>
    

    Then you can write your CSS as:

    .no-touch .myClass {
        ...
    }
    .touch .myClass {
        ...
    }
    

How to copy a file to multiple directories using the gnu cp command

If you want to do it without a forked command:

tee <inputfile file2 file3 file4 ... >/dev/null

How to make remote REST call inside Node.js? any CURL?

If you have Node.js 4.4+, take a look at reqclient, it allows you to make calls and log the requests in cURL style, so you can easily check and reproduce the calls outside the application.

Returns Promise objects instead of pass simple callbacks, so you can handle the result in a more "fashion" way, chain the result easily, and handle errors in a standard way. Also removes a lot of boilerplate configurations on each request: base URL, time out, content type format, default headers, parameters and query binding in the URL, and basic cache features.

This is an example of how to initialize it, make a call and log the operation with curl style:

var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
    baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});

This will log in the console...

[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json

And when the response is returned ...

[Response   client/orders]<- Status 200 - {"orderId": 1320934}

This is an example of how to handle the response with the promise object:

client.get("reports/clients")
  .then(function(response) {
    // Do something with the result
  }).catch(console.error);  // In case of error ...

Of course, it can be installed with: npm install reqclient.

Efficiently test if a port is open on Linux?

I wanted to check if a port is open on one of our linux test servers. I was able to do that by trying to connect with telnet from my dev machine to the test server. On you dev machine try to run:

$ telnet test2.host.com 8080
Trying 05.066.137.184...
Connected to test2.host.com

In this example I want to check if port 8080 is open on host test2.host.com

jQuery .scrollTop(); + animation

$("body").stop().animate({
        scrollTop: 0
    }, 500, 'swing', function () {
        console.log(confirm('Like This'))
    }
);

How to remove an element from an array in Swift

As of Xcode 10+, and according to the WWDC 2018 session 223, "Embracing Algorithms," a good method going forward will be mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows

Apple's example:

var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]

phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."

see Apple's Documentation

So in the OP's example, removing animals[2], "chimps":

var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }

This method may be preferred because it scales well (linear vs quadratic), is readable and clean. Keep in mind that it only works in Xcode 10+, and as of writing this is in Beta.

Accessing private member variables from prototype-defined functions

@Kai

That won't work. If you do

var t2 = new TestClass();

then t2.prototypeHello will be accessing t's private section.

@AnglesCrimes

The sample code works fine, but it actually creates a "static" private member shared by all instances. It may not be the solution morgancodes looked for.

So far I haven't found an easy and clean way to do this without introducing a private hash and extra cleanup functions. A private member function can be simulated to certain extent:

(function() {
    function Foo() { ... }
    Foo.prototype.bar = function() {
       privateFoo.call(this, blah);
    };
    function privateFoo(blah) { 
        // scoped to the instance by passing this to call 
    }

    window.Foo = Foo;
}());

How to upload file using Selenium WebDriver in Java

Find the tag as type="file". this the main tag which is supported by selenium. If you are able to build your XPath with same when it is recommended.

  • use sendkeys for the button having browse option(The button which will open your window box to select files)
  • Now click on the button which is going to upload your file

As below :-

driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"Lighthouse.jpg"");
Thread.sleep(5000);    
driver.findElement(By.xpath("//button[@id='Upload']")).click(); 

For multiple file upload put all files one by one by sendkeys and then click on upload

driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"Lighthouse.jpg"");  
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"home.jpg");
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"tsquare.jpg");
Thread.sleep(5000); 
driver.findElement(By.xpath("//button[@id='Upload']")).click(); // Upload button

Static Initialization Blocks

It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):

public enum Language { 
  ENGLISH("eng", "en", "en_GB", "en_US"),   
  GERMAN("de", "ge"),   
  CROATIAN("hr", "cro"),   
  RUSSIAN("ru"),
  BELGIAN("be",";-)");

  static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>(); 
  static { 
    for (Language l:Language.values()) { 
      // ignoring the case by normalizing to uppercase
      ALIAS_MAP.put(l.name().toUpperCase(),l); 
      for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l); 
    } 
  } 

  static public boolean has(String value) { 
    // ignoring the case by normalizing to uppercase
    return ALIAS_MAP.containsKey(value.toUpper()); 
  } 

  static public Language fromString(String value) { 
    if (value == null) throw new NullPointerException("alias null"); 
    Language l = ALIAS_MAP.get(value); 
    if (l == null) throw new IllegalArgumentException("Not an alias: "+value); 
    return l; 
  } 

  private List<String> aliases; 
  private Language(String... aliases) { 
    this.aliases = Arrays.asList(aliases); 
  } 
} 

Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.

As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:

  1. The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
  2. static block and initialization of static fields in the order of occurrence.

This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):

public class Foo {
  static { System.out.println("Static Block 1"); }
  public static final Foo FOO = new Foo();
  static { System.out.println("Static Block 2"); }
  public Foo() { System.out.println("Constructor"); }
  static public void main(String p[]) {
    System.out.println("In Main");
    new Foo();
  }
}

What we see is the following output:

Static Block 1
Constructor
Static Block 2
In Main
Constructor

Clear is that the static initialization actually can happen before the constructor, and even after:

Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.

For more info on this see the book "Effective Java".

JUnit 4 compare Sets

Using Hamcrest:

assertThat( set1, both(everyItem(isIn(set2))).and(containsInAnyOrder(set1)));

This works also when the sets have different datatypes, and reports on the difference instead of just failing.

How do I reference tables in Excel using VBA?

The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of

Sheets("Sheet1").Table("A_Table").Select

would be this statement:

Sheets("Sheet1").ListObjects("A_Table").Range.Select

or to select parts (like only the data in the table):

Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select        ' Select just header row
LO.DataBodyRange.Select         ' Select just data cells
LO.TotalsRowRange.Select        ' Select just totals row

For the parts, you may want to test for the existence of the header and totals rows before selecting them.

And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!

How do I call a SQL Server stored procedure from PowerShell?

Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each line with the call to the stored procedure.

SQL Server provides some assemblies that could be of use with the name SMO that have seamless integration with PowerShell. Here is an article on that.

http://www.databasejournal.com/features/mssql/article.php/3696731

There are API methods to execute stored procedures that I think are worth being investigated. Here a startup example:

http://www.eggheadcafe.com/software/aspnet/29974894/smo-running-a-stored-pro.aspx

Merge 2 DataTables and store in a new one

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
{
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table
    dtAllCountries.Merge(dtCountry);
}

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

IIS 6.0 and previous versions :

ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.

This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.

Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.

The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests

What's a SCRIPT MAP ?

Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed

A good example can be seen here

IIS 7 and above

IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.

IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )

What this means is that IIS 7 processes requests that arrive for any content type, with both NON ASP.NET Modules / native IIS modules and ASP.NET modules providing request processing in all stages This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.

  • You can build new managed modules (IHttpModule) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.
  • Add new managed Handlers ( IHttpHandler)

static linking only some libraries

Some loaders (linkers) provide switches for turning dynamic loading on and off. If GCC is running on such a system (Solaris - and possibly others), then you can use the relevant option.

If you know which libraries you want to link statically, you can simply specify the static library file in the link line - by full path.

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

Capturing mobile phone traffic on Wireshark

Wireshark + OSX + iOS:

Great overview so far, but if you want specifics for Wireshark + OSX + iOS:

  • install Wireshark on your computer
  • connect iOS device to computer via USB cable
  • connect iOS device and computer to the same WiFi network
  • run this command in a OSX terminal window: rvictl -s x where x is the UDID of your iOS device. You can find the UDID of your iOS device via iTunes (make sure you are using the UDID and not the serial number).
  • goto Wireshark Capture->Options, a dialog box appears, click on the line rvi0 then press the Start button.

Wireshark Capture Options Dialog Box

Now you will see all network traffic on the iOS device. It can be pretty overwhelming. A couple of pointers:

  • don't use iOS with a VPN, you don't be able to make sense of the encrypted traffic
  • use simple filters to focus on interesting traffic
  • ip.addr==204.144.14.134 views traffic with a source or destination address of 204.144.14.134
  • http views only http traffic

Here's a sample window depicting TCP traffic for for pdf download from 204.144.14.134:

Wireshark TCP traffic for pdf download from 204.144.14.134

What is compiler, linker, loader?

=====> COMPILATION PROCESS <======

                     |
                     |---->  Input is Source file(.c)
                     |
                     V
            +=================+
            |                 |
            | C Preprocessor  |
            |                 |
            +=================+
                     |
                     | ---> Pure C file ( comd:cc -E <file.name> )
                     |
                     V
            +=================+
            |                 |
            | Lexical Analyzer|
            |                 |
            +-----------------+
            |                 |
            | Syntax Analyzer |
            |                 |
            +-----------------+
            |                 |
            | Semantic Analyze|
            |                 |
            +-----------------+
            |                 |
            | Pre Optimization|
            |                 |
            +-----------------+
            |                 |
            | Code generation |
            |                 |
            +-----------------+
            |                 |
            | Post Optimize   |
            |                 |
            +=================+
                     |
                     |--->  Assembly code (comd: cc -S <file.name> )
                     |
                     V
            +=================+
            |                 |
            |   Assembler     |
            |                 |
            +=================+
                     |
                     |--->  Object file (.obj) (comd: cc -c <file.name>)
                     |
                     V
            +=================+
            |     Linker      |
            |      and        |
            |     loader      |
            +=================+
                     |
                     |--->  Executable (.Exe/a.out) (com:cc <file.name> ) 
                     |
                     V
            Executable file(a.out)

C preprocessor :-

C preprocessing is the first step in the compilation. It handles:

  1. #define statements.
  2. #include statements.
  3. Conditional statements.
  4. Macros

The purpose of the unit is to convert the C source file into Pure C code file.

C compilation :

There are Six steps in the unit :

1) Lexical Analyzer:

It combines characters in the source file, to form a "TOKEN". A token is a set of characters that does not have 'space', 'tab' and 'new line'. Therefore this unit of compilation is also called "TOKENIZER". It also removes the comments, generates symbol table and relocation table entries.

2) Syntactic Analyzer:

This unit check for the syntax in the code. For ex:

{
    int a;
    int b;
    int c;
    int d;

    d = a + b - c *   ;
}

The above code will generate the parse error because the equation is not balanced. This unit checks this internally by generating the parser tree as follows:

                            =
                          /   \
                        d       -
                              /     \
                            +           *
                          /   \       /   \
                        a       b   c       ?

Therefore this unit is also called PARSER.

3) Semantic Analyzer:

This unit checks the meaning in the statements. For ex:

{
    int i;
    int *p;

    p = i;
    -----
    -----
    -----
}

The above code generates the error "Assignment of incompatible type".

4) Pre-Optimization:

This unit is independent of the CPU, i.e., there are two types of optimization

  1. Preoptimization (CPU independent)
  2. Postoptimization (CPU dependent)

This unit optimizes the code in following forms:

  • I) Dead code elimination
  • II) Sub code elimination
  • III) Loop optimization

I) Dead code elimination:

For ex:

{
    int a = 10;
    if ( a > 5 ) {
        /*
        ...
        */
    } else {
       /*
       ...
       */
    }
}

Here, the compiler knows the value of 'a' at compile time, therefore it also knows that the if condition is always true. Hence it eliminates the else part in the code.

II) Sub code elimination:

For ex:

{
    int a, b, c;
    int x, y;

    /*
    ...
    */

    x = a + b;
    y = a + b + c;

    /*
    ...
    */
}

can be optimized as follows:

{
    int a, b, c;
    int x, y;

    /*
     ...
    */

    x = a + b;
    y = x + c;      // a + b is replaced by x

    /*
     ...
    */
}

III) Loop optimization:

For ex:

{
    int a;
    for (i = 0; i < 1000; i++ ) {

    /*
     ...
    */

    a = 10;

    /*
     ...
    */
    }
}

In the above code, if 'a' is local and not used in the loop, then it can be optimized as follows:

{
    int a;
    a = 10;
    for (i = 0; i < 1000; i++ ) {
        /*
        ...
        */
    }
}

5) Code generation:

Here, the compiler generates the assembly code so that the more frequently used variables are stored in the registers.

6) Post-Optimization:

Here the optimization is CPU dependent. Suppose if there are more than one jumps in the code then they are converted to one as:

            -----
        jmp:<addr1>
<addr1> jmp:<addr2>
            -----
            -----

The control jumps to the directly.

Then the last phase is Linking (which creates executable or library). When the executable is run, the libraries it requires are Loaded.

How do I exit the Vim editor?

Pictures are worth a thousand Unix commands and options:

Enter image description here

I draw this to my students each semester and they seem to grasp vi afterwards.

vi is a finite state machine with only three states.

Upon starting, vi goes into COMMAND mode, where you can type short, few character commands, blindly. You know what you are doing; this isn't for amateurs.

When you want to actually edit text, you should go to INSERT mode with some one-character command:

  • i: go to INSERT in the place of the cursor
  • I: go to INSERT mode at the beginning of the line
  • a: append after the cursor
  • A: append at the end of line
  • o: open a new line below the current line
  • O: open a new line in the place of the current line

Now, answering the question: exiting.

You can exit vi from EX mode:

  • q: if you haven't made any modifications, or saved them beforehand
  • q!: ignores any modifications and quit
  • wq: save and quit
  • x: this is equal to wq

w and x accept a file name parameter. If you started vi with a filename, you need not give it here again.

At last, the most important: how can you reach EX mode?

EX mode is for long commands that you can see typing at the bottom line of the screen. From COMMAND mode, you push colon, :, and a colon will appear at the bottom line, where you can type the above commands.

From INSERT mode, you need to push ESC, i.e. the Escape button, going to COMMAND mode, and then : to go to EX mode.

If you are unsure, push ESC and that will bring you to command mode.

So, the robust method is ESC-:-x-Enter which saves your file and quits.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

In PHP arrays are passed to functions by value by default, unless you explicitly pass them by reference, as the following snippet shows:

$foo = array(11, 22, 33);

function hello($fooarg) {
  $fooarg[0] = 99;
}

function world(&$fooarg) {
  $fooarg[0] = 66;
}

hello($foo);
var_dump($foo); // (original array not modified) array passed-by-value

world($foo);
var_dump($foo); // (original array modified) array passed-by-reference

Here is the output:

array(3) {
  [0]=>
  int(11)
  [1]=>
  int(22)
  [2]=>
  int(33)
}
array(3) {
  [0]=>
  int(66)
  [1]=>
  int(22)
  [2]=>
  int(33)
}

Parse JSON response using jQuery

I was hanging out on Google, then I found your question and it's very simple to parse JSON response into normal HTML. Just use this little JavaScript code:

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

</script>

</body>
</html>

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

How to write palindrome in JavaScript

You could also do something like this :

function isPalindrome(str) {
var newStr = '';

for(var i = str.length - 1; i >=0; i--) {
    newStr += str[i];
}

if(newStr == str) {
    return true;
    return newStr;
} else {
    return false;
    return newStr;
}
}

Youtube iframe wmode issue

If you are using the new asynchronous API, you will need to add the parameter like so:

<!-- YOUTUBE -->
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
var initialVideo = 'ApkM4t9L5jE'; // YOUR YOUTUBE VIDEO ID
function onYouTubePlayerAPIReady() {
    console.log("onYouTubePlayerAPIReady" + initialVideo);
    player = new YT.Player('player', {
      height: '381',
      width: '681',
      wmode: 'transparent', // SECRET SAUCE HERE
      videoId: initialVideo,      
       playerVars: { 'autoplay': 1, 'rel': 0, 'wmode':'transparent' },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
}

This is based on the google documentation and example here: http://code.google.com/apis/youtube/iframe_api_reference.html

vba error handling in loop

As a general way to handle error in a loop like your sample code, I would rather use:

on error resume next
for each...
    'do something that might raise an error, then
    if err.number <> 0 then
         ...
    end if
 next ....

Is there a list of screen resolutions for all Android based phones and tablets?

(out of date) Spreadsheet of device metrics.

SEE ALSO:
Device Metrics - Material Design.
Screen Sizes.

---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------                                                          
Galaxy Y                                 320 x  240     ldpi    0.75    120      427 x 320      4:3     1.3333                   427 x 320
?                                        400 x  240     ldpi    0.75    120      533 x 320      5:3     1.6667                   533 x 320
?                                        432 x  240     ldpi    0.75    120      576 x 320      9:5     1.8000                   576 x 320
Galaxy Ace                               480 x  320     mdpi    1       160      480 x 320      3:2     1.5000                   480 x 320
Nexus S                                  800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
"Galaxy SIII    Mini"                    800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
?                                        854 x  480     hdpi    1.5     240      569 x 320      427:240 1.7792                   569 x 320

Galaxy SIII                             1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Galaxy Nexus                            1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
HTC One X                       4.7"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 5                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778      YES          592 x 360
Galaxy S4                       5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note III                 5.7"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One Max                     5.9"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note II                  5.6"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 4                         4.4"    1200 x  768     xhdpi   2       320      600 x 384      25:16   1.5625      YES          552 x 384
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
?                                        800 x  480     mdpi    1       160      800 x 480      5:3     1.6667                   800 x 480
?                                        854 x  480     mdpi    1       160      854 x 480      427:240 1.7792                   854 x 480
Galaxy Mega                     6.3"    1280 x  720     hdpi    1.5     240      853 x 480      16:9    1.7778                   853 x 480
Kindle Fire HD                  7"      1280 x  800     hdpi    1.5     240      853 x 533      8:5     1.6000                   853 x 533
Galaxy Mega                     5.8"     960 x  540     tvdpi   1.33333 213.333  720 x 405      16:9    1.7778                   720 x 405
Sony Xperia Z Ultra             6.4"    1920 x 1080     xhdpi   2       320      960 x 540      16:9    1.7778                   960 x 540
Blackberry Priv                 5.43"   2560 x 1440     ?               540          ?          16:9    1.7778      
Blackberry Passport             4.5"    1440 x 1440     ?               453          ?          1:1     1.0     

Kindle Fire (1st & 2nd gen)     7"      1024 x  600     mdpi    1       160     1024 x 600      128:75  1.7067                  1024 x 600
Tesco Hudl                      7"      1400 x  900     hdpi    1.5     240      933 x 600      14:9    1.5556                   933 x 600
Nexus 7 (1st gen/2012)          7"      1280 x  800     tvdpi   1.33333 213.333  960 x 600      8:5     1.6000      YES          912 x 600
Nexus 7 (2nd gen/2013)          7"      1824 x 1200     xhdpi   2       320      912 x 600      38:25   1.5200      YES          864 x 600
Kindle Fire HDX                 7"      1920 x 1200     xhdpi   2       320      960 x 600      8:5     1.6000                   960 x 600
?                                        800 x  480     ldpi    0.75    120     1067 x 640      5:3     1.6667                  1067 x 640
?                                        854 x  480     ldpi    0.75    120     1139 x 640      427:240 1.7792                  1139 x 640

Kindle Fire HD                  8.9"    1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Kindle Fire HDX                 8.9"    2560 x 1600     xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 2                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 3                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer                10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer 2              10"     1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Nexus 10                        10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Note 10.1                10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------

Coping with different aspect ratios

The different aspect ratios seen above are (from most square; h/w):

1:1     1.0     <- rare for phone; common for watch
4:3     1.3333  <- matches iPad (when portrait)
3:2     1.5000
38:25   1.5200
14:9    1.5556  <- rare
25:16   1.5625
8:5     1.6000  <- aka 16:10
5:3     1.6667
128:75  1.7067
16:9    1.7778  <- matches iPhone 5-7
427:240 1.7792  <- rare
37:18   2.0555  <- Galaxy S8

If you skip the extreme aspect ratios, that are rarely seen at phone size or larger, all the other devices fit a range from 1.3333 to 1.7778, which conveniently matches the current iPhone/iPad ratios (considering all devices in portrait mode). Note that there are quite a few variations within that range, so if you are creating a small number of fixed aspect-ratio layouts, you will need to decide how to handle the odd "in-between" screens.

Minimum "portrait mode" solution is to support 1.3333, which results in unused space at top and bottom, on all the resolutions with larger aspect ratio.
Most likely, you would instead design it to stretch over the 1.333 to 1.778 range. But sometimes part of your design looks too distorted then.


Advanced layout ideas:

For text, you can design for 1.3333, then increase line spacing for 1.666 - though that will look quite sparse. For graphics, design for an intermediate ratio, so that on some screens it is slightly squashed, on others it is slightly stretched. geometric mean of Sqrt(1333 x 1667) ~= 1491. So you design for 1491 x 1000, which will be stretched/squashed by +-12% when assigned to the extreme cases.

Next refinement is to design layout as a stack of different-height "bands" that each fill the width of the screen. Then determine where you can most pleasingly "stretch-or-squash" a band's height, to adjust for different ratios.

For example, consider imaginary phones with 1333 x 1000 pixels and 1666 x 1000 pixels. Suppose you have two "bands", and your main "band" is square, so it is 1000 x 1000. Second band is 333 x 1000 on one screen, 666 x 1000 on the other - quite a range to design for.
You might decide your main band looks okay altered 10% up-or-down, and squash it 900 x 1000 on the 1333 x 1000 screen, leaving 433 x 1000. Then stretch it to 1100 x 1000 on 1666 x 1000 screen, leaving 566 x 1000. So your second band now needs to adjust over only 433 to 566, which has geometric mean of Sqrt(433 x 566) ~= 495. So you design for 495 x 1000, which will be stretched/squashed by +-14% when assigned to the extreme cases.

WPF chart controls

aM Charts are also making WPF Chart controls. Currently they only show off a pie chart, but they are set to provide new ones in short term.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.

You can either disable it by editing web.config to include the following:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Or better yet properly configure it by modifying the Application_Start method in global.asax:

void Application_Start(object sender, EventArgs e) 
{
    RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
        new ScriptResourceDefinition
        {
            Path = "/~Scripts/jquery-2.1.1.min.js"
        }
    );
}

Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.

For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace @default
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }
    }
}

Numpy how to iterate over columns of array?

Just iterate over the transposed of your array:

for column in array.T:
   some_function(column)

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

Using the passwd command from within a shell script

I stumbled upon the same problem and for some reason the --stdin option was not available on the version of passwd I was using (shipped in Ubuntu 14.04).

If any of you happen to experience the same issue, you can work it around as I did, by using the chpasswd command like this:

echo "<user>:<password>" | chpasswd

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

Set Jackson Timezone for Date deserialization

Your date object is probably ok, since you sent your date encoded in ISO format with GMT timezone and you are in EST when you print your date.

Note that Date objects perform timezone translation at the moment they are printed. You can check if your date object is correct with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
System.out.println (cal);

javascript window.location in new tab

You can even use

window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk');

This will open it on the same tab if the pop-up is blocked.

How to validate domain name in PHP?

After reading all the issues with the added functions I decided I need something more accurate. Here's what I came up with that works for me.

If you need to specifically validate hostnames (they must start and end with an alphanumberic character and contain only alphanumerics and hyphens) this function should be enough.

function is_valid_domain($domain) {
    // Check for starting and ending hyphen(s)
    if(preg_match('/-./', $domain) || substr($domain, 1) == '-') {
        return false;
    }

    // Detect and convert international UTF-8 domain names to IDNA ASCII form
    if(mb_detect_encoding($domain) != "ASCII") {
        $idn_dom = idn_to_ascii($domain);
    } else {
        $idn_dom = $domain;
    }

    // Validate
    if(filter_var($idn_dom, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) != false) {
        return true;
    }
    return false;
}

Note that this function will work on most (haven't tested all languages) LTR languages. It will not work on RTL languages.

is_valid_domain('a');                                                                       Y
is_valid_domain('a.b');                                                                     Y
is_valid_domain('localhost');                                                               Y
is_valid_domain('google.com');                                                              Y
is_valid_domain('news.google.co.uk');                                                       Y
is_valid_domain('xn--fsqu00a.xn--0zwm56d');                                                 Y
is_valid_domain('area51.com');                                                              Y
is_valid_domain('japanese.??');                                                           Y
is_valid_domain('??????.??');                                                               Y
is_valid_domain('goo gle.com');                                                             N
is_valid_domain('google..com');                                                             N
is_valid_domain('google-.com');                                                             N
is_valid_domain('.google.com');                                                             N
is_valid_domain('<script');                                                                 N
is_valid_domain('alert(');                                                                  N
is_valid_domain('.');                                                                       N
is_valid_domain('..');                                                                      N
is_valid_domain(' ');                                                                       N
is_valid_domain('-');                                                                       N
is_valid_domain('');                                                                        N
is_valid_domain('-günter-.de');                                                             N
is_valid_domain('-günter.de');                                                              N
is_valid_domain('günter-.de');                                                              N
is_valid_domain('sadyasgduysgduysdgyuasdgusydgsyudgsuydgusydgsyudgsuydusdsdsdsaad.com');    N
is_valid_domain('2001:db8::7');                                                             N
is_valid_domain('876-555-4321');                                                            N
is_valid_domain('1-876-555-4321');                                                          N

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

Convert an image to grayscale

There's a static method in ToolStripRenderer class, named CreateDisabledImage. Its usage is as simple as:

Bitmap c = new Bitmap("filename");
Image d = ToolStripRenderer.CreateDisabledImage(c);

It uses a little bit different matrix than the one in the accepted answer and additionally multiplies it by a transparency of value 0.7, so the effect is slightly different than just grayscale, but if you want to just get your image grayed, it's the simplest and best solution.

How to select a radio button by default?

XHTML solution:

<input type="radio" name="imgsel" value="" checked="checked" />

Please note, that the actual value of checked attribute does not actually matter; it's just a convention to assign "checked". Most importantly, strings like "true" or "false" don't have any special meaning.

If you don't aim for XHTML conformance, you can simplify the code to:

<input type="radio" name="imgsel" value="" checked>

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

Use the .val() method.

Also I think you meant to use $("#txtEmail") as $("txtEmail") returns elements of type <txtEmail> which you probably don't have.

See here at the jQuery documentation.

Also jQuery val() method.

How can I capitalize the first letter of each word in a string?

Just because this sort of thing is fun for me, here are two more solutions.

Split into words, initial-cap each word from the split groups, and rejoin. This will change the white space separating the words into a single white space, no matter what it was.

s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)

EDIT: I don't remember what I was thinking back when I wrote the above code, but there is no need to build an explicit list; we can use a generator expression to do it in lazy fashion. So here is a better solution:

s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())

Use a regular expression to match the beginning of the string, or white space separating words, plus a single non-whitespace character; use parentheses to mark "match groups". Write a function that takes a match object, and returns the white space match group unchanged and the non-whitespace character match group in upper case. Then use re.sub() to replace the patterns. This one does not have the punctuation problems of the first solution, nor does it redo the white space like my first solution. This one produces the best result.

import re
s = 'the brown fox'

def repl_func(m):
    """process regular expression match groups for word upper-casing problem"""
    return m.group(1) + m.group(2).upper()

s = re.sub("(^|\s)(\S)", repl_func, s)


>>> re.sub("(^|\s)(\S)", repl_func, s)
"They're Bill's Friends From The UK"

I'm glad I researched this answer. I had no idea that re.sub() could take a function! You can do nontrivial processing inside re.sub() to produce the final result!

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

Benefits of EBS vs. instance-store (and vice-versa)

I'm just starting to use EC2 myself so not an expert, but Amazon's own documentation says:

we recommend that you use the local instance store for temporary data and, for data requiring a higher level of durability, we recommend using Amazon EBS volumes or backing up the data to Amazon S3.

Emphasis mine.

I do more data analysis than web hosting, so persistence doesn't matter as much to me as it might for a web site. Given the distinction made by Amazon itself, I wouldn't assume that EBS is right for everyone.

I'll try to remember to weigh in again after I've used both.

Getting or changing CSS class property with Javascript using DOM style

You don't need to add '.' in your class name. This will do

document.getElementsByClassName('col1')

Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.

Here is a working example

http://jsfiddle.net/J9LU8/

Difference between multitasking, multithreading and multiprocessing?

A multiprogramming is the process when a computer system is performing different tasks all at once in a single computer system.

How to activate virtualenv?

run this code it will get activated if you on a windows machine
source venv/Scripts/activate

enter image description here

Test if element is present using Selenium WebDriver?

To find a particular Element is present or not, we have to use findElements() method instead of findElement()..

int i=driver.findElements(By.xpath(".......")).size();
if(i=0)
System.out.println("Element is not present");
else
System.out.println("Element is present");

this is worked for me.. suggest me if i am wrong..

how to merge 200 csv files in Python

You could import csv then loop through all the CSV files reading them into a list. Then write the list back out to disk.

import csv

rows = []

for f in (file1, file2, ...):
    reader = csv.reader(open("f", "rb"))

    for row in reader:
        rows.append(row)

writer = csv.writer(open("some.csv", "wb"))
writer.writerows("\n".join(rows))

The above is not very robust as it has no error handling nor does it close any open files. This should work whether or not the the individual files have one or more rows of CSV data in them. Also I did not run this code, but it should give you an idea of what to do.

Visual Studio opens the default browser instead of Internet Explorer

Quick note if you don't have an .aspx in your project (i.e. its XBAP) but you still need to debug using IE, just add a htm page to your project and right click on that to set the default. It's hacky, but it works :P

jQuery.inArray(), how to use it right?

jQuery.inArray() returns index of the item in the array, or -1 if item was not found. Read more here: jQuery.inArray()

How to randomize (shuffle) a JavaScript array?

A recursive solution:

function shuffle(a,b){
    return a.length==0?b:function(c){
        return shuffle(a,(b||[]).concat(c));
    }(a.splice(Math.floor(Math.random()*a.length),1));
};

Change a branch name in a Git repo

Assuming you're currently on the branch you want to rename:

git branch -m newname

This is documented in the manual for git-branch, which you can view using

man git-branch

or

git help branch

Specifically, the command is

git branch (-m | -M) [<oldbranch>] <newbranch>

where the parameters are:

   <oldbranch>
       The name of an existing branch to rename.

   <newbranch>
       The new name for an existing branch. The same restrictions as for <branchname> apply.

<oldbranch> is optional, if you want to rename the current branch.

The calling thread must be STA, because many UI components require this

You can also try this

// create a thread  
Thread newWindowThread = new Thread(new ThreadStart(() =>  
{  
    // create and show the window
    FaxImageLoad obj = new FaxImageLoad(destination);  
    obj.Show();  
    
    // start the Dispatcher processing  
    System.Windows.Threading.Dispatcher.Run();  
}));  

// set the apartment state  
newWindowThread.SetApartmentState(ApartmentState.STA);  

// make the thread a background thread  
newWindowThread.IsBackground = true;  

// start the thread  
newWindowThread.Start();  

VBA Count cells in column containing specified value

one way;

var = count("find me", Range("A1:A100"))

function count(find as string, lookin as range) As Long
   dim cell As Range
   for each cell in lookin
       if (cell.Value = find) then count = count + 1 '//case sens
   next
end function

Adding and removing extensionattribute to AD object

You could try using the -Clear parameter

Example:-Clear Attribute1LDAPDisplayName, Attribute2LDAPDisplayName

http://technet.microsoft.com/en-us/library/ee617215.aspx

Javascript require() function giving ReferenceError: require is not defined

By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.

Making a DateTime field in a database automatic?

Yes, here's an example:

CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )

You can INSERT into the table without indicating the createdDate and updatedDate columns:

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)

Then create a trigger for updating the updatedDate column:

CREATE TRIGGER dbo.updateMyTable 
ON dbo.myTable
FOR UPDATE 
AS 
BEGIN 
    IF NOT UPDATE(updatedDate) 
        UPDATE dbo.myTable SET updatedDate=GETDATE() 
        WHERE col1 IN (SELECT col1 FROM inserted) 
END 
GO

SQL Server query - Selecting COUNT(*) with DISTINCT

You have to create a derived table for the distinct columns and then query the count from that table:

SELECT COUNT(*) 
FROM (SELECT DISTINCT column1,column2
      FROM  tablename  
      WHERE condition ) as dt

Here dt is a derived table.

Populate dropdown select with array using jQuery

function validateForm(){
    var success = true;
    resetErrorMessages();
    var myArray = [];
    $(".linkedServiceDonationPurpose").each(function(){
        myArray.push($(this).val())
    });

    $(".linkedServiceDonationPurpose").each(function(){
    for ( var i = 0; i < myArray.length; i = i + 1 ) {
        for ( var j = i+1; j < myArray.length; j = j + 1 )
            if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
                $(this).next( "div" ).html('Duplicate item selected');
                success=false;
           }
        } 
    });
    if (success) {
        return true;
    } else {
        return false;
    }
    function resetErrorMessages() {
        $(".error").each(function(){
            $(this).html('');
        });``
    }
}

Python division

You're putting Integers in so Python is giving you an integer back:

>>> 10 / 90
0

If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.

If you use floats on either side of the division then Python will give you the answer you expect.

>>> 10 / 90.0
0.1111111111111111

So in your case:

>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111

How to detect when cancel is clicked on file input?

So I'll throw my hat into this question since I came up with a novel solution. I have a Progressive Web App which allows users to capture photos and videos and upload them. We use WebRTC when possible, but fall back to HTML5 file pickers for devices with less support *cough Safari cough*. If you're working specifically on an Android/iOS mobile web application which uses the native camera to capture photos/videos directly, then this is the best solution I have come across.

The crux of this problem is that when the page loads, the file is null, but then when the user opens the dialog and presses "Cancel", the file is still null, hence it did not "change", so no "change" event is triggered. For desktops, this isn't too bad because most desktop UI's aren't dependent on knowing when a cancel is invoked, but mobile UI's which bring up the camera to capture a photo/video are very dependent on knowing when a cancel is pressed.

I originally used the document.body.onfocus event to detect when the user returned from the file picker, and this worked for most devices, but iOS 11.3 broke it as that event is not triggered.

Concept

My solution to this is *shudder* to measure CPU timing to determine if the page is currently in the foreground or the background. On mobile devices, processing time is given to the app currently in the foreground. When a camera is visible it will steal CPU time and deprioritize the browser. All we need to do is measure how much processing time our page is given, when camera launches our available time will drop drastically. When the camera is dismissed (either cancelled or otherwise), our available time spike back up.

Implementation

We can measure CPU timing by using setTimeout() to invoke a callback in X milliseconds, and then measure how long it took to actually invoke it. The browser will never invoke it exactly after X milliseconds, but if it is reasonable close then we must be in the foreground. If the browser is very far away (over 10x slower than requested) then we must be in the background. A basic implementation of this is like so:

function waitForCameraDismiss() {
  const REQUESTED_DELAY_MS = 25;
  const ALLOWED_MARGIN_OF_ERROR_MS = 25;
  const MAX_REASONABLE_DELAY_MS =
      REQUESTED_DELAY_MS + ALLOWED_MARGIN_OF_ERROR_MS;
  const MAX_TRIALS_TO_RECORD = 10;

  const triggerDelays = [];
  let lastTriggerTime = Date.now();

  return new Promise((resolve) => {
    const evtTimer = () => {
      // Add the time since the last run
      const now = Date.now();
      triggerDelays.push(now - lastTriggerTime);
      lastTriggerTime = now;

      // Wait until we have enough trials before interpreting them.
      if (triggerDelays.length < MAX_TRIALS_TO_RECORD) {
        window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
        return;
      }

      // Only maintain the last few event delays as trials so as not
      // to penalize a long time in the camera and to avoid exploding
      // memory.
      if (triggerDelays.length > MAX_TRIALS_TO_RECORD) {
        triggerDelays.shift();
      }

      // Compute the average of all trials. If it is outside the
      // acceptable margin of error, then the user must have the
      // camera open. If it is within the margin of error, then the
      // user must have dismissed the camera and returned to the page.
      const averageDelay =
          triggerDelays.reduce((l, r) => l + r) / triggerDelays.length
      if (averageDelay < MAX_REASONABLE_DELAY_MS) {
        // Beyond any reasonable doubt, the user has returned from the
        // camera
        resolve();
      } else {
        // Probably not returned from camera, run another trial.
        window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
      }
    };
    window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
  });
}

I tested this on recent version of iOS and Android, bringing up the native camera by setting the attributes on the <input /> element.

<input type="file" accept="image/*" capture="camera" />
<input type="file" accept="video/*" capture="camcorder" />

This works out actually a lot better than I expected. It runs 10 trials by requesting a timer to be invoked in 25 milliseconds. It then measures how long it actually took to invoke, and if the average of 10 trials is less than 50 milliseconds, we assume that we must be in the foreground and the camera is gone. If it is greater than 50 milliseconds, then we must still be in the background and should continue to wait.

Some additional details

I used setTimeout() rather than setInterval() because the latter can queue multiple invocations which execute immediately after each other. This could drastically increase the noise in our data, so I stuck with setTimeout() even though it is a little more complicated to do so.

These particular numbers worked well for me, though I have see at least once instance where the camera dismiss was detected prematurely. I believe this is because the camera may be slow to open, and the device may run 10 trials before it actually becomes backgrounded. Adding more trials or waiting some 25-50 milliseconds before starting this function may be a workaround for that.

Desktop

Unfortuantely, this doesn't really work for desktop browsers. In theory the same trick is possible as they do prioritize the current page over backgrounded pages. However many desktops have enough resources to keep the page running at full speed even when backgrounded, so this strategy doesn't really work in practice.

Alternative solutions

One alternative solution not many people mention that I did explore was mocking a FileList. We start with null in the <input /> and then if the user opens the camera and cancels they come back to null, which is not a change and no event will trigger. One solution would be to assign a dummy file to the <input /> at page start, therefore setting to null would be a change which would trigger the appropriate event.

Unfortunately, there's no way official way to create a FileList, and the <input /> element requires a FileList in particular and will not accept any other value besides null. Naturally, FileList objects cannot be directly constructed, do to some old security issue which isn't even relevant anymore apparently. The only way to get ahold of one outside of an <input /> element is to utilize a hack which copy-pastes data to fake a clipboard event which can contain a FileList object (you're basically faking a drag-and-drop-a-file-on-your-website event). This is possible in Firefox, but not for iOS Safari, so it was not viable for my particular use case.

Browsers, please...

Needless to say this is patently ridiculous. The fact that web pages are given zero notification that a critical UI element has changed is simply laughable. This is really a bug in the spec, as it was never intended for a full-screen media capture UI, and not triggering the "change" event is technically to spec.

However, can browser vendors please recognize the reality of this? This could be solved with either a new "done" event which is triggered even when no change occurs, or you could just trigger "change" anyways. Yeah, that would be against spec, but it is trivial for me to dedup a change event on the JavaScript side, yet fundamentally impossible to invent my own "done" event. Even my solution is really just heuristics, if offer no guarantees on the state of the browser.

As it stands, this API is fundamentally unusable for mobile devices, and I think a relatively simple browser change could make this infinitely easier for web developers *steps off soap box*.

Counting inversions in an array

Use mergesort, in merge step incremeant counter if the number copied to output is from right array.

Why won't my PHP app send a 404 error?

You're doing it right though it could use some refining. Looks like that's been addressed so let's talk practical application benefits:

An old website of ours that has a large collection of multilingual tech docs was executing this inside an if else conditional:

    if (<no file found>){
        die("NO FILE HERE");
    }

The problem (besides the unhelpful message and bad user experience) being that we generally use a link crawler (in our case integrity) to check out bad links and missing documents. This means that we were getting a perfectly correct 200 no error response telling us that there was a file there. Integrity didn't know that we were expecting a PDF so we had to manually add a 404 header with php. By adding your code above the die (because nothing afterwards would execute and header should always be before any rendered html anyway), integrity (which behaves more or less like a browser) would return a 404 and we would know exactly where to look for missing files. There are more elegant ways of telling the user that there is an error, but by serving a 404 error you are not only notifying browsers and browser-like programs of the error but (I believe-correct me if I'm wrong) are also recording those errors in your server logs where you can easily grep for 404s.

    header('HTTP/1.0 404 Not Found');
    die("NO FILE HERE");

writing to existing workbook using xlwt

I had the same problem. My customer ordered me Python 3.4 script that updates XLS (not XLSX) Excel files.

The 1st package xlrd was installed by "pip install" without problems in my Python home.

The 2nd one xlwt needed to say "pip install xlwt-future" to be compatible.

The 3rd one xlutils has no support for Python 3, but I adapted it a little bit and now it works at least for dummy script:

#!C:\Python343\python
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt

file_path = 'C:\Dev\Test_upd.xls'
rb = open_workbook('C:\Dev\Test.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
w_sheet.write(1, 1, 'Value')
wb.save(file_path)

I attached the file here: http://ifolder.su/43507580

Write to [email protected] if it got expired.

P.S.: Some functions are not called in the dummy example, so maybe they will need for an adaptation also. Who wants to do it, fix exceptions one-by-one with a google help. It's not a very difficult task, because the package code is small...

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

How to exit from ForEach-Object in PowerShell

Item #1. Putting a break within the foreach loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:

$todo=$project.PropertyGroup 
foreach ($thing in $todo){
    if ($thing -eq 'some_condition'){
        break
    }
}

Item #2. PowerShell lets you modify an array within a foreach loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.

$a=1,2,3
foreach ($value in $a){
  Write-Host $value
}
Write-Host $a

I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.

Linux c++ error: undefined reference to 'dlopen'

You needed to do something like this for the makefile:

LDFLAGS='-ldl'
make install

That'll pass the linker flags from make through to the linker. Doesn't matter that the makefile was autogenerated.

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

PHP substring extraction. Get the string before the first '/' or the whole string

You could create a helper function to take care of that:

/**
 * Return string before needle if it exists.
 *
 * @param string $str
 * @param mixed $needle
 * @return string
 */
function str_before($str, $needle)
{
    $pos = strpos($str, $needle);

    return ($pos !== false) ? substr($str, 0, $pos) : $str;
}

Here's a use case:

$sing = 'My name is Luka. I live on the second floor.';

echo str_before($sing, '.'); // My name is Luka

How does the "position: sticky;" property work?

The real behavior of a sticky element is:

  • First it is relative for a while
  • then it is fixed for a while
  • finally, it disappears from the view

A stickily positioned element is treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.

This value always creates a new stacking context. Note that a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn't the nearest actually scrolling ancestor.

This example will help you understand:

code https://codepen.io/darylljann/pen/PpjwPM

Filtering Pandas DataFrames on dates

How about using pyjanitor

It has cool features.

After pip install pyjanitor

import janitor

df_filtered = df.filter_date(your_date_column_name, start_date, end_date)

Where can I find Android source code online?

2020: The official AOSP code search https://cs.android.com/


You can view the source code through http://developer.android.com, when you're reading the API there will be a link to the matching source code on GitHub, you just need to add the Android SDK Reference Search Plugin on Chrome.

I blogged about it here:
http://blog.blundellapps.com/add-source-code-links-to-android-apis/

enter image description here

How to COUNT rows within EntityFramework without loading contents?

This is my code:

IQueryable<AuctionRecord> records = db.AuctionRecord;
var count = records.Count();

Make sure the variable is defined as IQueryable then when you use Count() method, EF will execute something like

select count(*) from ...

Otherwise, if the records is defined as IEnumerable, the sql generated will query the entire table and count rows returned.

git: fatal: Could not read from remote repository

I was facing same issue a while ago...

my .git/config had

url = [email protected]:manishnakar/polymer-demo.git

I replaced it with

url = https://github.com/manishnakar/polymer-demo.git 

and it works now:)

How do I convert Long to byte[] and back in java

 public static long bytesToLong(byte[] bytes) {
        if (bytes.length > 8) {
            throw new IllegalMethodParameterException("byte should not be more than 8 bytes");

        }
        long r = 0;
        for (int i = 0; i < bytes.length; i++) {
            r = r << 8;
            r += bytes[i];
        }

        return r;
    }



public static byte[] longToBytes(long l) {
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        while (l != 0) {
            bytes.add((byte) (l % (0xff + 1)));
            l = l >> 8;
        }
        byte[] bytesp = new byte[bytes.size()];
        for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) {
            bytesp[j] = bytes.get(i);
        }
        return bytesp;
    }

Convert JavaScript String to be all lower case?

Just an examples for toLowerCase(), toUpperCase() and prototype for not yet available toTitleCase() or toPropperCase()

_x000D_
_x000D_
String.prototype.toTitleCase = function() {_x000D_
  return this.split(' ').map(i => i[0].toUpperCase() + i.substring(1).toLowerCase()).join(' ');_x000D_
}_x000D_
_x000D_
String.prototype.toPropperCase = function() {_x000D_
  return this.toTitleCase();_x000D_
}_x000D_
_x000D_
var OriginalCase = 'Your Name';_x000D_
var lowercase = OriginalCase.toLowerCase();_x000D_
var upperCase = lowercase.toUpperCase();_x000D_
var titleCase = upperCase.toTitleCase();_x000D_
_x000D_
console.log('Original: ' + OriginalCase);_x000D_
console.log('toLowerCase(): ' + lowercase);_x000D_
console.log('toUpperCase(): ' + upperCase);_x000D_
console.log('toTitleCase(): ' + titleCase);
_x000D_
_x000D_
_x000D_

edited 2018

Check if table exists without using "select from"

You can do something like below:

            string strCheck = "SHOW TABLES LIKE \'tableName\'";
            cmd = new MySqlCommand(strCheck, connection);
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            cmd.Prepare();
            var reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {                             
              Console.WriteLine("Table Exist!");
            }
            else
            {                             
              Console.WriteLine("Table does not Exist!");
            }

Set cookie and get cookie with JavaScript

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

What is an NP-complete in computer science?

Honestly, Wikipedia might be the best place to look for an answer to this.

If NP = P, then we can solve very hard problems much faster than we thought we could before. If we solve only one NP-Complete problem in P (polynomial) time, then it can be applied to all other problems in the NP-Complete category.

Threading Example in Android

One of Androids powerful feature is the AsyncTask class.

To work with it, you have to first extend it and override doInBackground(...). doInBackground automatically executes on a worker thread, and you can add some listeners on the UI Thread to get notified about status update, those functions are called: onPreExecute(), onPostExecute() and onProgressUpdate()

You can find a example here.

Refer to below post for other alternatives:

Handler vs AsyncTask vs Thread

Protect image download

There is no full-proof method to prevent your images being downloaded/stolen.

But, some solutions like: watermarking your images(from client side or server side), implement a background image, disable/prevent right clicks, slice images into small pieces and then present as a complete image to browser, you can also use flash to show images.

Personally, recommended methods are: Watermarking and flash. But it is a difficult and almost impossible mission to accomplish. As long as user is able to "see" that image, means they take "screenshot" to steal the image.

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

Developing C# on Linux

This is an old question but it has a high view count, so I think some new information should be added: In the mean time a lot has changed, and you can now also use Microsoft's own .NET Core on linux. It's also available in ARM builds, 32 and 64 bit.

Error Code: 1406. Data too long for column - MySQL

This happened to me recently. I was fully migrate to MySQL 5.7, and everything is in default configuration.

All previously answers are already clear and I just want to add something.

This 1406 error could happen in your function / procedure too and not only to your table's column length.

In my case, I've trigger which call procedure with IN parameter varchar(16) but received 32 length value.

I hope this help someone with similar problem.

document.all vs. document.getElementById

document.all works in Chrome now (not sure when since), but I've been missing it the last 20 years.... Simply a shorter method name than the clunky document.getElementById. Not sure if it works in Firefox, those guys never had any desire to be compatible with the existing web, always creating new standards instead of embracing the existing web.

Installing packages in Sublime Text 2

Here is a link to a shorter and to the point description: http://www.granneman.com/webdev/editors/sublime-text/packages/how-to-install-and-use-package-control/

The steps are:

  1. Install package control.
  2. Go to http://wbond.net/sublime_packages/package_control/installation and grab the install code.
  3. In Sublime Text 2 open the console (Ctrl+`) and paste the code.
  4. Restart Sublime Text 2.
  5. Open command palette via Command+Shift+P (Mac OSX) or Ctrl+Shift+P (Windows).
  6. Start typing Package Control and choose the package you are looking for.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

git rebase fatal: Needed a single revision

You need to provide the name of a branch (or other commit identifier), not the name of a remote to git rebase.

E.g.:

git rebase origin/master

not:

git rebase origin

Note, although origin should resolve to the the ref origin/HEAD when used as an argument where a commit reference is required, it seems that not every repository gains such a reference so it may not (and in your case doesn't) work. It pays to be explicit.

Xcode Project vs. Xcode Workspace - Differences

I think there are three key items you need to understand regarding project structure: Targets, projects, and workspaces. Targets specify in detail how a product/binary (i.e., an application or library) is built. They include build settings, such as compiler and linker flags, and they define which files (source code and resources) actually belong to a product. When you build/run, you always select one specific target.

It is likely that you have a few targets that share code and resources. These different targets can be slightly different versions of an app (iPad/iPhone, different brandings,…) or test cases that naturally need to access the same source files as the app. All these related targets can be grouped in a project. While the project contains the files from all its targets, each target picks its own subset of relevant files. The same goes for build settings: You can define default project-wide settings in the project, but if one of your targets needs different settings, you can always override them there:

Shared project settings that all targets inherit, unless they overwrite it

Shared project settings that all targets inherit, unless they override it

Concrete target settings: PSE iPhone overwrites the project’s Base SDK setting

Concrete target settings: PSE iPhone overrides the project’s Base SDK setting

In Xcode, you always open projects (or workspaces, but not targets), and all the targets it contains can be built/run, but there’s no way/definition of building a project, so every project needs at least one target in order to be more than just a collection of files and settings.

Select one of the project’s targets to run

Select one of the project’s targets to run

In a lot of cases, projects are all you need. If you have a dependency that you build from source, you can embed it as a subproject. Subprojects can be opened separately or within their super project.

demoLib is a subprojec

demoLib is a subproject

If you add one of the subproject’s targets to the super project’s dependencies, the subproject will be automatically built unless it has remained unchanged. The advantage here is that you can edit files from both your project and your dependencies in the same Xcode window, and when you build/run, you can select from the project’s and its subprojects’ targets:

Running targets from a subproject

If, however, your library (the subproject) is used by a variety of other projects (or their targets, to be precise), it makes sense to put it on the same hierarchy level – that’s what workspaces are for. Workspaces contain and manage projects, and all the projects it includes directly (i.e., not their subprojects) are on the same level and their targets can depend on each other (projects’ targets can depend on subprojects’ targets, but not vice versa).

Workspace structure

Workspace structure

In this example, both apps (AnotherApplication / ProjectStructureExample) can reference the demoLib project’s targets. This would also be possible by including the demoLib project in both other projects as a subproject (which is a reference only, so no duplication necessary), but if you have lots of cross-dependencies, workspaces make more sense. If you open a workspace, you can choose from all projects’ targets when building/running.

Running targets from a workspace

You can still open your project files separately, but it is likely their targets won’t build because Xcode cannot resolve the dependencies unless you open the workspace file. Workspaces give you the same benefit as subprojects: Once a dependency changes, Xcode will rebuild it to make sure it’s up-to-date (although I have had some issues with that, it doesn’t seem to work reliably).

Your questions in a nutshell:

1) Projects contain files (code/resouces), settings, and targets that build products from those files and settings. Workspaces contain projects which can reference each other.

2) Both are responsible for structuring your overall project, but on different levels.

3) I think projects are sufficient in most cases. Don’t use workspaces unless there’s a specific reason. Plus, you can always embed your project in a workspace later.

4) I think that’s what the above text is for…

There’s one remark for 3): CocoaPods, which automatically handles 3rd party libraries for you, uses workspaces. Therefore, you have to use them, too, when you use CocoaPods (which a lot of people do).

Why does find -exec mv {} ./target/ + not work?

The manual page (or the online GNU manual) pretty much explains everything.

find -exec command {} \;

For each result, command {} is executed. All occurences of {} are replaced by the filename. ; is prefixed with a slash to prevent the shell from interpreting it.

find -exec command {} +

Each result is appended to command and executed afterwards. Taking the command length limitations into account, I guess that this command may be executed more times, with the manual page supporting me:

the total number of invocations of the command will be much less than the number of matched files.

Note this quote from the manual page:

The command line is built in much the same way that xargs builds its command lines

That's why no characters are allowed between {} and + except for whitespace. + makes find detect that the arguments should be appended to the command just like xargs.

The solution

Luckily, the GNU implementation of mv can accept the target directory as an argument, with either -t or the longer parameter --target. It's usage will be:

mv -t target file1 file2 ...

Your find command becomes:

find . -type f -iname '*.cpp' -exec mv -t ./test/ {} \+

From the manual page:

-exec command ;

Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.

-exec command {} +

This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.

How to select bottom most rows?

Logically,

BOTTOM (x) is all the records except TOP (n - x), where n is the count; x <= n

E.g. Select Bottom 1000 from Employee:

In T-SQL,

DECLARE 
@bottom int,
@count int

SET @bottom = 1000 
SET @count = (select COUNT(*) from Employee)

select * from Employee emp where emp.EmployeeID not in 
(
SELECT TOP (@count-@bottom) Employee.EmployeeID FROM Employee
)

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

I updated

implementation 'com.google.android.gms:play-services-analytics:16.0.3'

and it works for me

How do I prompt for Yes/No/Cancel input in a Linux shell script?

Use the read command:

echo Would you like to install? "(Y or N)"

read x

# now check if $x is "y"
if [ "$x" = "y" ]; then
    # do something here!
fi

and then all of the other stuff you need

Automatic exit from Bash shell script on error

One point missed in the existing answers is show how to inherit the error traps. The bash shell provides one such option for that using set

-E

If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR trap is normally not inherited in such cases.


Adam Rosenfield's answer recommendation to use set -e is right in certain cases but it has its own potential pitfalls. See GreyCat's BashFAQ - 105 - Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?

According to the manual, set -e exits

if a simple commandexits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in a if statement, part of an && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted via !".

which means, set -e does not work under the following simple cases (detailed explanations can be found on the wiki)

  1. Using the arithmetic operator let or $((..)) ( bash 4.1 onwards) to increment a variable value as

    #!/usr/bin/env bash
    set -e
    i=0
    let i++                   # or ((i++)) on bash 4.1 or later
    echo "i is $i" 
    
  2. If the offending command is not part of the last command executed via && or ||. For e.g. the below trap wouldn't fire when its expected to

    #!/usr/bin/env bash
    set -e
    test -d nosuchdir && echo no dir
    echo survived
    
  3. When used incorrectly in an if statement as, the exit code of the if statement is the exit code of the last executed command. In the example below the last executed command was echo which wouldn't fire the trap, even though the test -d failed

    #!/usr/bin/env bash
    set -e
    f() { if test -d nosuchdir; then echo no dir; fi; }
    f 
    echo survived
    
  4. When used with command-substitution, they are ignored, unless inherit_errexit is set with bash 4.4

    #!/usr/bin/env bash
    set -e
    foo=$(expr 1-1; true)
    echo survived
    
  5. when you use commands that look like assignments but aren't, such as export, declare, typeset or local. Here the function call to f will not exit as local has swept the error code that was set previously.

    set -e
    f() { local var=$(somecommand that fails); }        
    g() { local var; var=$(somecommand that fails); }
    
  6. When used in a pipeline, and the offending command is not part of the last command. For e.g. the below command would still go through. One options is to enable pipefail by returning the exit code of the first failed process:

    set -e
    somecommand that fails | cat -
    echo survived
    

The ideal recommendation is to not use set -e and implement an own version of error checking instead. More information on implementing custom error handling on one of my answers to Raise error in a Bash script

How do you use https / SSL on localhost?

This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:

install webpack-dev-server

npm i -g webpack-dev-server

start webpack-dev-server with https

webpack-dev-server --https

What should I do if the current ASP.NET session is null?

In my case ASP.NET State Service was stopped. Changing the Startup type to Automatic and starting the service manually for the first time solved the issue.

Remove the newline character in a list read from a file

You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.

with open("grades.dat") as input:
    grades = [line.split(",") for line in input.read().splitlines()]
etc...

Can I use Twitter Bootstrap and jQuery UI at the same time?

just to update this, bootstrap v2 no longer conflicts with jquery ui

https://github.com/twbs/bootstrap/issues/171

Edit: as @Freshblood there are a few things that still conflict. However, as originally posted Twitter suggests that they are working on this and it largely works, specially compared to v1.

How can I get a specific field of a csv file?

import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
  print row[1]

Volley - POST/GET parameters

This may help you...

private void loggedInToMainPage(final String emailName, final String passwordName) {

    String tag_string_req = "req_login";
    StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://localhost/index", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            try {
                JSONObject jsonObject = new JSONObject(response);
                Boolean error = jsonObject.getBoolean("error");
                if (!error) {

                    String uid = jsonObject.getString("uid");
                    JSONObject user = jsonObject.getJSONObject("user");
                    String email = user.getString("email");
                    String password = user.getString("password");


                    session.setLogin(true);
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                    Toast.makeText(getApplicationContext(), "its ok", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            System.out.println("volley Error .................");
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "login");
            params.put("email", emailName);
            params.put("password", passwordName);
            return params;
        }
    };


    MyApplication.getInstance().addToRequestQueue(stringRequest,tag_string_req);
}

Can I create view with parameter in MySQL?

Actually if you create func:

create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;

and view:

create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;

Then you can call a view with a parameter:

select s.* from (select @p1:=12 p) parm , h_parm s;

I hope it helps.

JPA and Hibernate - Criteria vs. JPQL or HQL

Criteria API

Criteria API is better suited for dynamically generated queries. So, if you want to add WHERE clause filters, JOIN clauses, or vary the ORDER BY clause or the projection columns, then the Criteria API can help you generate the query dynamically in a way that also prevents SQL Injection attacks.

On the other hand, Criteria queries are less expressive and can even lead to very complicated and inefficient SQL queries.

JPQL and HQL

JPQL is the JPA standard entity query language while HQL extends JPQL and adds some Hibernate-specific features.

JPQL and HQL are very expressive and resemble SQL. Unlike Criteria API, JPQL and HQL make it easy to predict the underlying SQL query that's generated by the JPA provider. It's also much easier to review one's HQL queries than Criteria ones.

It's worth noting that selecting entities with JPQL or Criteria API makes sense if you need to modify them. Otherwise, a DTO projection is a much better choice.

Conclusion

If you don't need to vary the entity query structure, then use JPQL or HQL. If you need to change the filtering or sorting criteria or change the projection, then use Criteria API.

However, just because you are using JPA or Hibernate, it doesn't mean you should not use native SQL. SQL queries are very useful and JPQL and Criteria API are not a replacement for SQL.

Column calculated from another column?

@krtek's answer is in the right direction, but has a couple of issues.

The bad news is that using UPDATE in a trigger on the same table won't work. The good news is that it's not necessary; there is a NEW object that you can operate on before the table is even touched.

The trigger becomes:

CREATE TRIGGER halfcolumn_update BEFORE UPDATE ON my_table
  FOR EACH ROW BEGIN
    SET NEW.calculated = NEW.value/2;
  END;

Note also that the BEGIN...END; syntax has to be parsed with a different delimiter in effect. The whole shebang becomes:

DELIMITER |

CREATE TRIGGER halfcolumn_insert BEFORE INSERT ON my_table
  FOR EACH ROW BEGIN
    SET NEW.calculated = NEW.value/2;
  END;
|

CREATE TRIGGER halfcolumn_update BEFORE UPDATE ON my_table
  FOR EACH ROW BEGIN
    SET NEW.calculated = NEW.value/2;
  END;
|

DELIMITER ;

What is special about /dev/tty?

/dev/tty is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c in the ls -l output means.

man 4 tty or man -s 4 tty should give you more information, or you can read the man page online here.

Incidentally, pwd > /dev/tty doesn't necessarily print to the shell's stdout (though it is the pwd command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty still refers to the terminal.

You can also read from /dev/tty, which will normally read from the keyboard.

How can I add "href" attribute to a link dynamically using JavaScript?

First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.

Then, add something like this in the javascript function that you're calling:

var abc = 'somelink';
document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';

This way the link will look like this:

<a href="somelink">Link</a>

The controller for path was not found or does not implement IController

In my case, I was rendering another action method for my menu section in _layout.cshtml file using @Html.Action("Menu", "Menu") whereas I forgot to create Menu controller and as layout file was being used in my current controller action's view therefore I was getting this error in my current action render request. try to look in your layout and as well as view file if you did the same mistake

Is it possible to have a multi-line comments in R?

You can, if you want, use standalone strings for multi-line comments — I've always thought that prettier than if (FALSE) { } blocks. The string will get evaluated and then discarded, so as long as it's not the last line in a function nothing will happen.

"This function takes a value x, and does things and returns things that
 take several lines to explain"
doEverythingOften <- function(x) {
     # Non! Comment it out! We'll just do it once for now.
     "if (x %in% 1:9) {
          doTenEverythings()
     }"
     doEverythingOnce()
     ...
     return(list(
         everythingDone = TRUE, 
         howOftenDone = 1
     ))
}

The main limitation is that when you're commenting stuff out, you've got to watch your quotation marks: if you've got one kind inside, you'll have to use the other kind for the comment; and if you've got something like "strings with 'postrophes" inside that block, then there's no way this method is a good idea. But then there's still the if (FALSE) block.

The other limitation, one that both methods have, is that you can only use such blocks in places where an expression would be syntactically valid - no commenting out parts of lists, say.

Regarding what do in which IDE: I'm a Vim user, and I find NERD Commenter an utterly excellent tool for quickly commenting or uncommenting multiple lines. Very user-friendly, very well-documented.

Lastly, at the R prompt (at least under Linux), there's the lovely Alt-Shift-# to comment the current line. Very nice to put a line 'on hold', if you're working on a one-liner and then realise you need a prep step first.

How to do a regular expression replace in MySQL?

My brute force method to get this to work was just:

  1. Dump the table - mysqldump -u user -p database table > dump.sql
  2. Find and replace a couple patterns - find /path/to/dump.sql -type f -exec sed -i 's/old_string/new_string/g' {} \;, There are obviously other perl regeular expressions you could perform on the file as well.
  3. Import the table - mysqlimport -u user -p database table < dump.sql

If you want to make sure the string isn't elsewhere in your dataset, run a few regular expressions to make sure they all occur in a similar environment. It's also not that tough to create a backup before you run a replace, in case you accidentally destroy something that loses depth of information.

Response.Redirect to new window

You can also use in code behind like this way

ClientScript.RegisterStartupScript(this.Page.GetType(), "",
  "window.open('page.aspx','Graph','height=400,width=500');", true);

writing to serial port from linux command line

If you want to use hex codes, you should add -e option to enable interpretation of backslash escapes by echo (but the result is the same as with echoCtrlRCtrlB). And as wallyk said, you probably want to add -n to prevent the output of a newline:

echo -en '\x12\x02' > /dev/ttyS0

Also make sure that /dev/ttyS0 is the port you want.

How to squash all git commits into one?

This worked best for me.

git rebase -X ours -i master

This will git will prefer your feature branch to master; avoiding the arduous merge edits. Your branch needs to be up to date with master.

ours
           This resolves any number of heads, but the resulting tree of the merge is always that of the current
           branch head, effectively ignoring all changes from all other branches. It is meant to be used to
           supersede old development history of side branches. Note that this is different from the -Xours
           option to the recursive merge strategy.

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

Getting the last argument passed to a shell script

There is a much more concise way to do this. Arguments to a bash script can be brought into an array, which makes dealing with the elements much simpler. The script below will always print the last argument passed to a script.

  argArray=( "$@" )                        # Add all script arguments to argArray
  arrayLength=${#argArray[@]}              # Get the length of the array
  lastArg=$((arrayLength - 1))             # Arrays are zero based, so last arg is -1
  echo ${argArray[$lastArg]}

Sample output

$ ./lastarg.sh 1 2 buckle my shoe
shoe

Escape double quotes in a string

One solution, is to add support to the csharp language so that "" isn't the only scheme used for strings.

For another string terminator to the C# language - I'm a fan of backtick in ES6.

string test = `He said to me, "Hello World". How are you?`;

But also, the doubling idea in Markdown might be better:

string test = ""He said to me, "Hello World". How are you?"";

The code does not work at the date of this post. This post is a solution where the visitors to this Q&A jump onto this csharplank ticket for C# and upvote it - https://github.com/dotnet/csharplang/discussions/3917

Sorting list based on values from another list

Shortest Code

[x for _,x in sorted(zip(Y,X))]

Example:

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Z = [x for _,x in sorted(zip(Y,X))]
print(Z)  # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]

Generally Speaking

[x for _, x in sorted(zip(Y,X), key=lambda pair: pair[0])]

Explained:

  1. zip the two lists.
  2. create a new, sorted list based on the zip using sorted().
  3. using a list comprehension extract the first elements of each pair from the sorted, zipped list.

For more information on how to set\use the key parameter as well as the sorted function in general, take a look at this.


How to dismiss notification after action has been clicked

You can always cancel() the Notification from whatever is being invoked by the action (e.g., in onCreate() of the activity tied to the PendingIntent you supply to addAction()).

SQL query to get most recent row for each instance of a given key

Can't post comments yet, but @Cristi S's answer works a treat for me.

In my scenario, I needed to keep only the most recent 3 records in Lowest_Offers for all product_ids.

Need to rework his SQL to delete - thought that this would be ok, but syntax is wrong.

DELETE from (
SELECT product_id, id, date_checked,
  ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY date_checked DESC) rn
FROM lowest_offers
) tmp WHERE > 3;

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Commenting here as this seems to be the most popular answer on the subject for searching for files whilst excluding certain directories in powershell.

To avoid issues with post filtering of results (i.e. avoiding permission issues etc), I only needed to filter out top level directories and that is all this example is based on, so whilst this example doesn't filter child directory names, it could very easily be made recursive to support this, if you were so inclined.

Quick breakdown of how the snippet works

$folders << Uses Get-Childitem to query the file system and perform folder exclusion

$file << The pattern of the file I am looking for

foreach << Iterates the $folders variable performing a recursive search using the Get-Childitem command

$folders = Get-ChildItem -Path C:\ -Directory -Name -Exclude Folder1,"Folder 2"
$file = "*filenametosearchfor*.extension"

foreach ($folder in $folders) {
   Get-Childitem -Path "C:/$folder" -Recurse -Filter $file | ForEach-Object { Write-Output $_.FullName }
}

How to add elements of a string array to a string array list?

public class duplicateArrayList {


    ArrayList al = new ArrayList();
    public duplicateArrayList(Object[] obj) {

        for (int i = 0; i < obj.length; i++) {

            al.add(obj[i]);
        }

        Iterator iter = al.iterator();
        while(iter.hasNext()){

            System.out.print(" "+iter.next());
        }
    }

    public static void main(String[] args) {


    String[] str = {"A","B","C","D"};

    duplicateArrayList dd = new duplicateArrayList(str);

    }

}

Parsing HTML using Python

I recommend lxml for parsing HTML. See "Parsing HTML" (on the lxml site).

In my experience Beautiful Soup messes up on some complex HTML. I believe that is because Beautiful Soup is not a parser, rather a very good string analyzer.

moving changed files to another branch for check-in

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally - changes to files are not tied to a particular branch until you commit them.

If you have already committed your changes:

  1. Type git log and remember the SHA of the commit you want to move.
  2. Check out the branch you want to move the commit to.
  3. Type git cherry-pick SHA substituting the SHA from above.
  4. Switch back to your original branch.
  5. Use git reset HEAD~1 to reset back before your wrong-branch commit.

cherry-pick takes a given commit and applies it to the currently checked-out head, thus allowing you to copy the commit over to a new branch.

Why can't I declare static methods in an interface?

It seems the static method in the interface might be supported in Java 8, well, my solution is just define them in the inner class.

interface Foo {
    // ...
    class fn {
        public static void func1(...) {
            // ...
        }
    }
}

The same technique can also be used in annotations:

public @interface Foo {
    String value();

    class fn {
        public static String getValue(Object obj) {
            Foo foo = obj.getClass().getAnnotation(Foo.class);
            return foo == null ? null : foo.value();
        }
    }
}

The inner class should always be accessed in the form of Interface.fn... instead of Class.fn..., then, you can get rid of ambiguous problem.

Exception.Message vs Exception.ToString()

Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

Query to get the names of all tables in SQL Server 2008 Database

Try this:

SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

it will display the schema+table name for all tables in the current database.

Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:

SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
       ,@SQL   nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''

INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1

set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.

Embedding Windows Media Player for all browsers

Use the following. It works in Firefox and Internet Explorer.

        <object id="MediaPlayer1" width="690" height="500" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
            codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
            standby="Loading Microsoft® Windows® Media Player components..." type="application/x-oleobject"
            >
            <param name="FileName" value='<%= GetSource() %>' />
            <param name="AutoStart" value="True" />
            <param name="DefaultFrame" value="mainFrame" />
            <param name="ShowStatusBar" value="0" />
            <param name="ShowPositionControls" value="0" />
            <param name="showcontrols" value="0" />
            <param name="ShowAudioControls" value="0" />
            <param name="ShowTracker" value="0" />
            <param name="EnablePositionControls" value="0" />


            <!-- BEGIN PLUG-IN HTML FOR FIREFOX-->
            <embed  type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"
                src='<%= GetSource() %>' align="middle" width="600" height="500" defaultframe="rightFrame"
                 id="MediaPlayer2" />

And in JavaScript,

    function playVideo() {
        try{
                if(-1 != navigator.userAgent.indexOf("MSIE"))
                {
                        var obj = document.getElementById("MediaPlayer1");
                            obj.Play();

                }
                else
                {
                            var player = document.getElementById("MediaPlayer2");
                            player.controls.play();

                }
             }  
        catch(error) {
            alert(error)
        } 


        }

When to choose mouseover() and hover() function?

You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.

In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.

Append text to input field

_x000D_
_x000D_
 // Define appendVal by extending JQuery_x000D_
 $.fn.appendVal = function( TextToAppend ) {_x000D_
  return $(this).val(_x000D_
   $(this).val() + TextToAppend_x000D_
  );_x000D_
 };_x000D_
//______________________________________________x000D_
_x000D_
 // And that's how to use it:_x000D_
 $('#SomeID')_x000D_
  .appendVal( 'This text was just added' )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<textarea _x000D_
          id    =  "SomeID"_x000D_
          value =  "ValueText"_x000D_
          type  =  "text"_x000D_
>Current NodeText_x000D_
</textarea>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

Well when creating this example I somehow got a little confused. "ValueText" vs >Current NodeText< Isn't .val() supposed to run on the data of the value attribute? Anyway I and you me may clear up this sooner or later.

However the point for now is:

When working with form data use .val().

When dealing with the mostly read only data in between the tag use .text() or .append() to append text.

How do I append a node to an existing XML file in java

If you need to insert node/element in some specific place , you can to do next steps

  1. Divide original xml into two parts
  2. Append your new node/element as child to first first(the first part should ended with element after wich you wanna add your element )
  3. Append second part to the new document.

It is simple algorithm but should works...

How to access site through IP address when website is on a shared host?

serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.

As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.

67.225.235.59 somerandomservice.com www.somerandomservice.com

RequiredIf Conditional Validation Attribute

The main difference from other solutions here is that this one reuses logic in RequiredAttribute on the server side, and uses required's validation method depends property on the client side:

public class RequiredIf : RequiredAttribute, IClientValidatable
{
    public string OtherProperty { get; private set; }
    public object OtherPropertyValue { get; private set; }

    public RequiredIf(string otherProperty, object otherPropertyValue)
    {
        OtherProperty = otherProperty;
        OtherPropertyValue = otherPropertyValue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
        if (otherPropertyInfo == null)
        {
            return new ValidationResult($"Unknown property {OtherProperty}");
        }

        object otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
        if (Equals(OtherPropertyValue, otherValue)) // if other property has the configured value
            return base.IsValid(value, validationContext);

        return null;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "requiredif"; // data-val-requiredif
        rule.ValidationParameters.Add("other", OtherProperty); // data-val-requiredif-other
        rule.ValidationParameters.Add("otherval", OtherPropertyValue); // data-val-requiredif-otherval

        yield return rule;
    }
}

$.validator.unobtrusive.adapters.add("requiredif", ["other", "otherval"], function (options) {
    var value = {
        depends: function () {
            var element = $(options.form).find(":input[name='" + options.params.other + "']")[0];
            return element && $(element).val() == options.params.otherval;
        }
    }
    options.rules["required"] = value;
    options.messages["required"] = options.message;
});

Converting an object to a string

I had need to make a more configurable version of JSON.stringify as I had to add comments and know the JSON path:

_x000D_
_x000D_
const someObj = {_x000D_
  a: {_x000D_
    nested: {_x000D_
      value: 'apple',_x000D_
    },_x000D_
    sibling: 'peanut'_x000D_
  },_x000D_
  b: {_x000D_
    languages: ['en', 'de', 'fr'],_x000D_
    c: {_x000D_
      nice: 'heh'_x000D_
    }_x000D_
  },_x000D_
  c: 'butter',_x000D_
  d: function () {}_x000D_
};_x000D_
_x000D_
function* objIter(obj, indent = '  ', depth = 0, path = '') {_x000D_
  const t = indent.repeat(depth);_x000D_
  const t1 = indent.repeat(depth + 1);_x000D_
  const v = v => JSON.stringify(v);_x000D_
  yield { type: Array.isArray(obj) ? 'OPEN_ARR' : 'OPEN_OBJ', indent, depth };_x000D_
  const keys = Object.keys(obj);_x000D_
  _x000D_
  for (let i = 0, l = keys.length; i < l; i++) {_x000D_
    const key = keys[i];_x000D_
    const prop = obj[key];_x000D_
    const nextPath = !path && key || `${path}.${key}`;_x000D_
 _x000D_
    if (typeof prop !== 'object') {_x000D_
      yield { type:  isNaN(key) ? 'VAL' : 'ARR_VAL', key, prop, indent, depth, path: nextPath };_x000D_
    } else {_x000D_
      yield { type: 'OBJ_KEY', key, indent, depth, path: nextPath };_x000D_
      yield* objIter(prop, indent, depth + 1, nextPath);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  yield { type: Array.isArray(obj) ? 'CLOSE_ARR' : 'CLOSE_OBJ', indent, depth };_x000D_
}_x000D_
_x000D_
const iterMap = (it, mapFn) => {_x000D_
  const arr = [];_x000D_
  for (const x of it) { arr.push(mapFn(x)) }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
const objToStr = obj => iterMap(objIter(obj), ({ type, key, prop, indent, depth, path }) => {_x000D_
  const t = indent.repeat(depth);_x000D_
  const t1 = indent.repeat(depth + 1);_x000D_
  const v = v => JSON.stringify(v);_x000D_
_x000D_
  switch (type) {_x000D_
    case 'OPEN_ARR':_x000D_
      return '[\n';_x000D_
    case 'OPEN_OBJ':_x000D_
      return '{\n';_x000D_
    case 'VAL':_x000D_
      return `${t1}// ${path}\n${t1}${v(key)}: ${v(prop)},\n`;_x000D_
    case 'ARR_VAL':_x000D_
      return `${t1}// ${path}\n${t1}${v(prop)},\n`;_x000D_
    case 'OBJ_KEY':_x000D_
      return `${t1}// ${path}\n${t1}${v(key)}: `;_x000D_
    case 'CLOSE_ARR':_x000D_
    case 'CLOSE_OBJ':_x000D_
      return `${t}${type === 'CLOSE_ARR' ? ']' : '}'}${depth ? ',' : ';'}\n`;_x000D_
    default:_x000D_
      throw new Error('Unknown type:', type);_x000D_
  }_x000D_
}).join('');_x000D_
_x000D_
const s = objToStr(someObj);_x000D_
console.log(s);
_x000D_
_x000D_
_x000D_

Maven Could not resolve dependencies, artifacts could not be resolved

I had this problem as well, it turned out it was because of NetBeans adding something to my pom.xml file. Double check nothing was added since previous successful deployments.

How do I search a Perl array for a matching string?

Perl string match can also be used for a simple yes/no.

my @foo=("hello", "world", "foo", "bar");

if ("@foo" =~ /\bhello\b/){
    print "found";
}
else{
    print "not found";
}

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

Counting the number of occurences of characters in a string

You should be able to utilize the StringUtils class and the countMatches() method.

public static int countMatches(String str, String sub)

Counts how many times the substring appears in the larger String.

Try the following:

int count = StringUtils.countMatches("a.b.c.d", ".");

jQuery change event on dropdown

Or you can use this javascript

$(function () {
    $("#projectKey").change(function () {
        alert($('#projectKey option:selected').text());
    });
});

How do I make bootstrap table rows clickable?

May be you are trying to attach a function when table rows are clicked.

var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
    rows[i].onclick = functioname(); //call the function like this
}

How do I tell CMake to link in a static library in the source directory?

I found this helpful...

http://www.cmake.org/pipermail/cmake/2011-June/045222.html

From their example:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

Prevent flex items from overflowing a container

Instead of flex: 1 0 auto just use flex: 1

_x000D_
_x000D_
main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
}_x000D_
main {_x000D_
  display: flex;_x000D_
}_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
  flex: 1;_x000D_
}
_x000D_
<main>_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

How to Scroll Down - JQuery

If you want to scroll down to the div (id="div1"). Then you can use this code.

 $('html, body').animate({
     scrollTop: $("#div1").offset().top
 }, 1500);

How to make a machine trust a self-signed Java application

SERIOUS DISCLAIMER

This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.


OK, I had to go to the customer premises and found a solution. I:

  • Exported the keystore that holds the signing keys in PKCS #12 format
  • Opened control panel Java -> Security tab
  • Clicked Manage certificates
  • Imported this new keystore as a secure site CA

Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!

How get an apostrophe in a string in javascript

You can try the following:

theAnchorText = "I'm home";

OR

theAnchorText = 'I\'m home';

iPhone App Icons - Exact Radius?

After trying some of the answers in this post, I consulted with Louie Mantia (former Apple, Square, and Iconfactory designer) and all the answers so far on this post are wrong (or at least incomplete). Apple starts with the 57px icon and a radius of 10 then scales up or down from there. Thus you can calculate the radius for any icon size using 10/57 x new size (for example 10/57 x 114 gives 20, which is the proper radius for a 114px icon). Here is a list of the most commonly used icons, proper naming conventions, pixel dimensions, and corner radii.

  1. Icon1024.png - 1024px - 179.649
  2. Icon512.png - 512px - 89.825
  3. Icon.png - 57px - 10
  4. [email protected] - 114px - 20
  5. Icon-72.png - 72px - 12.632
  6. [email protected] - 144px - 25.263
  7. Icon-Small.png - 29px - 5.088
  8. [email protected] - 58px - 10.175

Also, as mentioned in other answers, you don't actually want to crop any of the images you use in the binary or submit to Apple. Those should all be square and not have any transparency. Apple will automatically mask each icon in the appropriate context.

Knowing the above is important, however, for icon usage within app UI where you have to apply the mask in code, or pre-rendered in photoshop. It's also helpful when creating artwork for websites and other promotional material.

Additional reading:

Neven Mrgan on additional icon sizes and other design considerations: ios app icon sizes

Bjango's Marc Edwards on the different options for creating roundrects in Photoshop and why it matters: roundrect

Apple's official docs on icon size and design considerations: Icons and Images

Update:

I did some tests in Photoshop CS6 and it seems as though 3 digits after the decimal point is enough precision to end up with the exact same vector (at least as displayed by Photoshop at 3200% zoom). The Round Rect Tool sometimes rounds the input to the nearest whole number, but you can see a significant difference between 90 and 89.825. And several times the Round Rectangle Tool didn't round up and actually showed multiple digits after the decimal point. Not sure what's going on there, but it's definitely using and storing the more precise number that was entered.

Anyhow, I've updated the list above to include just 3 digits after the decimal point (before there were 13!). In most situations it would probably be hard to tell the difference between a transparent 512px icon masked at a 90px radius and one masked at 89.825, but the antialiasing of the rounded corner would definitely end up slightly different and would likely be visible in certain circumstances especially if a second, more precise mask is applied by Apple, in code, or otherwise.

Alter table to modify default value of column

ALTER TABLE {TABLE NAME}
ALTER COLUMN {COLUMN NAME} SET DEFAULT '{DEFAULT VALUES}'

example :

ALTER TABLE RESULT
ALTER COLUMN STATUS SET DEFAULT 'FAIL'

pandas dataframe columns scaling with sklearn

Like this?

dfTest = pd.DataFrame({
           'A':[14.00,90.20,90.95,96.27,91.21],
           'B':[103.02,107.26,110.35,114.23,114.68], 
           'C':['big','small','big','small','small']
         })
dfTest[['A','B']] = dfTest[['A','B']].apply(
                           lambda x: MinMaxScaler().fit_transform(x))
dfTest

    A           B           C
0   0.000000    0.000000    big
1   0.926219    0.363636    small
2   0.935335    0.628645    big
3   1.000000    0.961407    small
4   0.938495    1.000000    small

How to "crop" a rectangular image into a square with CSS?

Use CSS: overflow:

.thumb {
   width:230px;
   height:230px;
   overflow:hidden
}

Vue.js getting an element within a component

Vue 2.x

For Official information:

https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced

A simple Example:

On any Element you have to add an attribute ref with a unique value

<input ref="foo" type="text" >

To target that elemet use this.$refs.foo

this.$refs.foo.focus(); // it will focus the input having ref="foo"

What does <value optimized out> mean in gdb?

Just run "export COPTS='-g -O0';" and rebuild your code. After rebuild, debug it using gdb. You'll not see such error. Thanks.

What are the various "Build action" settings in Visual Studio project properties and what do they do?

How about this page from Microsoft Connect (explaining the DesignData and DesignDataWithDesignTimeCreatableTypes) types. Quoting:

The following describes the two Build Actions for Sample Data files.

Sample data .xaml files must be assigned one of the below Build Actions:

DesignData: Sample data types will be created as faux types. Use this Build Action when the sample data types are not creatable or have read-only properties that you want to defined sample data values for.

DesignDataWithDesignTimeCreatableTypes: Sample data types will be created using the types defined in the sample data file. Use this Build Action when the sample data types are creatable using their default empty constructor.

Not so incredibly exhaustive, but it at least gives a hint. This MSDN walkthrough also gives some ideas. I don't know whether these Build Actions are applicable for non-Silverlight projects also.

How can I print variable and string on same line in Python?

Just use , (comma) in between.

See this code for better understanding:

# Weight converter pounds to kg

weight_lbs = input("Enter your weight in pounds: ")

weight_kg = 0.45 * int(weight_lbs)

print("You are ", weight_kg, " kg")

Docker container will automatically stop after "docker run -d"

Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.

So if your docker entry script is a background process like following:

/usr/local/bin/confd -interval=30 -backend etcd -node $CONFIG_CENTER &

The '&' makes the container stop and exit if there are no other foreground process triggered later. So the solution is just remove the '&' or have another foreground CMD running after it, such as

tail -f server.log

Keytool is not recognized as an internal or external command

Run the cmd as run as administrator this worked for me

What is the use of a cursor in SQL Server?

Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.

However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ..., they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.

In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.

When should you use 'friend' in C++?

The creator of C++ says that isn't broking any encapsulation principle, and I will quote him:

Does "friend" violate encapsulation? No. It does not. "Friend" is an explicit mechanism for granting access, just like membership. You cannot (in a standard conforming program) grant yourself access to a class without modifying its source.

Is more than clear...

Finding local IP addresses using Python's stdlib

This is very similar to previously posted answers, but I could not find any with this usage of calls. This is what I use for ipv4. For ipv6 change the '.' in to ':' in

import socket
print next(i[4][0] for i in socket.getaddrinfo(
    socket.gethostname(), 80) if '127.' not in i[4][0] and '.' in i[4][0]);"

How to check if user input is not an int value

Maybe you can try this:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}

How to get the total number of rows of a GROUP BY query?

It's a little memory-inefficient but if you're using the data anyway, I use this frequently:

$rows = $q->fetchAll();
$num_rows = count($rows);

How can I split a delimited string into an array in PHP?

What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:

part1,"part2,with a comma and a quote "" in it",part3

PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of explode:

print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
    [0] => part1
    [1] => part2,with a comma and a quote " in it
    [2] => part3
)

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

You can also specify your own hash on the redirect_uri parameter for the Facebook callback, which might be helpful in certain circumstances e.g. /api/account/callback#home. When you are redirected back, it'll at least be a hash that corresponds to a known route if you are using backbone.js or similar (not sure about jquery mobile).

Error: Could not find or load main class in intelliJ IDE

I ran into this problem when my Java class was under src/main/kotlin. After I moved it to src/main/java, the problem was gone.

<img>: Unsafe value used in a resource URL context

It is possible to set image as background image to avoid unsafe url error:

<div [style.backgroundImage]="'url(' + imageUrl + ')'" class="show-image"></div>

CSS:

.show-image {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-size: cover;        
}

clear form values after submission ajax

use this:

$('form.contactForm input[type="text"],texatrea, select').val('');

or if you have a reference to the form with this:

$('input[type="text"],texatrea, select', this).val('');

:input === <input> + <select>s + <textarea>s

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

Node.js getaddrinfo ENOTFOUND

My problem was we were parsing url and generating http_options for http.request();

I was using request_url.host which already had port number with domain name so had to use request_url.hostname.

var request_url = new URL('http://example.org:4444/path');
var http_options = {};

http_options['hostname'] = request_url.hostname;//We were using request_url.host which includes port number
http_options['port'] = request_url.port;
http_options['path'] = request_url.pathname;
http_options['method'] = 'POST';
http_options['timeout'] = 3000;
http_options['rejectUnauthorized'] = false;

Descending order by date filter in AngularJs

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.filter("toArray", function () {_x000D_
    return function (obj) {_x000D_
        var result = [];_x000D_
        angular.forEach(obj, function (val, key) {_x000D_
            result.push(val);_x000D_
        });_x000D_
        return result;_x000D_
    };_x000D_
});_x000D_
_x000D_
_x000D_
myApp.controller("mainCtrl", function ($scope) {_x000D_
_x000D_
  $scope.logData = [_x000D_
              { event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },_x000D_
              { event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },_x000D_
              { event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }_x000D_
          ]; _x000D_
        _x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="mainCtrl">_x000D_
_x000D_
  <h4>Descending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
  <br>_x000D_
  _x000D_
  _x000D_
  <h4>Ascending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Mean of a column in a data frame, given the column's name

Any of the following should work!!

df <- data.frame(x=1:3,y=4:6)

mean(df$x)
mean(df[,1])
mean(df[["x"]])

I need to convert an int variable to double

Either use casting as others have already said, or multiply one of the int variables by 1.0:

double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));

How do I round a double to two decimal places in Java?

You can try this one:

public static String getRoundedValue(Double value, String format) {
    DecimalFormat df;
    if(format == null)
        df = new DecimalFormat("#.00");
    else 
        df = new DecimalFormat(format);
    return df.format(value);
}

or

public static double roundDoubleValue(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

CodeIgniter - accessing $config variable in view

This is how I did it. In config.php

$config['HTML_TITLE'] = "SO TITLE test";

In applications/view/header.php (assuming html code)

<title><?=$this->config->item("HTML_TITLE");?> </title>

Example of Title

Display rows with one or more NaN values in pandas dataframe

You can use DataFrame.any with parameter axis=1 for check at least one True in row by DataFrame.isna with boolean indexing:

df1 = df[df.isna().any(axis=1)]

d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')

print (df)
                             alpha1  alpha2    gamma1    gamma2       chi2min
filename                                                                     
M66_MI_NSRh35d32kpoints.dat  0.8016  0.9283  1.000000  0.074804  3.985599e+01
F71_sMI_DMRI51d.dat          0.0000  0.0000       NaN  0.000000  1.000000e+25
F62_sMI_St22d7.dat           1.7210  3.8330  0.237480  0.150000  1.091832e+01
F41_Car_HOC498d.dat          1.1670  2.8090  0.364190  0.300000  7.966335e+00
F78_MI_547d.dat              1.8970  5.4590  0.095319       NaN  2.593468e+01

Explanation:

print (df.isna())
                            alpha1 alpha2 gamma1 gamma2 chi2min
filename                                                       
M66_MI_NSRh35d32kpoints.dat  False  False  False  False   False
F71_sMI_DMRI51d.dat          False  False   True  False   False
F62_sMI_St22d7.dat           False  False  False  False   False
F41_Car_HOC498d.dat          False  False  False  False   False
F78_MI_547d.dat              False  False  False   True   False

print (df.isna().any(axis=1))
filename
M66_MI_NSRh35d32kpoints.dat    False
F71_sMI_DMRI51d.dat             True
F62_sMI_St22d7.dat             False
F41_Car_HOC498d.dat            False
F78_MI_547d.dat                 True
dtype: bool

df1 = df[df.isna().any(axis=1)]
print (df1)
                     alpha1  alpha2    gamma1  gamma2       chi2min
filename                                                           
F71_sMI_DMRI51d.dat   0.000   0.000       NaN     0.0  1.000000e+25
F78_MI_547d.dat       1.897   5.459  0.095319     NaN  2.593468e+01

Best way to update an element in a generic List

You could do:

var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));

This will return the matching dog, else it will return null.

You can then set the property like follows:

if (matchingDog != null)
    matchingDog.Name = "New Dog Name";

Send JSON via POST in C# and Receive the JSON returned?

I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.

(Edit: Adding JSON from question for clarity)

{
  "agent": {                             
    "name": "Agent Name",                
    "version": 1                                                          
  },
  "username": "Username",                                   
  "password": "User Password",
  "token": "xxxxxx"
}

With two classes representing the JSON-Structure you posted that may look like this:

public class Credentials
{
    [JsonProperty("agent")]
    public Agent Agent { get; set; }

    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }
}

public class Agent
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("version")]
    public int Version { get; set; }
}

you could have a method like this, which would do your POST request:

var payload = new Credentials { 
    Agent = new Agent { 
        Name = "Agent Name",
        Version = 1 
    },
    Username = "Username",
    Password = "User Password",
    Token = "xxxxx"
};

// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

using (var httpClient = new HttpClient()) {

    // Do the actual request and await the response
    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);

    // If the response contains content we want to read it!
    if (httpResponse.Content != null) {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();

        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
    }
}

How to allow only one radio button to be checked?

All radio buttons have to have the same name:

<input type='radio' name='foo'>

Only 1 radio button of each group of buttons with the same name can be checked.

Calling UserForm_Initialize() in a Module

IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.

This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.

Example:

Standard module code:

Option Explicit

Public Sub Main()
  Dim myUserForm As UserForm1

  Set myUserForm = New UserForm1
  myUserForm.Show

End Sub

User form code:

Option Explicit

Private m_initializationDate As Date

Private Sub UserForm_Initialize()
  m_initializationDate = VBA.DateTime.Date
  MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

This ORA error is occurred because of violation of unique constraint.

ORA-00001: unique constraint (constraint_name) violated

This is caused because of trying to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

You can resolve this either by

  • changing the constraint to allow duplicates, or
  • drop the unique constraint or you can change your SQL to avoid duplicate inserts

error: Error parsing XML: not well-formed (invalid token) ...?

Problem is that you are doing something wrong in XML layout file

android:text=" <- Go Back" // this creates error
android:text="Go Back" // correct way