Programs & Examples On #Database replication

Database replication is used to ensure consistency between redundant databases and to improve reliability and increase fault-tolerance. The replication process commonly involves continuously duplicating a "master" database to one or more additional "slave" databases.

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

Following up on David's answer...

Using SHOW SLAVE STATUS\G will give human-readable output.

Spring Data JPA - "No Property Found for Type" Exception

Another scenario, that was not yet mentioned here, that caused this error is an API that receives Pageable (or Sort) and passes it, as is, to the JPA repository when calling the API from Swagger.

Swagger default value for the Pageable parameter is this:

  {
    "page": 0,
    "size": 0,
    "sort": [
      "string"
    ]
  }

Notice the "string" there which is a property that does exist. Running the API without deleting or changing it will cause org.springframework.data.mapping.PropertyReferenceException: No property string found for type ...

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Set your editor to point to this program:

/Applications/TextEdit.app/Contents/MacOS/TextEdit

With SVN, you should set SVN_EDITOR environment variable to:

$ export SVN_EDITOR=/Applications/TextEdit.app/Contents/MacOS/TextEdit

And then, when you try committing something, TextEdit will launch.

How to move columns in a MySQL table?

phpMyAdmin provides a GUI for this within the structure view of a table. Check to select the column you want to move and click the change action at the bottom of the column list. You can then change all of the column properties and you'll find the 'move column' function at the far right of the screen.

Of course this is all just building the queries in the perfectly good top answer but GUI fans might appreciate the alternative.

my phpMyAdmin version is 4.1.7

What is the best open source help ticket system?

I like eTicket Support, is very simple to use and install.

CSS - How to Style a Selected Radio Buttons Label?

_x000D_
_x000D_
.radio-toolbar input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
  display: inline-block;_x000D_
  background-color: #ddd;_x000D_
  padding: 4px 11px;_x000D_
  font-family: Arial;_x000D_
  font-size: 16px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
  background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
  <label for="radio1">All</label>_x000D_
_x000D_
  <input type="radio" id="radio2" name="radios" value="false">_x000D_
  <label for="radio2">Open</label>_x000D_
_x000D_
  <input type="radio" id="radio3" name="radios" value="true">_x000D_
  <label for="radio3">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

First of all, you probably want to add the name attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.

Also, since I placed the labels as siblings (of the radio buttons), I had to use the id and for attributes to associate them together.

How do I add an active class to a Link from React Router?

For me what worked has is using NavLink as it has this active class property.

  1. First import it

    import { NavLink } from 'react-router-dom';
    
  2. Use an activeClassName to get the active class property.

    <NavLink to="/" activeClassName="active">
     Home
    </NavLink>
    
    <NavLink to="/store" activeClassName="active">
     Store
    </NavLink>
    
    <NavLink to="/about" activeClassName="active">
     About Us
    </NavLink>
    
  3. Style your class in the css by the property active.

    .active{
      color:#fcfcfc;
     }
    

session handling in jquery

In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

Consider using sessionStorage directly: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

Git undo local branch delete

This worked for me:

git fsck --full --no-reflogs --unreachable --lost-found
git show d6e883ff45be514397dcb641c5a914f40b938c86
git branch helpme 15e521b0f716269718bb4e4edc81442a6c11c139

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

Javascript replace with reference to matched group?

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")

Base64 encoding and decoding in client-side Javascript

Short and fast Base64 JavaScript Decode Function without Failsafe:

function decode_base64 (s)
{
    var e = {}, i, k, v = [], r = '', w = String.fromCharCode;
    var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]];

    for (z in n)
    {
        for (i = n[z][0]; i < n[z][1]; i++)
        {
            v.push(w(i));
        }
    }
    for (i = 0; i < 64; i++)
    {
        e[v[i]] = i;
    }

    for (i = 0; i < s.length; i+=72)
    {
        var b = 0, c, x, l = 0, o = s.substring(i, i+72);
        for (x = 0; x < o.length; x++)
        {
            c = e[o.charAt(x)];
            b = (b << 6) + c;
            l += 6;
            while (l >= 8)
            {
                r += w((b >>> (l -= 8)) % 256);
            }
         }
    }
    return r;
}

Writing a new line to file in PHP (line feed)

Use PHP_EOL which outputs \r\n or \n depending on the OS.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

C++ templates that accept only certain types

We can use std::is_base_of and std::enable_if:
(static_assert can be removed, the above classes can be custom-implemented or used from boost if we cannot reference type_traits)

#include <type_traits>
#include <list>

class Base {};
class Derived: public Base {};

#if 0   // wrapper
template <class T> class MyClass /* where T:Base */ {
private:
    static_assert(std::is_base_of<Base, T>::value, "T is not derived from Base");
    typename std::enable_if<std::is_base_of<Base, T>::value, T>::type inner;
};
#elif 0 // base class
template <class T> class MyClass: /* where T:Base */
    protected std::enable_if<std::is_base_of<Base, T>::value, T>::type {
private:
    static_assert(std::is_base_of<Base, T>::value, "T is not derived from Base");
};
#elif 1 // list-of
template <class T> class MyClass /* where T:list<Base> */ {
    static_assert(std::is_base_of<Base, typename T::value_type>::value , "T::value_type is not derived from Base");
    typedef typename std::enable_if<std::is_base_of<Base, typename T::value_type>::value, T>::type base; 
    typedef typename std::enable_if<std::is_base_of<Base, typename T::value_type>::value, T>::type::value_type value_type;

};
#endif

int main() {
#if 0   // wrapper or base-class
    MyClass<Derived> derived;
    MyClass<Base> base;
//  error:
    MyClass<int> wrong;
#elif 1 // list-of
    MyClass<std::list<Derived>> derived;
    MyClass<std::list<Base>> base;
//  error:
    MyClass<std::list<int>> wrong;
#endif
//  all of the static_asserts if not commented out
//  or "error: no type named ‘type’ in ‘struct std::enable_if<false, ...>’ pointing to:
//  1. inner
//  2. MyClass
//  3. base + value_type
}

How to use custom packages

another solution:
add src/myproject to $GOPATH.

Then import "mylib" will compile.

Laravel - check if Ajax request

Those who prefer to use laravel helpers they can check if a request is ajax using laravel request() helper.

if(request()->ajax())
   // code

How to make PyCharm always show line numbers

Using Search bar

  1. Press 2 times Shift
  2. Paste /editor /appearance/ and then
  3. Click on Show line numbers toggle button

For Windows and Linux

File | Settings | Editor | General | Appearance 

For macOS

IntelliJ IDEA | Preferences | Editor | General | Appearance 

Using shortcut

Ctrl+Alt+S

Then

Editor > General > Appearance

Click on Show line numbers toggle button.


Pycharm Official Doc (Appearance)

How to use the gecko executable with Selenium

Recently Selenium has launched Selenium 3 and if you are trying to use Firefox latest version then you have to use GeckoDriver:

System.setProperty("webdriver.gecko.driver","G:\\Selenium\\Firefox driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

You can check full documentation from here

How can I use pointers in Java?

Not really, no.

Java doesn't have pointers. If you really wanted you could try to emulate them by building around something like reflection, but it would have all of the complexity of pointers with none of the benefits.

Java doesn't have pointers because it doesn't need them. What kind of answers were you hoping for from this question, i.e. deep down did you hope you could use them for something or was this just curiousity?

Twitter Bootstrap Datepicker within modal window

$('#effective_to').datepicker({
    dateFormat: "dd-mm-yyyy",
    changeMonth: true,
    changeYear: true,
    beforeShow: function() { 
        $('#ui-datepicker-div').addClass('datepicker');
    }
});

CSS

.datepicker {
    z-index: 100000 !important;
    display: block;
}

This works form me. Even though I called model via ajax

Create controller for partial view in ASP.NET MVC

Why not use Html.RenderAction()?

Then you could put the following into any controller (even creating a new controller for it):

[ChildActionOnly]
public ActionResult MyActionThatGeneratesAPartial(string parameter1)
{
    var model = repository.GetThingByParameter(parameter1);
    var partialViewModel = new PartialViewModel(model);
    return PartialView(partialViewModel); 
}

Then you could create a new partial view and have your PartialViewModel be what it inherits from.

For Razor, the code block in the view would look like this:

@{ Html.RenderAction("Index", "Home"); }

For the WebFormsViewEngine, it would look like this:

<% Html.RenderAction("Index", "Home"); %>

Resize Google Maps marker icon image

If the original size is 100 x 100 and you want to scale it to 50 x 50, use scaledSize instead of Size.

var icon = {
    url: "../res/sit_marron.png", // url
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
};

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    icon: icon
});

PHP XML how to output nice format

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$dom = new DOMDocument();                               //create a document
$dom->preserveWhiteSpace = false;                       //disable whitespace preservation
$dom->formatOutput = true;                              //pretty print output
$documentElement = $dom->createElement("Entry");        //create a node
$dom->appendChild ($documentElement);                   //append it 
$message = new DOMDocument();                           //create another document
$message->loadXML($messageXMLtext);                     //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node);                   //append the new node to the document Element
$dom->saveXML($dom->documentElement);                   //print the original document

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

inner join in linq to entities

You can find a whole bunch of Linq examples in visual studio. Just select Help -> Samples, and then unzip the Linq samples.

Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.

The answer you are looking for is in method Linq14:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
   from a in numbersA
   from b in numbersB
   where a < b
   select new {a, b};

How can I enable MySQL's slow query log without restarting MySQL?

If you want to enable general error logs and slow query error log in the table instead of file

To start logging in table instead of file:

set global log_output = “TABLE”;

To enable general and slow query log:

set global general_log = 1;
set global slow_query_log = 1;

To view the logs:

select * from mysql.slow_log;
select * from mysql.general_log;

For more details visit this link

http://easysolutionweb.com/technology/mysql-server-logs/

How do you update a DateTime field in T-SQL?

That should work, I'd put brackets around [Date] as it's a reserved keyword.

How do you know a variable type in java?

I think we have multiple solutions here:

  • instance of could be a solution.

Why? In Java every class is inherited from the Object class itself. So if you have a variable and you would like to know its type. You can use

  • System.out.println(((Object)f).getClass().getName());

or

  • Integer.class.isInstance(1985); // gives true

or

  • isPrimitive()

    public static void main(String[] args) {
    
     ClassDemo classOne = new ClassDemo();
     Class classOneClass = classOne();
    
     int i = 5;
     Class iClass = int.class;
    
     // checking for primitive type
     boolean retval1 = classOneClass.isPrimitive();
     System.out.println("classOneClass is primitive type? = " + retval1);
    
     // checking for primitive type?
     boolean retval2 = iClass.isPrimitive();
     System.out.println("iClass is primitive type? = " + retval2);
    }
    

This going to give us:

  1. FALSE
  2. TRUE

Find out more here: How to determine the primitive type of a primitive variable?

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

http://docs.oracle.com/cd/E26806_01/wlp.1034/e14255/com/bea/p13n/expression/operator/Instanceof.html

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

Getting an element from a Set

Convert set to list, and then use get method of list

Set<Foo> set = ...;
List<Foo> list = new ArrayList<Foo>(set);
Foo obj = list.get(0);

How to apply a patch generated with git format-patch?

First you should take a note about difference between git am and git apply

When you are using git am you usually wanna to apply many patches. Thus should use:

git am *.patch

or just:

git am

Git will find patches automatically and apply them in order ;-)

UPD
Here you can find how to generate such patches

Why does an image captured using camera intent gets rotated on some devices on Android?

Jason Robinson's answer and Sami Eltamawy answer are excelent.

Just an improvement to complete the aproach, you should use compat ExifInterface.

com.android.support:exifinterface:${lastLibVersion}

You will be able to instantiate the ExifInterface(pior API <24) with InputStream (from ContentResolver) instead of uri paths avoiding "File not found exceptions"

https://android-developers.googleblog.com/2016/12/introducing-the-exifinterface-support-library.html

Setting device orientation in Swift iOS

Swift 4:

The simplest answer, in my case needing to ensure one onboarding tutorial view was portrait-only:

extension myViewController {
    //manage rotation for this viewcontroller
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

Eezy-peezy.

How do I multiply each element in a list by a number?

from functools import partial as p
from operator import mul
map(p(mul,5),my_list)

is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class

Why would you use String.Equals over ==?

I've just been banging my head against a wall trying to solve a bug because I read this page and concluded there was no meaningful difference when in practice there is so I'll post this link here in case anyone else finds they get different results out of == and equals.

Object == equality fails, but .Equals succeeds. Does this make sense?

string a = "x";
string b = new String(new []{'x'});

Console.WriteLine("x == x " + (a == b));//True
Console.WriteLine("object x == x " + ((object)a == (object)b));//False
Console.WriteLine("x equals x " + (a.Equals(b)));//True
Console.WriteLine("object x equals x " + (((object)a).Equals((object)b)));//True

Provisioning Profiles menu item missing from Xcode 5

Try this:

Xcode >> Preferences >> Accounts

Free Online Team Foundation Server

One of recent the TFS Rocks pocasts mentioned such an organisation, may have been number 16.

Does overflow:hidden applied to <body> work on iPhone Safari?

body {
  position:relative; // that's it
  overflow:hidden;
}

Android: Create spinner programmatically from array

This worked for me with a string-array named shoes loaded from the projects resources:

Spinner              spinnerCountShoes = (Spinner)findViewById(R.id.spinner_countshoes);
ArrayAdapter<String> spinnerCountShoesArrayAdapter = new ArrayAdapter<String>(
                     this,
                     android.R.layout.simple_spinner_dropdown_item, 
                     getResources().getStringArray(R.array.shoes));
spinnerCountShoes.setAdapter(spinnerCountShoesArrayAdapter);

This is my resource file (res/values/arrays.xml) with the string-array named shoes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="shoes">
        <item>0</item>
        <item>5</item>
        <item>10</item>
        <item>100</item>
        <item>1000</item>
        <item>10000</item>
    </string-array>
</resources>

With this method it's easier to make it multilingual (if necessary).

how to set image from url for imageView

Try the library SimpleDraweeView

<com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/badge_image"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

and now you can simply do:

 final Uri uri = Uri.parse(post.getImageUrl());

What is the native keyword in Java for?

functions that implement native code are declared native.

The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be called by, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

http://en.wikipedia.org/wiki/Java_Native_Interface

Foreign Key naming scheme

I usually just leave my PK named id, and then concatenate my table name and key column name when naming FKs in other tables. I never bother with camel-casing, because some databases discard case-sensitivity and simply return all upper or lower case names anyway. In any case, here's what my version of your tables would look like:

task (id, userid, title);
note (id, taskid, userid, note);
user (id, name);

Note that I also name my tables in the singular, because a row represents one of the objects I'm persisting. Many of these conventions are personal preference. I'd suggest that it's more important to choose a convention and always use it, than it is to adopt someone else's convention.

List<T> or IList<T>

Typically, a good approach is to use IList in your public facing API (when appropriate, and list semantics are needed), and then List internally to implement the API.  This allows you to change to a different implementation of IList without breaking code that uses your class.

The class name List may be changed in next .net framework but the interface is never going to change as interface is contract.

Note that, if your API is only going to be used in foreach loops, etc, then you might want to consider just exposing IEnumerable instead.

python pandas: apply a function with arguments to a series

Steps:

  1. Create a dataframe
  2. Create a function
  3. Use the named arguments of the function in the apply statement.

Example

x=pd.DataFrame([1,2,3,4])  

def add(i1, i2):  
    return i1+i2

x.apply(add,i2=9)

The outcome of this example is that each number in the dataframe will be added to the number 9.

    0
0  10
1  11
2  12
3  13

Explanation:

The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

Generate a UUID on iOS from Swift

You could also just use the NSUUID API:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

Note that NSUUID is available from iOS 6 and up.

React Checkbox not sending onChange

To get the checked state of your checkbox the path would be:

this.refs.complete.state.checked

The alternative is to get it from the event passed into the handleChange method:

event.target.checked

Iterate Multi-Dimensional Array with Nested Foreach Statement

Use LINQ .Cast<int>() to convert 2D array to IEnumerable<int>.

LINQPad example:

var arr = new int[,] { 
  { 1, 2, 3 }, 
  { 4, 5, 6 } 
};

IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);

Output:

Sequence is 1,2,3,4,5,6

CSS-Only Scrollable Table with fixed headers

Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

How to get current available GPUs in tensorflow?

I got a GPU called NVIDIA GTX GeForce 1650 Ti in my machine with tensorflow-gpu==2.2.0

Run the following two lines of code:

import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

Output:

Num GPUs Available:  1

How to show only next line after the matched one?

If you want to stick to grep:

grep -A1 'blah' logfile | grep -v "blah"

or alternatively with sed:

sed -n '/blah/{n;p;}' logfile

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

Global and local variables in R

<- does assignment in the current environment.

When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.

In most cases <<- will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.

This might illustrate what is going on.

bar <- "global"
foo <- function(){
    bar <- "in foo"
    baz <- function(){
        bar <- "in baz - before <<-"
        bar <<- "in baz - after <<-"
        print(bar)
    }
    print(bar)
    baz()
    print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"

The first time we print bar we haven't called foo yet so it should still be global - this makes sense. The second time we print it's inside of foo before calling baz so the value "in foo" makes sense. The following is where we see what <<- is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-. This is because <<- doesn't look in the current environment (unless you're in the global environment in which case <<- acts like <-). So inside of baz the value of bar stays as "in baz - before <<-". Once we call baz the copy of bar inside of foo gets changed to "in baz" but as we can see the global bar is unchanged. This is because the copy of bar that is defined inside of foo is in the parent environment when we created baz so this is the first copy of bar that <<- sees and thus the copy it assigns to. So <<- isn't just directly assigning to the global environment.

<<- is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.

Now I change the <<- to an assign statement and we can see what effect that has:

bar <- "global"
foo <- function(){
    bar <- "in foo"   
    baz <- function(){
        assign("bar", "in baz", envir = .GlobalEnv)
    }
    print(bar)
    baz()
    print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"

So both times we print bar inside of foo the value is "in foo" even after calling baz. This is because assign never even considered the copy of bar inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.

Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local function.

bar <- "global"
# local will create a new environment for us to play in
local({
    bar <- "local"
    print(bar)
})
#[1] "local"
bar
#[1] "global"

How to create relationships in MySQL

as ehogue said, put this in your CREATE TABLE

FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 

alternatively, if you already have the table created, use an ALTER TABLE command:

ALTER TABLE `accounts`
  ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;

One good way to start learning these commands is using the MySQL GUI Tools, which give you a more "visual" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.

c - warning: implicit declaration of function ‘printf’

You need to include the appropriate header

#include <stdio.h>

If you're not sure which header a standard function is defined in, the function's man page will state this.

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

Why can't decimal numbers be represented exactly in binary?

A parallel can be made of fractions and whole numbers. Some fractions eg 1/7 cannot be represented in decimal form without lots and lots of decimals. Because floating point is binary based the special cases change but the same sort of accuracy problems present themselves.

Passing an array using an HTML form hidden element

You can use serialize and base64_encode from the client side. After that, then use unserialize and base64_decode on the server side.

Like:

On the client side, use:

    $postvalue = array("a", "b", "c");
    $postvalue = base64_encode(serialize($array));

   // Your form hidden input
   <input type="hidden" name="result" value="<?php echo $postvalue; ?>">

On the server side, use:

    $postvalue = unserialize(base64_decode($_POST['result']));
    print_r($postvalue) // Your desired array data will be printed here

Is it possible to remove the focus from a text input when a page loads?

A jQuery solution would be something like:

$(function () {
    $('input').blur();
});

How do I append to a table in Lua

I'd personally make use of the table.insert function:

table.insert(a,"b");

This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.

Calculate time difference in Windows batch file

As answered here: How can I use a Windows batch file to measure the performance of console application?

Below batch "program" should do what you want. Please note that it outputs the data in centiseconds instead of milliseconds. The precision of the used commands is only centiseconds.

Here is an example output:

STARTTIME: 13:42:52,25
ENDTIME: 13:42:56,51
STARTTIME: 4937225 centiseconds
ENDTIME: 4937651 centiseconds
DURATION: 426 in centiseconds
00:00:04,26

Here is the batch script:

@echo off
setlocal

rem The format of %TIME% is HH:MM:SS,CS for example 23:59:59,99
set STARTTIME=%TIME%

rem here begins the command you want to measure
dir /s > nul
rem here ends the command you want to measure

set ENDTIME=%TIME%

rem output as time
echo STARTTIME: %STARTTIME%
echo ENDTIME: %ENDTIME%

rem convert STARTTIME and ENDTIME to centiseconds
set /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
set /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)

rem calculating the duratyion is easy
set /A DURATION=%ENDTIME%-%STARTTIME%

rem we might have measured the time inbetween days
if %ENDTIME% LSS %STARTTIME% set set /A DURATION=%STARTTIME%-%ENDTIME%

rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A DURATIONH=%DURATION% / 360000
set /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
set /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
set /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)

rem some formatting
if %DURATIONH% LSS 10 set DURATIONH=0%DURATIONH%
if %DURATIONM% LSS 10 set DURATIONM=0%DURATIONM%
if %DURATIONS% LSS 10 set DURATIONS=0%DURATIONS%
if %DURATIONHS% LSS 10 set DURATIONHS=0%DURATIONHS%

rem outputing
echo STARTTIME: %STARTTIME% centiseconds
echo ENDTIME: %ENDTIME% centiseconds
echo DURATION: %DURATION% in centiseconds
echo %DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%

endlocal
goto :EOF

NSURLConnection Using iOS Swift

Swift 3.0

AsynchonousRequest

let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared

session.dataTask(with: request) {data, response, error in
  if error != nil {
    print(error!.localizedDescription)
    return
  }

  do {
    let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
    print("Synchronous\(jsonResult)")
  } catch {
    print(error.localizedDescription)
  }
}.resume()

Inserting values into tables Oracle SQL

You can insert into a table from a SELECT.

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  (SELECT id FROM state WHERE name = 'New York'),
  (SELECT id FROM positions WHERE name = 'Sales Executive'),
  (SELECT id FROM manager WHERE name = 'Barry Green')
FROM
  dual

Or, similarly...

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  state.id,
  positions.id,
  manager.id
FROM
  state
CROSS JOIN
  positions
CROSS JOIN
  manager
WHERE
      state.name     = 'New York'
  AND positions.name = 'Sales Executive'
  AND manager.name   = 'Barry Green'

Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.

Trigger a button click with JavaScript on the Enter key in a text box

In plain JavaScript,

if (document.layers) {
  document.captureEvents(Event.KEYDOWN);
}

document.onkeydown = function (evt) {
  var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
  if (keyCode == 13) {
    // For Enter.
    // Your function here.
  }
  if (keyCode == 27) {
    // For Escape.
    // Your function here.
  } else {
    return true;
  }
};

I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.

When is the init() function run?

Here is another example - https://play.golang.org/p/9P-LmSkUMKY

package main

import (
    "fmt"
)

func callOut() int {
    fmt.Println("Outside is beinge executed")
    return 1
}

var test = callOut()

func init() {
    fmt.Println("Init3 is being executed")
}

func init() {
    fmt.Println("Init is being executed")
}

func init() {
    fmt.Println("Init2 is being executed")
}

func main() {
    fmt.Println("Do your thing !")
}

Output of the above program

$ go run init/init.go
Outside is being executed
Init3 is being executed
Init is being executed
Init2 is being executed
Do your thing !

How do you clear Apache Maven's cache?

I've had this same problem, and I wrote a one-liner in shell to do it.

rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
                       -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
                       -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*

I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:

#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
  -Dexpression=settings.localRepository \
  -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
  -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
  --batch-mode \
  | grep -vF '[INFO]')

rm -rf $REPOSITORY/*

Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.

It's a bit wieldy, but it's a decent way of doing business, IMO.

Which sort algorithm works best on mostly sorted data?

Insertion sort takes time O(n + the number of inversions).

An inversion is a pair (i, j) such that i < j && a[i] > a[j]. That is, an out-of-order pair.

One measure of being "almost sorted" is the number of inversions---one could take "almost sorted data" to mean data with few inversions. If one knows the number of inversions to be linear (for instance, you have just appended O(1) elements to a sorted list), insertion sort takes O(n) time.

Send email from localhost running XAMMP in PHP using GMAIL mail server

Simplest way is to use PHPMailer and Gmail SMTP. The configuration would be like the below.

require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();                            
$mail->Host = 'smtp.gmail.com';            
$mail->SMTPAuth = true;                     
$mail->Username = 'Email Address';          
$mail->Password = 'Email Account Password'; 
$mail->SMTPSecure = 'tls';               
$mail->Port = 587;                  

Example script and full source code can be found from here - How to Send Email from Localhost in PHP

How to print to stderr in Python?

For Python 2 my choice is: print >> sys.stderr, 'spam' Because you can simply print lists/dicts etc. without convert it to string. print >> sys.stderr, {'spam': 'spam'} instead of: sys.stderr.write(str({'spam': 'spam'}))

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

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

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

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

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

How do you post to the wall on a facebook page (not profile)

You can not post to Facebook walls automatically without creating an application and using the templated feed publisher as Frank pointed out.

The only thing you can do is use the 'share' widgets that they provide, which require user interaction.

d3.select("#element") not working when code above the html element

just add your <script src="./custom.js"></script> before </bod> tag. that is supply time to d3.select(#chart) detect your #chart element in html body

MySQL CURRENT_TIMESTAMP on create and on update

you can try this ts_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP, ts_update TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP

Regex any ASCII character

Depending on what you mean with "ASCII character" you could simply try:

xxx.+xxx

SVN repository backup strategies

1.1 Create Dump from SVN (Subversion) repository

svnadmin dump /path/to/reponame > /path/to/reponame.dump

Real example

svnadmin dump /var/www/svn/testrepo > /backups/testrepo.dump

1.2 Gzip Created Dump

gzip -9 /path/to/reponame.dump

Real example

gzip -9 /backups/testrepo.dump

1.3 SVN Dump and Gzip Dump with One-liner

svnadmin dump /path/to/reponame | gzip -9 > /path/to/reponame.dump.gz

Real example

svnadmin dump /var/www/svn/testrepo |Â gzip -9 > /backups/testrepo.dump.gz

How to Backup (dump) and Restore (load) SVN (Subversion) repository on Linux.
Ref: svn subversion backup andrestore

How do I find the maximum of 2 numbers?

I noticed that if you have divisions it rounds off to integer, it would be better to use:

c=float(max(a1,...,an))/b

Sorry for the late post!

How to pull remote branch from somebody else's repo

git remote add coworker git://path/to/coworkers/repo.git
git fetch coworker
git checkout --track coworker/foo

This will setup a local branch foo, tracking the remote branch coworker/foo. So when your co-worker has made some changes, you can easily pull them:

git checkout foo
git pull

Response to comments:

Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?

You don't need to create a new branch, even though I recommend it. You might as well commit directly to foo and have your co-worker pull your branch. But that branch already exists and your branch foo need to be setup as an upstream branch to it:

git branch --set-upstream foo colin/foo

assuming colin is your repository (a remote to your co-workers repository) defined in similar way:

git remote add colin git://path/to/colins/repo.git

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

You can transfer those (simply by adding a remote to a GitHub repo and by pushing them)

  • create an empty repo on GitHub
  • git remote add github https://[email protected]/yourLogin/yourRepoName.git
  • git push --mirror github

The history will be the same.

But you will loose the access control (teams defined in GitLab with specific access rights on your repo)

If you facing any issue with the https URL of the GitHub repo:

The requested URL returned an error: 403

All you need to do is to enter your GitHub password, but the OP suggests:

Then you might need to push it the ssh way. You can read more on how to do it here.

See "Pushing to Git returning Error Code 403 fatal: HTTP request failed".

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

sh: 0: getcwd() failed: No such file or directory on cited drive

This can happen with symlinks sometimes. If you experience this issue and you know you are in an existing directory, but your symlink may have changed, you can use this command:

cd $(pwd)

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

The simplest and best solution is just to use XMLRoot attribute in your class, in which you wish to deserialize.

Like:

[XmlRoot(ElementName = "YourPreferableNameHere")]
public class MyClass{
...
}

Also, use the following Assembly :

using System.Xml.Serialization;

postgresql port confusion 5433 or 5432?

It seems that one of the most common reasons this happens is if you install a new version of PostgreSQL without stopping the service of an existing installation. This was a particular headache of mine, too. Before installing or upgrading, particularly on OS X and using the one click installer from Enterprise DB, make sure you check the status of the old installation before proceeding.

Adding values to a C# array

This seems like a lot less trouble to me:

var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();

Create an Android GPS tracking application

Basically you need following things to make location detector android app

Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.

Using all these resources, you will be able to create an flawless android location detection app.

1. Location Listening

You will first need to listen for current location of user. You can use any of below libraries to quick start.

Google Play Location Samples

This library provide last known location, location updates

Location Manager

With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.

Live Location Sharing

Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.

2. Markers Library

Google Maps Android API utility library

  • Marker clustering — handles the display of a large number of points
  • Heat maps — display a large number of points as a heat map
  • IconGenerator — display text on your Markers
  • Poly decoding and encoding — compact encoding for paths, interoperability with Maps API web services
  • Spherical geometry — for example: computeDistance, computeHeading, computeArea
  • KML — displays KML data
  • GeoJSON — displays and styles GeoJSON data

3. Polyline Libraries

DrawRouteMaps

If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.

trail-android

Simple, smooth animation for route / polylines on google maps using projections. (WIP)

Google-Directions-Android

This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.

A map demo app for quick start with maps

Matching an empty input box using CSS

There is no selector in CSS which does this. Attribute selectors match attribute values, not computed values.

You would have to use JavaScript.

SQL how to make null values come last when sorting ascending

(A "bit" late, but this hasn't been mentioned at all)

You didn't specify your DBMS.

In standard SQL (and most modern DBMS like Oracle, PostgreSQL, DB2, Firebird, Apache Derby, HSQLDB and H2) you can specify NULLS LAST or NULLS FIRST:

Use NULLS LAST to sort them to the end:

select *
from some_table
order by some_column DESC NULLS LAST

Can't access 127.0.0.1

If it's a DNS problem, you could try:

  • ipconfig /flushdns
  • ipconfig /registerdns

If this doesn't fix it, you could try editing the hosts file located here:

C:\Windows\System32\drivers\etc\hosts

And ensure that this line (and no other line referencing localhost) is in there:

127.0.0.1 localhost

jQuery - adding elements into an array

var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');

        ids.push(this.id);       
    });
});

How to check what user php is running as?

Kind of backward way, but without exec/system:

file_put_contents("testFile", "test");
$user = fileowner("testFile");
unlink("testFile");

If you create a file, the owner will be the PHP user.

This could also likely be run with any of the temporary file functions such as tempnam(), which creates a random file in the temporary directory and returns the name of that file. If there are issues due to something like the permissions, open_basedir or safe mode that prevent writing a file, typically, the temp directory will still be allowed.

What is lazy loading in Hibernate?

"Lazy loading" means that an entity will be loaded only when you actually accesses the entity for the first time.

The pattern is like this:

public Entity getEntity() {
    if (entity == null) {
        entity = loadEntity();
    }
    return entity;
}

This saves the cost of preloading/prefilling all the entities in a large dataset beforehand while you after all actually don't need all of them.

In Hibernate, you can configure to lazily load a collection of child entities. The actual lazy loading is then done inside the methods of the PersistentSet which Hibernate uses "under the hoods" to assign the collection of entities as Set.

E.g.

public class Parent {
    private Set<Child> children;

    public Set<Child> getChildren() {
        return children;
    }
}

.

public void doSomething() {
    Set<Child> children = parent.getChildren(); // Still contains nothing.

    // Whenever you call one of the following (indirectly), 
    // Hibernate will start to actually load and fill the set.
    children.size();
    children.iterator();
}

android.content.Context.getPackageName()' on a null object reference

In my case the error occurred inside a Fragment on this line:

Intent intent = new Intent(getActivity(), SecondaryActivity.class);

It happened when I double clicked on an item which triggered the code above so two SecondaryActivity.class activities were launched at the same time, one on top of the other. I closed the top SecondaryActivity.class activity by pressing back button which triggered a call to getActivity() in the SecondaryActivity.class which came to foreground. The call to getActivity() returned null. It's some kind of weird Android bug so it usually should not happen. You can block the clicks after the user clicked once.

How to return value from function which has Observable subscription inside?

EDIT: updated code in order to reflect changes made to the way pipes work in more recent versions of RXJS. All operators (take in my example) are now wrapped into the pipe() operator.

I realize that this Question was quite a while ago and you surely have a proper solution by now, but for anyone looking for this I would suggest solving it with a Promise to keep the async pattern.

A more verbose version would be creating a new Promise:

function getValueFromObservable() {
    return new Promise(resolve=>{
        this.store.pipe(
           take(1) //useful if you need the data once and don't want to manually cancel the subscription again
         )
         .subscribe(
            (data:any) => {
                console.log(data);
                resolve(data);
         })
    })
}

On the receiving end you will then have "wait" for the promise to resolve with something like this:

getValueFromObservable()
   .then((data:any)=>{
   //... continue with anything depending on "data" after the Promise has resolved
})

A slimmer solution would be using RxJS' .toPromise() instead:

function getValueFromObservable() {
    return this.store.pipe(take(1))
       .toPromise()   
}

The receiving side stays the same as above of course.

C# elegant way to check if a property's property is null

var result = nullableproperty ?? defaultvalue;

The ?? (null-coalescing operator) means if the first argument is null, return the second one instead.

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

Converting an int to std::string

Non-standard function, but its implemented on most common compilers:

int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);

Update

C++11 introduced several std::to_string overloads (note that it defaults to base-10).

Export data from R to Excel

I have been trying out the different packages including the function:

install.packages ("prettyR") 

library (prettyR)

delimit.table (Corrvar,"Name the csv.csv") ## Corrvar is a name of an object from an output I had on scaled variables to run a regression.

However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:

  • copied the output from R (Ctrl+c)
  • in Excel sheet I pasted it (Ctrl+V)
  • Select the first column where the data is
  • In the "Data" vignette, click on "Text to column"

  • Select Delimited option, click next

  • Tick space box in "Separator", click next

  • Click Finalize (End)

Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.

PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.

SVN: Is there a way to mark a file as "do not commit"?

As I was facing the exact same issue, and my googling kept giving me nothing, I think I found a workaround. Here's what I did, it seems to work for me, but as I'm stuck with an old version of SVN (< 1.5, as it doesn't have the --keep-local option) and I'm no expert of it, I can't be sure it's an universal solution. If it works for you too, please let me know !

I was dealing with a Prestashop install I got from SVN, since other people had already started working on it. Since the DB settings were done for another server, I changed them in some file in the /config folder. As this folder was already versioned, setting it in svn:ignore would not prevent my local modifications on it from being committed. Here's what I did :

cp config ../cfg_bkp              # copy the files out of the repo
svn rm config                     # delete files both from svn and "physically"
svn propset svn:ignore "config" . # as the files no longer exists, I can add my ignore rule and then...
mv ../cfg_bkp config              # ...bring'em back
svn revert --recursive config     # make svn forget any existing status for the files (they won't be up for deletion anymore)

Now I can run svn add --force . at the repo root without adding my config, even if it's not matching the repo's version (I guess I would have to go through all this again if I modified it one more time, did not test). I can svn update as well without having my files being overwritten or getting any error.

Angular 2 change event - model changes

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel">

See also

Set selected radio from radio group with a value

There is a better way of checking radios and checkbox; you have to pass an array of values to the val method instead of a raw value

Note: If you simply pass the value by itself (without being inside an array), that will result in all values of "mygroup" being set to the value.

$("input[name=mygroup]").val([5]);

Here is the jQuery doc that explains how it works: http://api.jquery.com/val/#val-value

And .val([...]) also works with form elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>.

The inputs and the options having a value that matches one of the elements of the array will be checked or selected, while those having a value that don't match one of the elements of the array will be unchecked or unselected

Fiddle demonstrating this working: https://jsfiddle.net/92nekvp3/

Android Lint contentDescription warning

For graphical elements that are purely decorative, set their respective android:contentDescription XML attributes to "@null".

If your app only supports devices running Android 4.1 (API level 16) or higher, you can instead set these elements' android:importantForAccessibility XML attributes to "no"

Error inflating when extending a class

The thing to understand here is that:

The constructor ViewClassName(Context context, AttributeSet attrs ) is called when inflating the customView via xml. You see you are not using the new keyword to instantiate your object i.e. you are not doing new GhostSurfaceCameraView(). Doing this you are calling the first constructor i.e. public View (Context context).

Whereas when inflating view from XML, i.e. when using setContentView(R.layout.ghostviewscreen); or using findViewById, you, NO, not you!, the android system calls the ViewClassName(Context context, AttributeSet attrs ) constructor.

This is clear when reading the documentation : "Constructor that is called when inflating a view from XML." See: https://developer.android.com/reference/android/view/View.html#View(android.content.Context,%20android.util.AttributeSet)

Hence, never forget basic polymorphism and never forget reading through the documentation. It saves a ton of headache.

Get size of an Iterable in Java

Why don't you simply use the size() method on your Collection to get the number of elements?

Iterator is just meant to iterate,nothing else.

Which version of MVC am I using?

typeof(Controller).Assembly.GetName().Version

Gives the current version programmatically.

Python: Figure out local timezone

First, note that the question presents an incorrect initialization of an aware datetime object:

>>> local_time=datetime.datetime(2010, 4, 27, 12, 0, 0, 0,
...                                  tzinfo=pytz.timezone('Israel'))

creates an invalid instance. One can see the problem by computing the UTC offset of the resulting object:

>>> print(local_time.utcoffset())
2:21:00

(Note the result which is an odd fraction of an hour.)

To initialize an aware datetime properly using pytz one should use the localize() method as follows:

>>> local_time=pytz.timezone('Israel').localize(datetime.datetime(2010, 4, 27, 12))
>>> print(local_time.utcoffset())
3:00:00

Now, if you require a local pytz timezone as the new tzinfo, you should use the tzlocal package as others have explained, but if all you need is an instance with a correct local time zone offset and abbreviation then tarting with Python 3.3, you can call the astimezone() method with no arguments to convert an aware datetime instance to your local timezone:

>>> local_time.astimezone().strftime('%Y-%m-%d %H:%M %Z %z')
'2010-04-27 05:00 EDT -0400'

C99 stdint.h header and MS Visual Studio

Boost contains cstdint.hpp header file with the types you are looking for: http://www.boost.org/doc/libs/1_36_0/boost/cstdint.hpp

Getting reference to the top-most view/window in iOS application

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:@"UIWindow"]) {

    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if ([NSStringFromClass([window class]) isEqualToString:@"UIWindow"]) {
            keyWindow = window;
            break;
        }
    }
}

Remove lines that contain certain string

to_skip = ("bad", "naughty")
out_handle = open("testout", "w")

with open("testin", "r") as handle:
    for line in handle:
        if set(line.split(" ")).intersection(to_skip):
            continue
        out_handle.write(line)
out_handle.close()

How to enable directory listing in apache web server

Once I changed Options -Index to Options +Index in my conf file, I removed the welcome page and restarted services.

$ sudo rm -f /etc/httpd/conf.d/welcome.conf
$ sudo service httpd restart

I was able to see directory listings after that.

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

How to detect the currently pressed key?

The best way I have found to manage keyboard input on a Windows Forms form is to process it after the keystroke and before the focused control receives the event. Microsoft maintains a built-in Form-level property named .KeyPreview to facilitate this precise thing:

public frmForm()
{
    // ...
    frmForm.KeyPreview = true;
    // ...
}

Then the form's _KeyDown, _KeyPress, and / or _KeyUp events can be marshaled to access input events before the focused form control ever sees them, and you can apply handler logic to capture the event there or allow it to pass through to the focused form control.

Although not as structurally graceful as XAML's event-routing architecture, it makes management of form-level functions in Winforms far simpler. See the MSDN notes on KeyPreview for caveats.

How to grep, excluding some patterns?

How about just chaining the greps?

grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'

ERROR 1148: The used command is not allowed with this MySQL version

I got this error while loading data when using docker[1]. The solution worked after I followed these next steps. Initially, I created the database and table datavault and fdata. When I tried to import the data[2], I got the error[3]. Then I did:

  • SET GLOBAL local_infile = 1;
  • Confirm using SHOW VARIABLES LIKE 'local_infile';
  • Then I restarted my mysql session: mysql -P 3306 -u required --local-infile=1 -p, see [4] for user creation.
  • I recreated my table as this solved my problem:
    • use datavault;
    • drop table fdata;
    • CREATE TABLE fdata (fID INT, NAME VARCHAR(64), LASTNAME VARCHAR(64), EMAIL VARCHAR(128), GENDER VARCHAR(12), IPADDRESS VARCHAR(40));
  • Finally I imported the data using [2].

For completeness, I would add I was running the mysql version inside the container via docker exec -it testdb sh. The mysql version was mysql Ver 8.0.17 for Linux on x86_64 (MySQL Community Server - GPL). This was also tested with mysql.exe Ver 14.14 Distrib 5.7.14, for Win64 (x86_64) which was another version of mysql from WAMP64. The associated commands used are listed in [5].


[1] docker run --name testdb -v //c/Users/C/Downloads/data/csv-data/:/var/data -p 3306 -e MYSQL_ROOT_PASSWORD=password -d mysql:latest

[2] load data local infile '/var/data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n' IGNORE 1 ROWS;

[3] ERROR 1148 (42000): The used command is not allowed with this MySQL version

[4] The required client was created using:

  • CREATE USER 'required'@'%' IDENTIFIED BY 'password';
  • GRANT ALL PRIVILEGES ON * . * TO 'required'@'%';
  • FLUSH PRIVILEGES;
  • You might need this line ALTER USER 'required'@'%' IDENTIFIED WITH mysql_native_password BY 'password'; if you run into this error: Authentication plugin ‘caching_sha2_password’ cannot be loaded

[5] Commands using mysql from WAMP64:

  • mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile=1 where the port is thee mapped port into the host as described by docker ps -a and the host ip was optained using docker-machine ip (This depends on OS and possibly Docker version).
  • Create database datavault2 and table fdata as described above
  • load data local infile 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n';
  • For my record, this other alternative to load the file worked after I have previously created datavault3 and fdata: mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile datavault3 -e "LOAD DATA LOCAL INFILE 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' REPLACE INTO TABLE fdata FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS" and it successfully loaded the data easily checked after running select * from fdata limit 10;.

Convert char * to LPWSTR

The clean way to use mbstowcs is to call it twice to find the length of the result:

  const char * cs = <your input char*>
  size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);

  // error if wn == size_t(-1)

  wchar_t * buf = new wchar_t[wn + 1]();  // value-initialize to 0 (see below)

  wn = mbsrtowcs(buf, &cs, wn + 1, NULL);

  // error if wn == size_t(-1)

  assert(cs == NULL); // successful conversion

  // result now in buf, return e.g. as std::wstring

  delete[] buf;

Don't forget to call setlocale(LC_CTYPE, ""); at the beginning of your program!

The advantage over the Windows MultiByteToWideChar is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.

I usually wrap this method, along with the opposite one, in two conversion functions string->wstring and wstring->string. If you also add trivial overloads string->string and wstring->wstring, you can easily write code that compiles with the Winapi TCHAR typedef in any setting.

[Edit:] I added zero-initialization to buf, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn), though, but do beware if you plan on using C-style null-terminated arrays.[/]

In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.

Here is a small rant of mine on this topic.

Spark: subtract two DataFrames

From spark 3.0

data_cl = reg_data.exceptAll(data_fr)

AWS : The config profile (MyName) could not be found

Use as follows

[profilename]
region=us-east-1
output=text

Example cmd

aws --profile myname CMD opts

how to get the value of a textarea in jquery?

You can directly use

var message = $.trim($("#message").val());

Read more @ Get the Value of TextArea using the jQuery Val () Method

How to delete a file after checking whether it exists

Use System.IO.File.Delete like so:

System.IO.File.Delete(@"C:\test.txt")

From the documentation:

If the file to be deleted does not exist, no exception is thrown.

Android getActivity() is undefined

In my application, it was enough to use:

myclassname.this

How can I create tests in Android Studio?

As of now (studio 0.61) maintaining proper project structure is enough. No need to create separate test project as in eclipse (see below).

Tests structure

Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

find . -type f -exec chmod 644 {} ;

I need this so often that I created a function in my ~/.bashrc file:

chmodf() {
        find $2 -type f -exec chmod $1 {} \;
}
chmodd() {
        find $2 -type d -exec chmod $1 {} \;
}

Now I can use these shortcuts:

chmodd 0775 .
chmodf 0664 .

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

Could not create work tree dir 'example.com'.: Permission denied

You should logged in not as "root" user.

Or assign permission to your "current_user" to do this by using following command

sudo chown -R username.www-data /var/www

sudo chmod -R +rwx /var/www

Java: int[] array vs int array[]

No, there is no difference. But I prefer using int[] array as it is more readable.

Named colors in matplotlib

I constantly forget the names of the colors I want to use and keep coming back to this question =)

The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.

I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.

enter image description here

I really didn't change much from the matplotlib example, but here is the code for completeness.

import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

Additional named colors

Updated 2017-10-25. I merged my previous updates into this section.

xkcd

If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:

plt.plot([1,2], lw=4, c='xkcd:baby poop green')

Now you have access to a plethora of named colors!

enter image description here

Tableau

The default Tableau colors are available in matplotlib via the 'tab:' prefix:

plt.plot([1,2], lw=4, c='tab:green')

There are ten distinct colors:

enter image description here

HTML

You can also plot colors by their HTML hex code:

plt.plot([1,2], lw=4, c='#8f9805')

This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...


For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


How do I find the parent directory in C#?

No one has provided a solution that would work cross-form. I know it wasn't specifically asked but I am working in a linux environment where most of the solutions (as at the time I post this) would provide an error.

Hardcoding path separators (as well as other things) will give an error in anything but Windows systems.

In my original solution I used:

char filesep = Path.DirectorySeparatorChar;
string datapath = $"..{filesep}..{filesep}";

However after seeing some of the answers here I adjusted it to be:

string datapath = Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).FullName).FullName; 

What is __declspec and when do I need to use it?

I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec() can bee used at the same level as the export keyword.

/** Declare a public MRuby API function. */
#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif

How to receive serial data using android bluetooth

I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.

My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!

How do Python's any and all functions work?

>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True

How do I return a char array from a function?

You have to realize that char[10] is similar to a char* (see comment by @DarkDust). You are in fact returning a pointer. Now the pointer points to a variable (str) which is destroyed as soon as you exit the function, so the pointer points to... nothing!

Usually in C, you explicitly allocate memory in this case, which won't be destroyed when the function ends:

char* testfunc()
{
    char* str = malloc(10 * sizeof(char));
    return str;
}

Be aware though! The memory pointed at by str is now never destroyed. If you don't take care of this, you get something that is known as a 'memory leak'. Be sure to free() the memory after you are done with it:

foo = testfunc();
// Do something with your foo
free(foo); 

Node.js Web Application examples/tutorials

I would suggest you check out the various tutorials that are coming out lately. My current fav is:

http://nodetuts.com/

Hope this helps.

Google Chrome default opening position and size

You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

How to edit/save a file through Ubuntu Terminal

Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering

C# : changing listbox row color?

You will need to draw the item yourself. Change the DrawMode to OwnerDrawFixed and handle the DrawItem event.

/// <summary>
/// Handles the DrawItem event of the listBox1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
private void listBox1_DrawItem( object sender, DrawItemEventArgs e )
{
   e.DrawBackground();
   Graphics g = e.Graphics;

    // draw the background color you want
    // mine is set to olive, change it to whatever you want
    g.FillRectangle( new SolidBrush( Color.Olive), e.Bounds );

    // draw the text of the list item, not doing this will only show
    // the background color
    // you will need to get the text of item to display
    g.DrawString( THE_LIST_ITEM_TEXT , e.Font, new SolidBrush( e.ForeColor ), new PointF( e.Bounds.X, e.Bounds.Y) );

    e.DrawFocusRectangle();
}

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

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

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

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

array-fill

Swift error : signal SIGABRT how to solve it

In my case I wasn't getting error just the crash in the AppDelegate and I had to uncheck the next option: OS_ACTIVITY_MODE then I could get the real crash reason in my .xib file

enter image description here

Hope this can help you too :)

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

6 digits regular expression

  ^\d{1,6}$

....................

Repair all tables in one go

If corrupted tables remain after

mysqlcheck -A --auto-repair

try

mysqlcheck -A --auto-repair --use-frm

Undoing a 'git push'

you can use the command reset

git reset --soft HEAD^1

then:

git reset <files>
git commit --amend

and

git push -f

How can I write output from a unit test?

I'm using xUnit so this is what I use:

Debugger.Log(0, "1", input);

PS: you can use Debugger.Break(); too, so you can see your log in out.

Make 2 functions run at the same time

This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

import ray

ray.init()

# Define functions you want to execute in parallel using 
# the ray.remote decorator.
@ray.remote
def func1():
    print("Working")

@ray.remote
def func2():
    print("Working")

# Execute func1 and func2 in parallel.
ray.get([func1.remote(), func2.remote()])

If func1() and func2() return results, you need to rewrite the above code a bit, by replacing ray.get([func1.remote(), func2.remote()]) with:

ret_id1 = func1.remote()
ret_id2 = func1.remote()
ret1, ret2 = ray.get([ret_id1, ret_id2])

There are a number of advantages of using Ray over the multiprocessing module or using multithreading. In particular, the same code will run on a single machine as well as on a cluster of machines.

For more advantages of Ray see this related post.

Permission denied on CopyFile in VBS

I have read your problem, And i had the same problem. But af ter i changed some, my problem "Permission Denied" is solved.

Private Sub Addi_Click()
'On Error Resume Next
'call ds
browsers ("false")
Call makeAdir
ffgg = "C:\Users\Backups\user\" & User & "1\data\"
Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.Getfolder("c:\users\Backups\user\" & User & "1\data")
    f.Attributes = 0
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Call fso.Copyfile(filetarget, ffgg, True)

Look at ffgg = "C:\Users\Backups\user\" & User & "1\data\", Before I changed it was ffgg = "C:\Users\Backups\user\" & User & "1\data" When i add backslash after "\data\", my problem is solved. Try to add back slash. Maybe solved your problem. Good luck.

GET and POST methods with the same Action name in the same Controller

You can't have multiple actions with the same name. You could add a parameter to one method and that would be valid. For example:

    public ActionResult Index(int i)
    {
        Some Code--Some Code---Some Code
        return View();
    }

There are a few ways to do to have actions that differ only by request verb. My favorite and, I think, the easiest to implement is to use the AttributeRouting package. Once installed simply add an attribute to your method as follows:

  [GET("Resources")]
  public ActionResult Index()
  {
      return View();
  }

  [POST("Resources")]
  public ActionResult Create()
  {
      return RedirectToAction("Index");
  }

In the above example the methods have different names but the action name in both cases is "Resources". The only difference is the request verb.

The package can be installed using NuGet like this:

PM> Install-Package AttributeRouting

If you don't want the dependency on the AttributeRouting packages you could do this by writing a custom action selector attribute.

How can I generate a list of files with their absolute path in Linux?

Use this for dirs (the / after ** is needed in bash to limit it to directories):

ls -d -1 "$PWD/"**/

this for files and directories directly under the current directory, whose names contain a .:

ls -d -1 "$PWD/"*.*

this for everything:

ls -d -1 "$PWD/"**/*

Taken from here http://www.zsh.org/mla/users/2002/msg00033.html

In bash, ** is recursive if you enable shopt -s globstar.

How can I create my own comparator for a map?

std::map takes up to four template type arguments, the third one being a comparator. E.g.:

struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.length() < b.length();
    }
};

// ...
std::map<std::string, std::string, cmpByStringLength> myMap;

Alternatively you could also pass a comparator to maps constructor.

Note however that when comparing by length you can only have one string of each length in the map as a key.

How to get the EXIF data from a file using C#

Here is a link to another similar SO question, which has an answer pointing to this good article on "Reading, writing and photo metadata" in .Net.

How do I add a new class to an element dynamically?

Using CSS only, no. You need to use jQuery to add it.

Disable Enable Trigger SQL server for a table

Below is the simplest way

Try the code

ALTER TRIGGER trigger_name DISABLE

That's it :)

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

How can I set the max-width of a table cell using percentages?

the percent should be relative to an absolute size, try this :

_x000D_
_x000D_
table {
  width:200px;
}

td {
  width:65%;
  border:1px solid black;
}
_x000D_
<table>
  <tr>
    <td>Testasdas 3123 1 dasd as da</td>
    <td>A long string blah blah blah</td>
  </tr>
</table>
    
_x000D_
_x000D_
_x000D_

Can we execute a java program without a main() method?

You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

How to get Spinner value?

Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.

Convert and format a Date in JSP

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.Locale"%>

<html>
<head>
<title>Date Format</title>
</head>
<body>
<%
String stringDate = "Fri May 13 2011 19:59:09 GMT 0530";
Date stringDate1 = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.ENGLISH).parse(stringDate);
String stringDate2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(stringDate1);

out.println(stringDate2);
%>
</body>
</html>

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The issue is with this line

 xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

 xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text 

How to annotate MYSQL autoincrement field with JPA annotations

To use a MySQL AUTO_INCREMENT column, you are supposed to use an IDENTITY strategy:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

Which is what you'd get when using AUTO with MySQL:

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

Which is actually equivalent to

@Id @GeneratedValue
private Long id;

In other words, your mapping should work. But Hibernate should omit the id column in the SQL insert statement, and it is not. There must be a kind of mismatch somewhere.

Did you specify a MySQL dialect in your Hibernate configuration (probably MySQL5InnoDBDialect or MySQL5Dialect depending on the engine you're using)?

Also, who created the table? Can you show the corresponding DDL?

Follow-up: I can't reproduce your problem. Using the code of your entity and your DDL, Hibernate generates the following (expected) SQL with MySQL:

insert 
into
    Operator
    (active, password, username) 
values
    (?, ?, ?)

Note that the id column is absent from the above statement, as expected.

To sum up, your code, the table definition and the dialect are correct and coherent, it should work. If it doesn't for you, maybe something is out of sync (do a clean build, double check the build directory, etc) or something else is just wrong (check the logs for anything suspicious).

Regarding the dialect, the only difference between MySQL5Dialect or MySQL5InnoDBDialect is that the later adds ENGINE=InnoDB to the table objects when generating the DDL. Using one or the other doesn't change the generated SQL.

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

Instead of gdb, run gdbtui. Or run gdb with the -tui switch. Or press C-x C-a after entering gdb. Now you're in GDB's TUI mode.

Enter layout asm to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish etc. are abbreviated to a single key, allowing you to walk through your program very quickly.

   +---------------------------------------------------------------------------+
B+>|0x402670 <main>         push   %r15                                        |
   |0x402672 <main+2>       mov    %edi,%r15d                                  |
   |0x402675 <main+5>       push   %r14                                        |
   |0x402677 <main+7>       push   %r13                                        |
   |0x402679 <main+9>       mov    %rsi,%r13                                   |
   |0x40267c <main+12>      push   %r12                                        |
   |0x40267e <main+14>      push   %rbp                                        |
   |0x40267f <main+15>      push   %rbx                                        |
   |0x402680 <main+16>      sub    $0x438,%rsp                                 |
   |0x402687 <main+23>      mov    (%rsi),%rdi                                 |
   |0x40268a <main+26>      movq   $0x402a10,0x400(%rsp)                       |
   |0x402696 <main+38>      movq   $0x0,0x408(%rsp)                            |
   |0x4026a2 <main+50>      movq   $0x402510,0x410(%rsp)                       |
   +---------------------------------------------------------------------------+
child process 21518 In: main                            Line: ??   PC: 0x402670
(gdb) file /opt/j64-602/bin/jconsole
Reading symbols from /opt/j64-602/bin/jconsole...done.
(no debugging symbols found)...done.
(gdb) layout asm
(gdb) start
(gdb)

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

Simple!

System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));

Difference between Role and GrantedAuthority in Spring Security

Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.

Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.

Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.

On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)

The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.

Jake

Encrypt and Decrypt in Java

If you use a static key, encrypt and decrypt always give the same result;

public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");

String.format() to format double in java

If you want to format it with manually set symbols, use this:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols);
System.out.println(decimalFormat.format(1237516.2548)); //1,237,516.25

Locale-based formatting is preferred, though.

How to group time by hour or by 10 minutes

finally done with

GROUP BY
DATEPART(YEAR, DT.[Date]),
DATEPART(MONTH, DT.[Date]),
DATEPART(DAY, DT.[Date]),
DATEPART(HOUR, DT.[Date]),
(DATEPART(MINUTE, DT.[Date]) / 10)

git ahead/behind info between master and branch?

First of all to see how many revisions you are behind locally, you should do a git fetch to make sure you have the latest info from your remote.

The default output of git status tells you how many revisions you are ahead or behind, but usually I find this too verbose:

$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)

I prefer git status -sb:

$ git status -sb
## master...origin/master [ahead 2, behind 1]

In fact I alias this to simply git s, and this is the main command I use for checking status.

To see the diff in the "ahead revisions" of master, I can exclude the "behind revisions" from origin/master:

git diff master..origin/master^

To see the diff in the "behind revisions" of origin/master, I can exclude the "ahead revisions" from master:

git diff origin/master..master^^

If there are 5 revisions ahead or behind it might be easier to write like this:

git diff master..origin/master~5
git diff origin/master..master~5

UPDATE

To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname. My version is 1.8.4.3, but it's been working like this as long as I remember.

As of version 1.8, you can set the tracking branch like this:

git branch --track test-branch

As of version 1.7, the syntax was different:

git branch --set-upstream test-branch

MySQL Error 1215: Cannot add foreign key constraint

Error 1215 is an annoying one. Explosion Pill's answer covers the basics. You want to make sure to start from there. However, there are more, much more subtle cases to look out for:

For example, when you try to link up PRIMARY KEYs of different tables, make sure to provide proper ON UPDATE and ON DELETE options. E.g.:

...
PRIMARY KEY (`id`),
FOREIGN KEY (`id`) REFERENCES `t` (`other_id`) ON DELETE SET NULL
....

won't fly, because PRIMARY KEYs (such as id) can't be NULL.

I am sure, there are even more, similarly subtle issues when adding these sort of constraints, which is why when coming across constraint errors, always make sure that the constraints and their implications make sense in your current context. Good luck with your error 1215!

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

Core dumped, but core file is not in the current directory?

I could think of two following possibilities:

  1. As others have already pointed out, the program might chdir(). Is the user running the program allowed to write into the directory it chdir()'ed to? If not, it cannot create the core dump.

  2. For some weird reason the core dump isn't named core.* You can check /proc/sys/kernel/core_pattern for that. Also, the find command you named wouldn't find a typical core dump. You should use find / -name "*core.*", as the typical name of the coredump is core.$PID

Truncate string in Laravel blade templates

You can set string limit as below example:

<td>{{str_limit($biodata ->description, $limit = 20, $end = '...')}}</td>

It will display only the 20 letters including whitespaces and ends with ....

Example imageIt shows the example of string limit

How to match hyphens with Regular Expression?

[-a-z0-9]+,[a-z0-9-]+,[a-z-0-9]+ and also [a-z-0-9]+ all are same.The hyphen between two ranges considered as a symbol.And also [a-z0-9-+()]+ this regex allow hyphen.

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

How Do I Make Glyphicons Bigger? (Change Size?)

Increase the font-size of glyphicon to increase all icons size.

.glyphicon {
    font-size: 50px;
}

To target only one icon,

.glyphicon.glyphicon-globe {
    font-size: 75px;
}

How to improve Netbeans performance?

Also defragment your disk. Netbeans is very aggressive about creating caches of one form or another. Most of them get persisted to disk at some point or another which can affect startup time. Virus scanners (Symantec in particular), Desktop search engines, and any other intrusive I/O product can drastically reduce performance.

I have noticed that Netbeans can be tempermental at times and its performance can vary greatly between two machines with nearly identical specs. My work machine has terrible performance and is unusable at times, but it's lightning fast when I use it on my home machine (with bigger projects in many cases).

How to Set Active Tab in jQuery Ui

Just to clarify in complete detail. This is what works with the current version of jQuery Ui

$( "#tabs" ).tabs( "option", "active", # );

where # is the index of the tab you want to make active.

What is dtype('O'), in pandas?

When you see dtype('O') inside dataframe this means Pandas string.

What is dtype?

Something that belongs to pandas or numpy, or both, or something else? If we examine pandas code:

df = pd.DataFrame({'float': [1.0],
                    'int': [1],
                    'datetime': [pd.Timestamp('20180310')],
                    'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype

It will output like this:

   float  int   datetime string    
0    1.0    1 2018-03-10    foo
---
float64 int64 datetime64[ns] object
---
dtype('O')

You can interpret the last as Pandas dtype('O') or Pandas object which is Python type string, and this corresponds to Numpy string_, or unicode_ types.

Pandas dtype    Python type     NumPy type          Usage
object          str             string_, unicode_   Text

Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype for that.

Data type object is an instance of numpy.dtype class that understand the data type more precise including:

  • Type of the data (integer, float, Python object, etc.)
  • Size of the data (how many bytes is in e.g. the integer)
  • Byte order of the data (little-endian or big-endian)
  • If the data type is structured, an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float)
  • What are the names of the "fields" of the structure
  • What is the data-type of each field
  • Which part of the memory block each field takes
  • If the data type is a sub-array, what is its shape and data type

In the context of this question dtype belongs to both pands and numpy and in particular dtype('O') means we expect the string.


Here is some code for testing with explanation: If we have the dataset as dictionary

import pandas as pd
import numpy as np
from pandas import Timestamp

data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe

print(df)
print(df.dtypes)

The last lines will examine the dataframe and note the output:

   id       date                  role  num   fnum
0   1 2018-12-12               Support  123   3.14
1   2 2018-12-12             Marketing  234   2.14
2   3 2018-12-12  Business Development  345  -0.14
3   4 2018-12-12                 Sales  456  41.30
4   5 2018-12-12           Engineering  567   3.14
id               int64
date    datetime64[ns]
role            object
num              int64
fnum           float64
dtype: object

All kind of different dtypes

df.iloc[1,:] = np.nan
df.iloc[2,:] = None

But if we try to set np.nan or None this will not affect the original column dtype. The output will be like this:

print(df)
print(df.dtypes)

    id       date         role    num   fnum
0  1.0 2018-12-12      Support  123.0   3.14
1  NaN        NaT          NaN    NaN    NaN
2  NaN        NaT         None    NaN    NaN
3  4.0 2018-12-12        Sales  456.0  41.30
4  5.0 2018-12-12  Engineering  567.0   3.14
id             float64
date    datetime64[ns]
role            object
num            float64
fnum           float64
dtype: object

So np.nan or None will not change the columns dtype, unless we set the all column rows to np.nan or None. In that case column will become float64 or object respectively.

You may try also setting single rows:

df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object

And to note here, if we set string inside a non string column it will become string or object dtype.

How to get a tab character?

Sure there's an entity for tabs:

&#9;

(The tab is ASCII character 9, or Unicode U+0009.)

However, just like literal tabs (ones you type in to your text editor), all tab characters are treated as whitespace by HTML parsers and collapsed into a single space except those within a <pre> block, where literal tabs will be rendered as 8 spaces in a monospace font.

Downloading and unzipping a .zip file without writing to disk

I'd like to add my Python3 answer for completeness:

from io import BytesIO
from zipfile import ZipFile
import requests

def get_zip(file_url):
    url = requests.get(file_url)
    zipfile = ZipFile(BytesIO(url.content))
    zip_names = zipfile.namelist()
    if len(zip_names) == 1:
        file_name = zip_names.pop()
        extracted_file = zipfile.open(file_name)
        return extracted_file
    return [zipfile.open(file_name) for file_name in zip_names]

Eclipse add Tomcat 7 blank server name

I also had this problem today, and deleting files org.eclipse.jst.server.tomcat.core.prefs and org.eclipse.wst.server.core.prefs didn't work.

Finally I found it's permission issue:

By default <apache-tomcat-version>/conf/* can be read only by owner, after I made it readable for all, it works! So run this command:

chmod a+r <apache-tomcat-version>/conf/*

Here is the link where I found the root cause:

http://www.thecodingforums.com/threads/eclipse-cannot-create-tomcat-server.953960/#post-5058434

How do I open a URL from C++?

Create a function and copy the code using winsock which is mentioned already by Software_Developer.

For Instance:

#ifdef _WIN32

// this is required only for windows

if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{

  //...

}

#endif

winsock code here

#ifdef _WIN32

WSACleanup();

#endif

Angular ng-if="" with multiple arguments

It is possible.

<span ng-if="checked && checked2">
  I'm removed when the checkbox is unchecked.
</span>

http://plnkr.co/edit/UKNoaaJX5KG3J7AswhLV?p=preview

When should I use Async Controllers in ASP.NET MVC?

You may find my MSDN article on the subject helpful; I took a lot of space in that article describing when you should use async on ASP.NET, not just how to use async on ASP.NET.

I have some concerns using async actions in ASP.NET MVC. When it improves performance of my apps, and when - not.

First, understand that async/await is all about freeing up threads. On GUI applications, it's mainly about freeing up the GUI thread so the user experience is better. On server applications (including ASP.NET MVC), it's mainly about freeing up the request thread so the server can scale.

In particular, it won't:

  • Make your individual requests complete faster. In fact, they will complete (just a teensy bit) slower.
  • Return to the caller/browser when you hit an await. await only "yields" to the ASP.NET thread pool, not to the browser.

First question is - is it good to use async action everywhere in ASP.NET MVC?

I'd say it's good to use it everywhere you're doing I/O. It may not necessarily be beneficial, though (see below).

However, it's bad to use it for CPU-bound methods. Sometimes devs think they can get the benefits of async by just calling Task.Run in their controllers, and this is a horrible idea. Because that code ends up freeing up the request thread by taking up another thread, so there's no benefit at all (and in fact, they're taking the penalty of extra thread switches)!

Shall I use async/await keywords when I want to query database (via EF/NHibernate/other ORM)?

You could use whatever awaitable methods you have available. Right now most of the major players support async, but there are a few that don't. If your ORM doesn't support async, then don't try to wrap it in Task.Run or anything like that (see above).

Note that I said "you could use". If you're talking about ASP.NET MVC with a single database backend, then you're (almost certainly) not going to get any scalability benefit from async. This is because IIS can handle far more concurrent requests than a single instance of SQL server (or other classic RDBMS). However, if your backend is more modern - a SQL server cluster, Azure SQL, NoSQL, etc - and your backend can scale, and your scalability bottleneck is IIS, then you can get a scalability benefit from async.

Third question - How many times I can use await keywords to query database asynchronously in ONE single action method?

As many as you like. However, note that many ORMs have a one-operation-per-connection rule. In particular, EF only allows a single operation per DbContext; this is true whether the operation is synchronous or asynchronous.

Also, keep in mind the scalability of your backend again. If you're hitting a single instance of SQL Server, and your IIS is already capable of keeping SQLServer at full capacity, then doubling or tripling the pressure on SQLServer is not going to help you at all.

C#: calling a button event handler method without actually clicking the button

btnTest_Click(null, null);

Provided that the method isn't using either of these parameters (it's very common not to.)

To be honest though this is icky. If you have code that needs to be called you should follow the following convention:

protected void btnTest_Click(object sender, EventArgs e)
{
   SomeSub();
}

protected void SomeOtherFunctionThatNeedsToCallTheCode()
{
   SomeSub();
}

protected void SomeSub()
{
   // ...
}

Maven not found in Mac OSX mavericks

Maven is not installed any more by default on Mac OS X 10.9. You need to install it yourself, for example using Homebrew.

The command to install Maven using Homebrew is brew install maven

Convert char array to single int?

I'll just leave this here for people interested in an implementation with no dependencies.

inline int
stringLength (char *String)
    {
    int Count = 0;
    while (*String ++) ++ Count;
    return Count;
    }

inline int
stringToInt (char *String)
    {
    int Integer = 0;
    int Length = stringLength(String);
    for (int Caret = Length - 1, Digit = 1; Caret >= 0; -- Caret, Digit *= 10)
        {
        if (String[Caret] == '-') return Integer * -1;
        Integer += (String[Caret] - '0') * Digit;
        }

    return Integer;
    }

Works with negative values, but can't handle non-numeric characters mixed in between (should be easy to add though). Integers only.

Get the second highest value in a MySQL table

Try this one to get n th max salary

i have tried this before posting & It Works fine

eg. to find 10th max salary replace limit 9,1;

mysql> select name,salary from emp group by salary desc limit n-1,1;

LINQ to Entities how to update a record

In most cases @tster's answer will suffice. However, I had a scenario where I wanted to update a row without first retrieving it.

My situation is this: I've got a table where I want to "lock" a row so that only a single user at a time will be able to edit it in my app. I'm achieving this by saying

update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'

The reason being, if I were to simply retrieve the row by ID, change the properties and then save, I could end up with two people accessing the same row simultaneously. This way, I simply send and update claiming this row as mine, then I try to retrieve the row which has the same properties I just updated with. If that row exists, great. If, for some reason it doesn't (someone else's "lock" command got there first), I simply return FALSE from my method.

I do this by using context.Database.ExecuteSqlCommand which accepts a string command and an array of parameters.

Just wanted to add this answer to point out that there will be scenarios in which retrieving a row, updating it, and saving it back to the DB won't suffice and that there are ways of running a straight update statement when necessary.

JDK was not found on the computer for NetBeans 6.5

Do the following steps to resolve the problem

  1. Ensure that the JDK is already installed.

  2. If the installer is on a CD, Copy the EXE file for the Netbeans 6.5.1 installer onto your hard disk.

  3. Note the location of the installer.

  4. Open a Command Prompt running as administrator: Go to Start button > All Programs > Accessories Right click Command Prompt Select Run as administrator

  5. In the Command Prompt use the cd command to change to the directory containing the installer.

  6. Execute the following command to extract the contents of the installer: [Note: You might need to change the name of the installer to match the one you have.]

    netbeans-6.5.1-ml-java-windows.exe --extract

  7. Execute the following command to manually execute the installer:

    java -jar bundle.jar

You will see rapid scrolling output in the Command Prompt window for a few moments, then the installer window will appear to begin the installation process.

How to pass credentials to the Send-MailMessage command for sending emails

It took me a while to combine everything, make it a bit secure, and have it work with Gmail. I hope this answer saves someone some time.

Create a file with the encrypted server password:

In Powershell, enter the following command (replace myPassword with your actual password):

"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"

Create a powershell script (Ex. sendEmail.ps1):

$User = "[email protected]"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Email Subject" 
$Body = "Email body text" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\fileIwantToSend.csv"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password); 
$SMTPClient.Send($SMTPMessage)

Automate with Task Scheduler:

Create a batch file (Ex. emailFile.bat) with the following:

powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1

Create a task to run the batch file. Note: you must have the task run with the same user account that you used to encrypted the password! (Aka, probably the logged in user)

That's all; you now have a way to automate and schedule sending an email and an attachment with Windows Task Scheduler and Powershell. No 3rd party software and the password is not stored as plain text (though granted, not terribly secure either).

You can also read this article on the level of security this provides for your email password.

What is the purpose of willSet and didSet in Swift?

In your own (base) class, willSet and didSet are quite reduntant , as you could instead define a calculated property (i.e get- and set- methods) that access a _propertyVariable and does the desired pre- and post- prosessing.

If, however, you override a class where the property is already defined, then the willSet and didSet are useful and not redundant!

Passing an array of parameters to a stored procedure

You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.

CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
    DELETE YourTable
    FROM YourTable                    
    LEFT OUTER JOIN #temp T ON T.myid=s.id
    WHERE s.id IS NULL
END

Get div's offsetTop positions in React

A quicker way if you are using React 16.3 and above is by creating a ref in the constructor, then attaching it to the component you wish to use with as shown below.

...
constructor(props){
   ...
   //create a ref
   this.someRefName = React.createRef();

}

onScroll(){
let offsetTop = this.someRefName.current.offsetTop;

}

render(){
...
<Component ref={this.someRefName} />

}

Is there any native DLL export functions viewer?

you can use Dependency Walker to view the function name. you can see the function's parameters only if it's decorated. read the following from the FAQ:

How do I view the parameter and return types of a function? For most functions, this information is simply not present in the module. The Windows' module file format only provides a single text string to identify each function. There is no structured way to list the number of parameters, the parameter types, or the return type. However, some languages do something called function "decoration" or "mangling", which is the process of encoding information into the text string. For example, a function like int Foo(int, int) encoded with simple decoration might be exported as _Foo@8. The 8 refers to the number of bytes used by the parameters. If C++ decoration is used, the function would be exported as ?Foo@@YGHHH@Z, which can be directly decoded back to the function's original prototype: int Foo(int, int). Dependency Walker supports C++ undecoration by using the Undecorate C++ Functions Command.

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

You can use

str1.compareTo(str2);

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

E.g.,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1
"b".compareTo(null); // throws java.lang.NullPointerException

How can I get all a form's values that would be submitted without submitting

Thanks Chris. That's what I was looking for. However, note that the method is serialize(). And there is another method serializeArray() that looks very useful that I may use. Thanks for pointing me in the right direction.

var queryString = $('#frmAdvancedSearch').serialize();
alert(queryString);

var fieldValuePairs = $('#frmAdvancedSearch').serializeArray();
$.each(fieldValuePairs, function(index, fieldValuePair) {
    alert("Item " + index + " is [" + fieldValuePair.name + "," + fieldValuePair.value + "]");
});

Conda command is not recognized on Windows 10

Even I got the same problem when I've first installed Anaconda. It said 'conda' command not found.

So I've just setup two values[added two new paths of Anaconda] system environment variables in the PATH variable which are: C:\Users\mshas\Anaconda2\ & C:\Users\mshas\Anaconda2\Scripts

Lot of people forgot to add the second variable which is "Scripts" just add that then 'conda' command works.