Programs & Examples On #Project setup

Using Spring MVC Test to unit test multipart POST request

Have a look at this example taken from the spring MVC showcase, this is the link to the source code:

@RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {

    @Test
    public void readString() throws Exception {

        MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());

        webAppContextSetup(this.wac).build()
            .perform(fileUpload("/fileupload").file(file))
            .andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
    }

}

Modify property value of the objects in list using Java 8 streams

You can use peek to do that.

List<Fruit> newList = fruits.stream()
    .peek(f -> f.setName(f.getName() + "s"))
    .collect(Collectors.toList());

Adding a collaborator to my free GitHub account?

In the repository, click Admin, then go to the Collaborators tab.

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

For some reason, even if changing the iOS Deployment Target to 8.0 or higher, the Xib files don't adopt that change and remain with the previous settings in the File inspector

File inspector in the Xib after changing the iOS Deployment target

Therefore, you should change it manually for each Xib Afther the manual change

Once done, the warning will disappear :-)

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

Event for Handling the Focus of the EditText

when in kotlin it will look like this :

editText.setOnFocusChangeListener { view, hasFocus ->
        if (hasFocus) toast("focused") else toast("focuse lose")
    }

How to run Maven from another directory (without cd to project dir)?

I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:

user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$

As a bash function (which you could add to your ~/.bashrc):

function mvn-there() {
  DIR="$1"
  shift
  (cd $DIR; mvn "$@")     
} 

user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$

I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.

Regards

How can I make a clickable link in an NSAttributedString?

Just find a code-free solution for UITextView: enter image description here

Enable Detection->Links options, the URL and also email will be detected and clickable!

How to return first 5 objects of Array in Swift?

For an array of objects you can create an extension from Sequence.

extension Sequence {
    func limit(_ max: Int) -> [Element] {
        return self.enumerated()
            .filter { $0.offset < max }
            .map { $0.element }
    }
}

Usage:

struct Apple {}

let apples: [Apple] = [Apple(), Apple(), Apple()]
let limitTwoApples = apples.limit(2)

// limitTwoApples: [Apple(), Apple()]

Validation error: "No validator could be found for type: java.lang.Integer"

You can add hibernate validator dependency, to provide a Validator

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>

Java 8 Lambda function that throws exception?

You can use unthrow wrapper

Function<String, Integer> func1 = s -> Unthrow.wrap(() -> myMethod(s));

or

Function<String, Integer> func2 = s1 -> Unthrow.wrap((s2) -> myMethod(s2), s1);

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Red lines under the ViewBag was my headache for 3 month ). Just remove the Microsoft.CSharp reference from project and then add it again.

Read file content from S3 bucket with boto3

You might also consider the smart_open module, which supports iterators:

from smart_open import smart_open

# stream lines from an S3 object
for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
    print(line.decode('utf8'))

and context managers:

with smart_open('s3://mybucket/mykey.txt', 'rb') as s3_source:
    for line in s3_source:
         print(line.decode('utf8'))

    s3_source.seek(0)  # seek to the beginning
    b1000 = s3_source.read(1000)  # read 1000 bytes

Find smart_open at https://pypi.org/project/smart_open/

How to reject in async/await syntax?

Your best bet is to throw an Error wrapping the value, which results in a rejected promise with an Error wrapping the value:

} catch (error) {
    throw new Error(400);
}

You can also just throw the value, but then there's no stack trace information:

} catch (error) {
    throw 400;
}

Alternately, return a rejected promise with an Error wrapping the value, but it's not idiomatic:

} catch (error) {
    return Promise.reject(new Error(400));
}

(Or just return Promise.reject(400);, but again, then there's no context information.)

In your case, as you're using TypeScript and foo's return value is Promise<A>, you'd use this:

return Promise.reject<A>(400 /*or Error*/ );

In an async/await situation, that last is probably a bit of a semantic mis-match, but it does work.

If you throw an Error, that plays well with anything consuming your foo's result with await syntax:

try {
    await foo();
} catch (error) {
    // Here, `error` would be an `Error` (with stack trace, etc.).
    // Whereas if you used `throw 400`, it would just be `400`.
}

Auto number column in SharePoint list

it's in there by default. It's the id field.

How do I UPDATE from a SELECT in SQL Server?

If you use MySQL instead of SQL Server, the syntax is:

UPDATE Table1
INNER JOIN Table2
ON Table1.id = Table2.id
SET Table1.col1 = Table2.col1,
    Table1.col2 = Table2.col2

Stop and Start a service via batch or cmd file?

You can use the NET START command and then check the ERRORLEVEL environment variable, e.g.

net start [your service]
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%

Disclaimer: I've written this from the top of my head, but I think it'll work.

Android overlay a view ontop of everything?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id = "@+id/Everything"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <!-- other actual layout stuff here EVERYTHING HERE -->

   </LinearLayout>

<LinearLayout
    android:id="@+id/overlay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right" >
</LinearLayout>

Now any view you add under LinearLayout with android:id = "@+id/overlay" will appear as overlay with gravity = right on Linear Layout with android:id="@+id/Everything"

What is JavaScript's highest integer value that a number can go to without losing precision?

Scato wrotes:

anything you want to use for bitwise operations must be between 0x80000000 (-2147483648 or -2^31) and 0x7fffffff (2147483647 or 2^31 - 1).

the console will tell you that 0x80000000 equals +2147483648, but 0x80000000 & 0x80000000 equals -2147483648

Hex-Decimals are unsigned positive values, so 0x80000000 = 2147483648 - thats mathematically correct. If you want to make it a signed value you have to right shift: 0x80000000 >> 0 = -2147483648. You can write 1 << 31 instead, too.

Laravel 5.2 redirect back with success message

In Controller

return redirect()->route('company')->with('update', 'Content has been updated successfully!');

In view

@if (session('update'))
  <div class="alert alert-success alert-dismissable custom-success-box" style="margin: 15px;">
     <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
     <strong> {{ session('update') }} </strong>
  </div>
@endif

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.

enter image description here

So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.

In the below picture I highlighted the input boxes that I've modified: enter image description here

How to scroll up or down the page to an anchor using jQuery?

following solution worked for me:

$("a[href^=#]").click(function(e)
        {
            e.preventDefault();
            var aid = $(this).attr('href');
            console.log(aid);
            aid = aid.replace("#", "");
            var aTag = $("a[name='"+ aid +"']");
            if(aTag == null || aTag.offset() == null)
                aTag = $("a[id='"+ aid +"']");

            $('html,body').animate({scrollTop: aTag.offset().top}, 1000);
        }
    );

How do I invoke a Java method when given the method name as a string?

For those who want a straight-forward code example in Java 7:

Dog class:

package com.mypackage.bean;

public class Dog {
    private String name;
    private int age;

    public Dog() {
        // empty constructor
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void printDog(String name, int age) {
        System.out.println(name + " is " + age + " year(s) old.");
    }
}

ReflectionDemo class:

package com.mypackage.demo;

import java.lang.reflect.*;

public class ReflectionDemo {

    public static void main(String[] args) throws Exception {
        String dogClassName = "com.mypackage.bean.Dog";
        Class<?> dogClass = Class.forName(dogClassName); // convert string classname to class
        Object dog = dogClass.newInstance(); // invoke empty constructor

        String methodName = "";

        // with single parameter, return void
        methodName = "setName";
        Method setNameMethod = dog.getClass().getMethod(methodName, String.class);
        setNameMethod.invoke(dog, "Mishka"); // pass arg

        // without parameters, return string
        methodName = "getName";
        Method getNameMethod = dog.getClass().getMethod(methodName);
        String name = (String) getNameMethod.invoke(dog); // explicit cast

        // with multiple parameters
        methodName = "printDog";
        Class<?>[] paramTypes = {String.class, int.class};
        Method printDogMethod = dog.getClass().getMethod(methodName, paramTypes);
        printDogMethod.invoke(dog, name, 3); // pass args
    }
}

Output: Mishka is 3 year(s) old.


You can invoke the constructor with parameters this way:

Constructor<?> dogConstructor = dogClass.getConstructor(String.class, int.class);
Object dog = dogConstructor.newInstance("Hachiko", 10);

Alternatively, you can remove

String dogClassName = "com.mypackage.bean.Dog";
Class<?> dogClass = Class.forName(dogClassName);
Object dog = dogClass.newInstance();

and do

Dog dog = new Dog();

Method method = Dog.class.getMethod(methodName, ...);
method.invoke(dog, ...);

Suggested reading: Creating New Class Instances

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

Documentation for parseDouble() says "Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.", so they should be identical.

jQuery find events handlers registered with an object

You can do it by crawling the events (as of jQuery 1.8+), like this:

$.each($._data($("#id")[0], "events"), function(i, event) {
  // i is the event type, like "click"
  $.each(event, function(j, h) {
    // h.handler is the function being called
  });
});

Here's an example you can play with:

_x000D_
_x000D_
$(function() {_x000D_
  $("#el").click(function(){ alert("click"); });_x000D_
  $("#el").mouseover(function(){ alert("mouseover"); });_x000D_
_x000D_
  $.each($._data($("#el")[0], "events"), function(i, event) {_x000D_
    output(i);_x000D_
    $.each(event, function(j, h) {_x000D_
        output("- " + h.handler);_x000D_
    });_x000D_
  });_x000D_
});_x000D_
_x000D_
function output(text) {_x000D_
    $("#output").html(function(i, h) {_x000D_
        return h + text + "<br />";_x000D_
    });_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="el">Test</div>_x000D_
<code>_x000D_
    <span id="output"></span>_x000D_
</code>
_x000D_
_x000D_
_x000D_

How to use TLS 1.2 in Java 6

I also got a similar error when forced to use TLS1.2 for java 6. And I handled it thanks to this library:

  1. Clone Source Code: https://github.com/tobszarny/ssl-provider-jvm16

  2. Add Main Class:

    public static void main(String[] args) throws Exception {
        try {
            String apiUrl = "https://domain/api/query?test=123";
    
            URL myurl = new URL(apiUrl);
            HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
            con.setSSLSocketFactory(new TSLSocketConnectionFactory());
            int responseCode = con.getResponseCode();
            System.out.println("GET Response Code :: " + responseCode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

How to sort a HashMap in Java

If you want to combine a Map for efficient retrieval with a SortedMap, you may use the ConcurrentSkipListMap.

Of course, you need the key to be the value used for sorting.

ASP.NET MVC Html.DropDownList SelectedValue

The problems is that dropboxes don't work the same as listboxes, at least the way ASP.NET MVC2 design expects: A dropbox allows only zero or one values, as listboxes can have a multiple value selection. So, being strict with HTML, that value shouldn't be in the option list as "selected" flag, but in the input itself.

See the following example:

<select id="combo" name="combo" value="id2">
  <option value="id1">This is option 1</option>
  <option value="id2" selected="selected">This is option 2</option>
  <option value="id3">This is option 3</option>
</select>

<select id="listbox" name="listbox" multiple>
  <option value="id1">This is option 1</option>
  <option value="id2" selected="selected">This is option 2</option>
  <option value="id3">This is option 3</option>
</select>

The combo has the option selected, but also has its value attribute set. So, if you want ASP.NET MVC2 to render a dropbox and also have a specific value selected (i.e., default values, etc.), you should give it a value in the rendering, like this:

// in my view             
<%=Html.DropDownList("UserId", selectListItems /* (SelectList)ViewData["UserId"]*/, new { @Value = selectedUser.Id } /* Your selected value as an additional HTML attribute */)%>

Android "elevation" not showing a shadow

Apparently, you cannot just set an elevation on a View and have it appear. You also need to specify a background.

The following lines added to my LinearLayout finally showed a shadow:

android:background="@android:color/white"
android:elevation="10dp"

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

If you are using numpy, you can perform extended slicing like that:

>>> import numpy
>>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> Idx = [0, 3, 7]
>>> a[Idx]
array(['a', 'd', 'h'], 
      dtype='|S1')

...and is probably much faster (if performance is enough of a concern to to bother with the numpy import)

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

How to get the GL library/headers?

What operating system?

Here on Ubuntu, I have

$ dpkg -S /usr/include/GL/gl.h 
mesa-common-dev: /usr/include/GL/gl.h
$ 

but not the difference in a) capitalization and b) forward/backward slashes. Your example is likely to be wrong in its use of backslashes.

Emulating a do-while loop in Bash

Two simple solutions:

  1. Execute your code once before the while loop

    actions() {
       check_if_file_present
       # Do other stuff
    }
    
    actions #1st execution
    while [ current_time <= $cutoff ]; do
       actions # Loop execution
    done
    
  2. Or:

    while : ; do
        actions
        [[ current_time <= $cutoff ]] || break
    done
    

How to convert Calendar to java.sql.Date in Java?

I found this code works:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");    
Calendar calendar = new GregorianCalendar(2013,0,31);
System.out.println(sdf.format(calendar.getTime()));  

you can find the rest in this tutorial:
http://www.mkyong.com/java/java-date-and-calendar-examples/

GROUP BY and COUNT in PostgreSQL

There is also EXISTS:

SELECT count(*) AS post_ct
FROM   posts p
WHERE  EXISTS (SELECT FROM votes v WHERE v.post_id = p.id);

In Postgres and with multiple entries on the n-side like you probably have, it's generally faster than count(DISTINCT post_id):

SELECT count(DISTINCT p.id) AS post_ct
FROM   posts p
JOIN   votes v ON v.post_id = p.id;

The more rows per post there are in votes, the bigger the difference in performance. Test with EXPLAIN ANALYZE.

count(DISTINCT post_id) has to read all rows, sort or hash them, and then only consider the first per identical set. EXISTS will only scan votes (or, preferably, an index on post_id) until the first match is found.

If every post_id in votes is guaranteed to be present in the table posts (referential integrity enforced with a foreign key constraint), this short form is equivalent to the longer form:

SELECT count(DISTINCT post_id) AS post_ct
FROM   votes;

May actually be faster than the EXISTS query with no or few entries per post.

The query you had works in simpler form, too:

SELECT count(*) AS post_ct
FROM  (
    SELECT FROM posts 
    JOIN   votes ON votes.post_id = posts.id 
    GROUP  BY posts.id
    ) sub;

Benchmark

To verify my claims I ran a benchmark on my test server with limited resources. All in a separate schema:

Test setup

Fake a typical post / vote situation:

CREATE SCHEMA y;
SET search_path = y;

CREATE TABLE posts (
  id   int PRIMARY KEY
, post text
);

INSERT INTO posts
SELECT g, repeat(chr(g%100 + 32), (random()* 500)::int)  -- random text
FROM   generate_series(1,10000) g;

DELETE FROM posts WHERE random() > 0.9;  -- create ~ 10 % dead tuples

CREATE TABLE votes (
  vote_id serial PRIMARY KEY
, post_id int REFERENCES posts(id)
, up_down bool
);

INSERT INTO votes (post_id, up_down)
SELECT g.* 
FROM  (
   SELECT ((random()* 21)^3)::int + 1111 AS post_id  -- uneven distribution
        , random()::int::bool AS up_down
   FROM   generate_series(1,70000)
   ) g
JOIN   posts p ON p.id = g.post_id;

All of the following queries returned the same result (8093 of 9107 posts had votes).
I ran 4 tests with EXPLAIN ANALYZE ant took the best of five on Postgres 9.1.4 with each of the three queries and appended the resulting total runtimes.

  1. As is.

  2. After ..

    ANALYZE posts;
    ANALYZE votes;
    
  3. After ..

    CREATE INDEX foo on votes(post_id);
    
  4. After ..

    VACUUM FULL ANALYZE posts;
    CLUSTER votes using foo;
    

count(*) ... WHERE EXISTS

  1. 253 ms
  2. 220 ms
  3. 85 ms -- winner (seq scan on posts, index scan on votes, nested loop)
  4. 85 ms

count(DISTINCT x) - long form with join

  1. 354 ms
  2. 358 ms
  3. 373 ms -- (index scan on posts, index scan on votes, merge join)
  4. 330 ms

count(DISTINCT x) - short form without join

  1. 164 ms
  2. 164 ms
  3. 164 ms -- (always seq scan)
  4. 142 ms

Best time for original query in question:

  • 353 ms

For simplified version:

  • 348 ms

@wildplasser's query with a CTE uses the same plan as the long form (index scan on posts, index scan on votes, merge join) plus a little overhead for the CTE. Best time:

  • 366 ms

Index-only scans in the upcoming PostgreSQL 9.2 can improve the result for each of these queries, most of all for EXISTS.

Related, more detailed benchmark for Postgres 9.5 (actually retrieving distinct rows, not just counting):

Swift - how to make custom header for UITableView?

The best working Solution of adding Custom header view in UITableView for section in swift 4 is --

1 first Use method ViewForHeaderInSection as below -

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))

        let label = UILabel()
        label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
        label.text = "Notification Times"
        label.font = UIFont().futuraPTMediumFont(16) // my custom font
        label.textColor = UIColor.charcolBlackColour() // my custom colour

        headerView.addSubview(label)

        return headerView
    }

2 Also Don't forget to set Height of the header using heightForHeaderInSection UITableView method -

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

and you're all set Check it here in image

How to concatenate a std::string and an int?

If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age).

Another way is to use stringstreams:

std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;

A third approach would be to use sprintf or snprintf from the C library.

char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;

Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.

How To Set Up GUI On Amazon EC2 Ubuntu server

This can be done. Following are the steps to setup the GUI

Create new user with password login

sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui

sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes

sudo /etc/init.d/ssh restart

Setting up ui based ubuntu machine on AWS.

In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:

sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server

Then run following commands and enter the login password for vnc connection:

su - awsgui

vncserver

vncserver -kill :1

vim /home/awsgui/.vnc/xstartup

Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads

exec sh /etc/X11/xinit/xinitrc. 

When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.

Then start vnc server again.

vncserver

You can download xtightvncviewer to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients

In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.

Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html

Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/

Port opening on console

sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT

If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.

vncserver

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

How to retrieve unique count of a field using Kibana + Elastic Search

Be aware with Unique count you are using 'cardinality' metric, which does not always guarantee exact unique count. :-)

the cardinality metric is an approximate algorithm. It is based on the HyperLogLog++ (HLL) algorithm. HLL works by hashing your input and using the bits from the hash to make probabilistic estimations on the cardinality.

Depending on amount of data I can get differences of 700+ entries missing in a 300k dataset via Unique Count in Elastic which are otherwise really unique.

Read more here: https://www.elastic.co/guide/en/elasticsearch/guide/current/cardinality.html

How do I remove javascript validation from my eclipse project?

Go to Windows->Preferences->Validation.

There would be a list of validators with checkbox options for Manual & Build, go and individually disable the javascript validator there.

If you select the Suspend All Validators checkbox on the top it doesn't necessarily take affect.

iOS9 Untrusted Enterprise Developer with no option to trust

Do it like this:

Enter image description here

Go to Settings -> General -> Profiles - tap on your Profile - tap on the Trust button.

but iOS10 has a little change,

Users should go to Settings - General - Device Management - tap on your Profile - tap on Trust button.

enter image description here

Reference: iOS10AdaptationTips

Algorithm to return all combinations of k elements from n

Following Haskell code calculate the combination number and combinations at the same time, and thanks to Haskell's laziness, you can get one part of them without calculating the other.

import Data.Semigroup
import Data.Monoid

data Comb = MkComb {count :: Int, combinations :: [[Int]]} deriving (Show, Eq, Ord)

instance Semigroup Comb where
    (MkComb c1 cs1) <> (MkComb c2 cs2) = MkComb (c1 + c2) (cs1 ++ cs2)

instance Monoid Comb where
    mempty = MkComb 0 []

addElem :: Comb -> Int -> Comb
addElem (MkComb c cs) x = MkComb c (map (x :) cs)

comb :: Int -> Int -> Comb
comb n k | n < 0 || k < 0 = error "error in `comb n k`, n and k should be natural number"
comb n k | k == 0 || k == n = MkComb 1 [(take k [k-1,k-2..0])]
comb n k | n < k = mempty
comb n k = comb (n-1) k <> (comb (n-1) (k-1) `addElem` (n-1))

It works like:

*Main> comb 0 1
MkComb {count = 0, combinations = []}

*Main> comb 0 0
MkComb {count = 1, combinations = [[]]}

*Main> comb 1 1
MkComb {count = 1, combinations = [[0]]}

*Main> comb 4 2
MkComb {count = 6, combinations = [[1,0],[2,0],[2,1],[3,0],[3,1],[3,2]]}

*Main> count (comb 10 5)
252

How to maximize a plt.show() window using Python

import matplotlib.pyplot as plt
def maximize():
    plot_backend = plt.get_backend()
    mng = plt.get_current_fig_manager()
    if plot_backend == 'TkAgg':
        mng.resize(*mng.window.maxsize())
    elif plot_backend == 'wxAgg':
        mng.frame.Maximize(True)
    elif plot_backend == 'Qt4Agg':
        mng.window.showMaximized()

Then call function maximize() before plt.show()

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How to create a JSON object

Usually, you would do something like this:

$post_data = json_encode(array('item' => $post_data));

But, as it seems you want the output to be with "{}", you better make sure to force json_encode() to encode as object, by passing the JSON_FORCE_OBJECT constant.

$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);

"{}" brackets specify an object and "[]" are used for arrays according to JSON specification.

Naming threads and thread-pools of ExecutorService

Using the existing functionality of Executors.defaultThreadFactory() but just setting the name:

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class NamingThreadFactory implements ThreadFactory {
    private final String prefix;
    private int threadNuber = 0;

    public NamingThreadFactory(String prefix){
        this.prefix = prefix;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = Executors.defaultThreadFactory().newThread(r);
        t.setName(prefix + threadNuber);
        return t;
    }
}

How do you perform a left outer join using linq extension methods

Whilst the accepted answer works and is good for Linq to Objects it bugged me that the SQL query isn't just a straight Left Outer Join.

The following code relies on the LinkKit Project that allows you to pass expressions and invoke them to your query.

static IQueryable<TResult> LeftOuterJoin<TSource,TInner, TKey, TResult>(
     this IQueryable<TSource> source, 
     IQueryable<TInner> inner, 
     Expression<Func<TSource,TKey>> sourceKey, 
     Expression<Func<TInner,TKey>> innerKey, 
     Expression<Func<TSource, TInner, TResult>> result
    ) {
    return from a in source.AsExpandable()
            join b in inner on sourceKey.Invoke(a) equals innerKey.Invoke(b) into c
            from d in c.DefaultIfEmpty()
            select result.Invoke(a,d);
}

It can be used as follows

Table1.LeftOuterJoin(Table2, x => x.Key1, x => x.Key2, (x,y) => new { x,y});

How to run a program without an operating system?

Runnable examples

Let's create and run some minuscule bare metal hello world programs that run without an OS on:

We will also try them out on the QEMU emulator as much as possible, as that is safer and more convenient for development. The QEMU tests have been on an Ubuntu 18.04 host with the pre-packaged QEMU 2.11.1.

The code of all x86 examples below and more is present on this GitHub repo.

How to run the examples on x86 real hardware

Remember that running examples on real hardware can be dangerous, e.g. you could wipe your disk or brick the hardware by mistake: only do this on old machines that don't contain critical data! Or even better, use cheap semi-disposable devboards such as the Raspberry Pi, see the ARM example below.

For a typical x86 laptop, you have to do something like:

  1. Burn the image to an USB stick (will destroy your data!):

    sudo dd if=main.img of=/dev/sdX
    
  2. plug the USB on a computer

  3. turn it on

  4. tell it to boot from the USB.

    This means making the firmware pick USB before hard disk.

    If that is not the default behavior of your machine, keep hitting Enter, F12, ESC or other such weird keys after power-on until you get a boot menu where you can select to boot from the USB.

    It is often possible to configure the search order in those menus.

For example, on my T430 I see the following.

After turning on, this is when I have to press Enter to enter the boot menu:

enter image description here

Then, here I have to press F12 to select the USB as the boot device:

enter image description here

From there, I can select the USB as the boot device like this:

enter image description here

Alternatively, to change the boot order and choose the USB to have higher precedence so I don't have to manually select it every time, I would hit F1 on the "Startup Interrupt Menu" screen, and then navigate to:

enter image description here

Boot sector

On x86, the simplest and lowest level thing you can do is to create a Master Boot Sector (MBR), which is a type of boot sector, and then install it to a disk.

Here we create one with a single printf call:

printf '\364%509s\125\252' > main.img
sudo apt-get install qemu-system-x86
qemu-system-x86_64 -hda main.img

Outcome:

enter image description here

Note that even without doing anything, a few characters are already printed on the screen. Those are printed by the firmware, and serve to identify the system.

And on the T430 we just get a blank screen with a blinking cursor:

enter image description here

main.img contains the following:

  • \364 in octal == 0xf4 in hex: the encoding for a hlt instruction, which tells the CPU to stop working.

    Therefore our program will not do anything: only start and stop.

    We use octal because \x hex numbers are not specified by POSIX.

    We could obtain this encoding easily with:

    echo hlt > a.S
    as -o a.o a.S
    objdump -S a.o
    

    which outputs:

    a.o:     file format elf64-x86-64
    
    
    Disassembly of section .text:
    
    0000000000000000 <.text>:
       0:   f4                      hlt
    

    but it is also documented in the Intel manual of course.

  • %509s produce 509 spaces. Needed to fill in the file until byte 510.

  • \125\252 in octal == 0x55 followed by 0xaa.

    These are 2 required magic bytes which must be bytes 511 and 512.

    The BIOS goes through all our disks looking for bootable ones, and it only considers bootable those that have those two magic bytes.

    If not present, the hardware will not treat this as a bootable disk.

If you are not a printf master, you can confirm the contents of main.img with:

hd main.img

which shows the expected:

00000000  f4 20 20 20 20 20 20 20  20 20 20 20 20 20 20 20  |.               |
00000010  20 20 20 20 20 20 20 20  20 20 20 20 20 20 20 20  |                |
*
000001f0  20 20 20 20 20 20 20 20  20 20 20 20 20 20 55 aa  |              U.|
00000200

where 20 is a space in ASCII.

The BIOS firmware reads those 512 bytes from the disk, puts them into memory, and sets the PC to the first byte to start executing them.

Hello world boot sector

Now that we have made a minimal program, let's move to a hello world.

The obvious question is: how to do IO? A few options:

  • ask the firmware, e.g. BIOS or UEFI, to do it for us

  • VGA: special memory region that gets printed to the screen if written to. Can be used in Protected Mode.

  • write a driver and talk directly to the display hardware. This is the "proper" way to do it: more powerful, but more complex.

  • serial port. This is a very simple standardized protocol that sends and receives characters from a host terminal.

    On desktops, it looks like this:

    enter image description here

    Source.

    It is unfortunately not exposed on most modern laptops, but is the common way to go for development boards, see the ARM examples below.

    This is really a shame, since such interfaces are really useful to debug the Linux kernel for example.

  • use debug features of chips. ARM calls theirs semihosting for example. On real hardware, it requires some extra hardware and software support, but on emulators it can be a free convenient option. Example.

Here we will do a BIOS example as it is simpler on x86. But note that it is not the most robust method.

main.S

.code16
    mov $msg, %si
    mov $0x0e, %ah
loop:
    lodsb
    or %al, %al
    jz halt
    int $0x10
    jmp loop
halt:
    hlt
msg:
    .asciz "hello world"

GitHub upstream.

link.ld

SECTIONS
{
    /* The BIOS loads the code from the disk to this location.
     * We must tell that to the linker so that it can properly
     * calculate the addresses of symbols we might jump to.
     */
    . = 0x7c00;
    .text :
    {
        __start = .;
        *(.text)
        /* Place the magic boot bytes at the end of the first 512 sector. */
        . = 0x1FE;
        SHORT(0xAA55)
    }
}

Assemble and link with:

as -g -o main.o main.S
ld --oformat binary -o main.img -T link.ld main.o
qemu-system-x86_64 -hda main.img

Outcome:

enter image description here

And on the T430:

enter image description here

Tested on: Lenovo Thinkpad T430, UEFI BIOS 1.16. Disk generated on an Ubuntu 18.04 host.

Besides the standard userland assembly instructions, we have:

  • .code16: tells GAS to output 16-bit code

  • cli: disable software interrupts. Those could make the processor start running again after the hlt

  • int $0x10: does a BIOS call. This is what prints the characters one by one.

The important link flags are:

  • --oformat binary: output raw binary assembly code, don't wrap it inside an ELF file as is the case for regular userland executables.

To better understand the linker script part, familiarize yourself with the relocation step of linking: What do linkers do?

Cooler x86 bare metal programs

Here are a few more complex bare metal setups that I've achieved:

Use C instead of assembly

Summary: use GRUB multiboot, which will solve a lot of annoying problems you never thought about. See the section below.

The main difficulty on x86 is that the BIOS only loads 512 bytes from the disk to memory, and you are likely to blow up those 512 bytes when using C!

To solve that, we can use a two-stage bootloader. This makes further BIOS calls, which load more bytes from the disk into memory. Here is a minimal stage 2 assembly example from scratch using the int 0x13 BIOS calls:

Alternatively:

  • if you only need it to work in QEMU but not real hardware, use the -kernel option, which loads an entire ELF file into memory. Here is an ARM example I've created with that method.
  • for the Raspberry Pi, the default firmware takes care of the image loading for us from an ELF file named kernel7.img, much like QEMU -kernel does.

For educational purposes only, here is a one stage minimal C example:

main.c

void main(void) {
    int i;
    char s[] = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
    for (i = 0; i < sizeof(s); ++i) {
        __asm__ (
            "int $0x10" : : "a" ((0x0e << 8) | s[i])
        );
    }
    while (1) {
        __asm__ ("hlt");
    };
}

entry.S

.code16
.text
.global mystart
mystart:
    ljmp $0, $.setcs
.setcs:
    xor %ax, %ax
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %ss
    mov $__stack_top, %esp
    cld
    call main

linker.ld

ENTRY(mystart)
SECTIONS
{
  . = 0x7c00;
  .text : {
    entry.o(.text)
    *(.text)
    *(.data)
    *(.rodata)
    __bss_start = .;
    /* COMMON vs BSS: https://stackoverflow.com/questions/16835716/bss-vs-common-what-goes-where */
    *(.bss)
    *(COMMON)
    __bss_end = .;
  }
  /* https://stackoverflow.com/questions/53584666/why-does-gnu-ld-include-a-section-that-does-not-appear-in-the-linker-script */
  .sig : AT(ADDR(.text) + 512 - 2)
  {
      SHORT(0xaa55);
  }
  /DISCARD/ : {
    *(.eh_frame)
  }
  __stack_bottom = .;
  . = . + 0x1000;
  __stack_top = .;
}

run

set -eux
as -ggdb3 --32 -o entry.o entry.S
gcc -c -ggdb3 -m16 -ffreestanding -fno-PIE -nostartfiles -nostdlib -o main.o -std=c99 main.c
ld -m elf_i386 -o main.elf -T linker.ld entry.o main.o
objcopy -O binary main.elf main.img
qemu-system-x86_64 -drive file=main.img,format=raw

C standard library

Things get more fun if you also want to use the C standard library however, since we don't have the Linux kernel, which implements much of the C standard library functionality through POSIX.

A few possibilities, without going to a full-blown OS like Linux, include:

  • Write your own. It's just a bunch of headers and C files in the end, right? Right??

  • Newlib

    Detailed example at: https://electronics.stackexchange.com/questions/223929/c-standard-libraries-on-bare-metal/223931

    Newlib implements all the boring non-OS specific things for you, e.g. memcmp, memcpy, etc.

    Then, it provides some stubs for you to implement the syscalls that you need yourself.

    For example, we can implement exit() on ARM through semihosting with:

    void _exit(int status) {
        __asm__ __volatile__ ("mov r0, #0x18; ldr r1, =#0x20026; svc 0x00123456");
    }
    

    as shown at in this example.

    For example, you could redirect printf to the UART or ARM systems, or implement exit() with semihosting.

  • embedded operating systems like FreeRTOS and Zephyr.

    Such operating systems typically allow you to turn off pre-emptive scheduling, therefore giving you full control over the runtime of the program.

    They can be seen as a sort of pre-implemented Newlib.

GNU GRUB Multiboot

Boot sectors are simple, but they are not very convenient:

  • you can only have one OS per disk
  • the load code has to be really small and fit into 512 bytes
  • you have to do a lot of startup yourself, like moving into protected mode

It is for those reasons that GNU GRUB created a more convenient file format called multiboot.

Minimal working example: https://github.com/cirosantilli/x86-bare-metal-examples/tree/d217b180be4220a0b4a453f31275d38e697a99e0/multiboot/hello-world

I also use it on my GitHub examples repo to be able to easily run all examples on real hardware without burning the USB a million times.

QEMU outcome:

enter image description here

T430:

enter image description here

If you prepare your OS as a multiboot file, GRUB is then able to find it inside a regular filesystem.

This is what most distros do, putting OS images under /boot.

Multiboot files are basically an ELF file with a special header. They are specified by GRUB at: https://www.gnu.org/software/grub/manual/multiboot/multiboot.html

You can turn a multiboot file into a bootable disk with grub-mkrescue.

Firmware

In truth, your boot sector is not the first software that runs on the system's CPU.

What actually runs first is the so-called firmware, which is a software:

  • made by the hardware manufacturers
  • typically closed source but likely C-based
  • stored in read-only memory, and therefore harder / impossible to modify without the vendor's consent.

Well known firmwares include:

  • BIOS: old all-present x86 firmware. SeaBIOS is the default open source implementation used by QEMU.
  • UEFI: BIOS successor, better standardized, but more capable, and incredibly bloated.
  • Coreboot: the noble cross arch open source attempt

The firmware does things like:

  • loop over each hard disk, USB, network, etc. until you find something bootable.

    When we run QEMU, -hda says that main.img is a hard disk connected to the hardware, and hda is the first one to be tried, and it is used.

  • load the first 512 bytes to RAM memory address 0x7c00, put the CPU's RIP there, and let it run

  • show things like the boot menu or BIOS print calls on the display

Firmware offers OS-like functionality on which most OS-es depend. E.g. a Python subset has been ported to run on BIOS / UEFI: https://www.youtube.com/watch?v=bYQ_lq5dcvM

It can be argued that firmwares are indistinguishable from OSes, and that firmware is the only "true" bare metal programming one can do.

As this CoreOS dev puts it:

The hard part

When you power up a PC, the chips that make up the chipset (northbridge, southbridge and SuperIO) are not yet initialized properly. Even though the BIOS ROM is as far removed from the CPU as it could be, this is accessible by the CPU, because it has to be, otherwise the CPU would have no instructions to execute. This does not mean that BIOS ROM is completely mapped, usually not. But just enough is mapped to get the boot process going. Any other devices, just forget it.

When you run Coreboot under QEMU, you can experiment with the higher layers of Coreboot and with payloads, but QEMU offers little opportunity to experiment with the low level startup code. For one thing, RAM just works right from the start.

Post BIOS initial state

Like many things in hardware, standardization is weak, and one of the things you should not rely on is the initial state of registers when your code starts running after BIOS.

So do yourself a favor and use some initialization code like the following: https://stackoverflow.com/a/32509555/895245

Registers like %ds and %es have important side effects, so you should zero them out even if you are not using them explicitly.

Note that some emulators are nicer than real hardware and give you a nice initial state. Then when you go run on real hardware, everything breaks.

El Torito

Format that can be burnt to CDs: https://en.wikipedia.org/wiki/El_Torito_%28CD-ROM_standard%29

It is also possible to produce a hybrid image that works on either ISO or USB. This is can be done with grub-mkrescue (example), and is also done by the Linux kernel on make isoimage using isohybrid.

ARM

In ARM, the general ideas are the same.

There is no widely available semi-standardized pre-installed firmware like BIOS for us to use for the IO, so the two simplest types of IO that we can do are:

  • serial, which is widely available on devboards
  • blink the LED

I have uploaded:

Some differences from x86 include:

  • IO is done by writing to magic addresses directly, there is no in and out instructions.

    This is called memory mapped IO.

  • for some real hardware, like the Raspberry Pi, you can add the firmware (BIOS) yourself to the disk image.

    That is a good thing, as it makes updating that firmware more transparent.

Resources

Change CSS properties on click

<div id="foo">hello world!</div>
<img src="zoom.png" id="click_me" />

JS

$('#click_me').click(function(){
  $('#foo').css({
    'background-color':'red',
    'color':'white',
    'font-size':'44px'
  });
});

Visual Studio 2010 shortcut to find classes and methods?

Visual Studio 2010 has the "Navigate To" command, which might be what you are looking for. The default keyboard shortcut is CTRL + ,. Here is an overview of some of the options for navigating in Visual Studio 2010.

Passing properties by reference in C#

If you want to get and set the property both, you can use this in C#7:

GetString(
    inputString,
    (() => client.WorkPhone, x => client.WorkPhone = x))

void GetString(string inValue, (Func<string> get, Action<string> set) outValue)
{
    if (!string.IsNullOrEmpty(outValue))
    {
        outValue.set(inValue);
    }
}

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

Passing parameters to JavaScript files

No, you cant really do this by adding variables to the querystring portion of the JS file URL. If its writing the portion of code to parse the string that bothers you, perhaps another way would be to json encode your variables and put them in something like the rel attribute of the tag? I don't know how valid this is in terms of HTML validation, if thats something you're very worried about. Then you just need to find the rel attribute of the script and then json_decode that.

eg

<script type='text/javascript' src='file.js' rel='{"myvar":"somevalue","anothervar":"anothervalue"}'></script>

What's the right way to decode a string that has special HTML entities in it?

This is so good answer. You can use this with angular like this:

 moduleDefinitions.filter('sanitize', ['$sce', function($sce) {
    return function(htmlCode) {
        var txt = document.createElement("textarea");
        txt.innerHTML = htmlCode;
        return $sce.trustAsHtml(txt.value);
    }
}]);

Allow user to select camera or gallery for image

this code will help you, in that there is two button one for Camera and another for Gallery, and Image will be displayed in ImageView

https://github.com/siddhpuraamitr/Choose-Image-From-Gallery-Or-Camera

How to add text to a WPF Label in code?

I believe you want to set the Content property. This has more information on what is available to a label.

Sorting by date & time in descending order?

This is one of the simplest ways to sort record by Date:

SELECT  `Article_Id` ,  `Title` ,  `Source_Link` ,  `Content` ,  `Source` , `Reg_Date`, UNIX_TIMESTAMP(  `Reg_Date` ) AS DATE
FROM article
ORDER BY DATE DESC 

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

Just little addition.

Found another reincarnation in mysql.connector ver 8.0.16 It now requires allow_local_infile=True or you will see the above error. Worked in prior versions.

conn = mysql.connector.connect(host=host, user=user, passwd=passwd, database=database, allow_local_infile=True)

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

I think jQuery cannot find the element.

First of all find the element

var rowTemplate= document.getElementsByName("rowTemplate");

or

var rowTemplate = document.getElementById("rowTemplate"); 

or

var rowTemplate = $('#rowTemplate');

Then try your code again

rowTemplate.html().replace(....)

What is the difference between iterator and iterable and how to use them?

In addition to ColinD and Seeker answers.

In simple terms, Iterable and Iterator are both interfaces provided in Java's Collection Framework.

Iterable

A class has to implement the Iterable interface if it wants to have a for-each loop to iterate over its collection. However, the for-each loop can only be used to cycle through the collection in the forward direction and you won't be able to modify the elements in this collection. But, if all you want is to read the elements data, then it's very simple and thanks to Java lambda expression it's often one liner. For example:

iterableElements.forEach (x -> System.out.println(x) );

Iterator

This interface enables you to iterate over a collection, obtaining and removing its elements. Each of the collection classes provides a iterator() method that returns an iterator to the start of the collection. The advantage of this interface over iterable is that with this interface you can add, modify or remove elements in a collection. But, accessing elements needs a little more code than iterable. For example:

for (Iterator i = c.iterator(); i.hasNext(); ) {
       Element e = i.next();    //Get the element
       System.out.println(e);    //access or modify the element
}

Sources:

  1. Java Doc Iterable
  2. Java Doc Iterator

What is the difference between typeof and instanceof and when should one be used vs. the other?

One more case is that You only can collate with instanceof - it returns true or false. With typeof you can get type of provided something

How to know if a DateTime is between a DateRange in C#

Usually I create Fowler's Range implementation for such things.

public interface IRange<T>
{
    T Start { get; }
    T End { get; }
    bool Includes(T value);
    bool Includes(IRange<T> range);
}

public class DateRange : IRange<DateTime>         
{
    public DateRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }

    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public bool Includes(DateTime value)
    {
        return (Start <= value) && (value <= End);
    }

    public bool Includes(IRange<DateTime> range)
    {
        return (Start <= range.Start) && (range.End <= End);
    }
}

Usage is pretty simple:

DateRange range = new DateRange(startDate, endDate);
range.Includes(date)

How to implement common bash idioms in Python?

As of 2015 and Python 3.4's release, there's now a reasonably complete user-interactive shell available at: http://xon.sh/ or https://github.com/scopatz/xonsh

The demonstration video does not show pipes being used, but they ARE supported when in the default shell mode.

Xonsh ('conch') tries very hard to emulate bash, so things you've already gained muscle memory for, like

env | uniq | sort -r | grep PATH

or

my-web-server 2>&1 | my-log-sorter

will still work fine.

The tutorial is quite lengthy and seems to cover a significant amount of the functionality someone would generally expect at a ash or bash prompt:

  • Compiles, Evaluates, & Executes!
  • Command History and Tab Completion
  • Help & Superhelp with ? & ??
  • Aliases & Customized Prompts
  • Executes Commands and/or *.xsh Scripts which can also be imported
  • Environment Variables including Lookup with ${}
  • Input/Output Redirection and Combining
  • Background Jobs & Job Control
  • Nesting Subprocesses, Pipes, and Coprocesses
  • Subprocess-mode when a command exists, Python-mode otherwise
  • Captured Subprocess with $(), Uncaptured Subprocess with $[], Python Evaluation with @()
  • Filename Globbing with * or Regular Expression Filename Globbing with Backticks

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also http://gitref.org/basic/#add

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }

   if(lines > 0) {
     // Do rest of program.
   }
}

How to print a number with commas as thousands separators in JavaScript

I thought I'd share a little trick which I'm using for large number formatting. Instead of inserting commas or spaces, I insert an empty but visible span in between the "thousands". This makes thousands easily visible, but it allows to copy/paste the input in the original format, without commas/spaces.

// This function accepts an integer, and produces a piece of HTML that shows it nicely with 
// some empty space at "thousand" markers. 
// Note, these space are not spaces, if you copy paste, they will not be visible.
function valPrettyPrint(orgVal) {
  // Save after-comma text, if present
  var period = orgVal.indexOf(".");
  var frac = period >= 0 ? orgVal.substr(period) : "";
  // Work on input as an integer
  var val = "" + Math.trunc(orgVal);
  var res = "";
  while (val.length > 0) {
    res = val.substr(Math.max(0, val.length - 3), 3) + res;
    val = val.substr(0, val.length - 3);
    if (val.length > 0) {
        res = "<span class='thousandsSeparator'></span>" + res;
    }
  }
  // Add the saved after-period information
  res += frac;
  return res;
}

With this CSS:

.thousandsSeparator {
  display : inline;
  padding-left : 4px;
}

See an example JSFiddle.

Updating a date in Oracle SQL table

Just to add to Alex Poole's answer, here is how you do the date and time:

    TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss')

jQuery: Wait/Delay 1 second without executing code

delay() doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeout which others have mentioned.

The purpose of jQuery's delay() is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250); will make the element fade in after 3 seconds.

What is DOM element?

DOM is a logical model that can be implemented in any convenient manner.It is based on an object structure that closely resembles the structure of the documents it models.

For More Information on DOM : Click Here

Best way to import Observable from rxjs

Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize


Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of, 
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay, 
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck, 
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take, 
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap: flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.


Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

Iterating Through a Dictionary in Swift

You can also use values.makeIterator() to iterate over dict values, like this:

for sb in sbItems.values.makeIterator(){
  // do something with your sb item..
  print(sb)
}

You can also do the iteration like this, in a more swifty style:

sbItems.values.makeIterator().forEach{
  // $0 is your dict value..
  print($0) 
}

sbItems is dict of type [String : NSManagedObject]

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

Unable to establish SSL connection, how do I fix my SSL cert?

SSL23_GET_SERVER_HELLO:unknown protocol

This error happens when OpenSSL receives something other than a ServerHello in a protocol version it understands from the server. It can happen if the server answers with a plain (unencrypted) HTTP. It can also happen if the server only supports e.g. TLS 1.2 and the client does not understand that protocol version. Normally, servers are backwards compatible to at least SSL 3.0 / TLS 1.0, but maybe this specific server isn't (by implementation or configuration).

It is unclear whether you attempted to pass --no-check-certificate or not. I would be rather surprised if that would work.

A simple test is to use wget (or a browser) to request http://example.com:443 (note the http://, not https://); if it works, SSL is not enabled on port 443. To further debug this, use openssl s_client with the -debug option, which right before the error message dumps the first few bytes of the server response which OpenSSL was unable to parse. This may help to identify the problem, especially if the server does not answer with a ServerHello message. To see what exactly OpenSSL is expecting, check the source: look for SSL_R_UNKNOWN_PROTOCOL in ssl/s23_clnt.c.

In any case, looking at the apache error log may provide some insight too.

How do I get the current username in Windows PowerShell?

I thought it would be valuable to summarize and compare the given answers.

If you want to access the environment variable:

(easier/shorter/memorable option)

  • [Environment]::UserName -- @ThomasBratt
  • $env:username -- @Eoin
  • whoami -- @galaktor

If you want to access the Windows access token:

(more dependable option)

  • [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -- @MarkSeemann

If you want the name of the logged in user

(rather than the name of the user running the PowerShell instance)

  • $(Get-WMIObject -class Win32_ComputerSystem | select username).username -- @TwonOfAn on this other forum

Comparison

@Kevin Panko's comment on @Mark Seemann's answer deals with choosing one of the categories over the other:

[The Windows access token approach] is the most secure answer, because $env:USERNAME can be altered by the user, but this will not be fooled by doing that.

In short, the environment variable option is more succinct, and the Windows access token option is more dependable.

I've had to use @Mark Seemann's Windows access token approach in a PowerShell script that I was running from a C# application with impersonation.

The C# application is run with my user account, and it runs the PowerShell script as a service account. Because of a limitation of the way I'm running the PowerShell script from C#, the PowerShell instance uses my user account's environment variables, even though it is run as the service account user.

In this setup, the environment variable options return my account name, and the Windows access token option returns the service account name (which is what I wanted), and the logged in user option returns my account name.


Testing

Also, if you want to compare the options yourself, here is a script you can use to run a script as another user. You need to use the Get-Credential cmdlet to get a credential object, and then run this script with the script to run as another user as argument 1, and the credential object as argument 2.

Usage:

$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred

Contents of Run-AsUser.ps1 script:

param(
  [Parameter(Mandatory=$true)]
  [string]$script,
  [Parameter(Mandatory=$true)]
  [System.Management.Automation.PsCredential]$cred
)

Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"

Loop Through All Subfolders Using VBA

Just a simple folder drill down.

sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "C:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
    Next
End Sub

How do change the color of the text of an <option> within a <select>?

_x000D_
_x000D_
<select id="select">_x000D_
    <optgroup label="select one option">_x000D_
        <option>one</option>  _x000D_
        <option>two</option>  _x000D_
        <option>three</option>  _x000D_
        <option>four</option>  _x000D_
        <option>five</option>_x000D_
    </optgroup>_x000D_
</select>
_x000D_
_x000D_
_x000D_

It all sounded like a lot of hard work to me, when optgroup gives you what you need - at least I think it does.

Tkinter example code for multiple windows, why won't buttons load correctly?

You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

Quick fix: add the frame new as the first argument to your Button in Demo2.

Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

class Demo2(tk.Toplevel):     
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.title("Demo 2")
        self.button = tk.Button(self, text="Button 2", # specified self as master
                                width=25, command=self.close_window)
        self.button.pack()

    def close_window(self):
        self.destroy()

Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

How do I load an HTML page in a <div> using JavaScript?

showhide.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript">
        function showHide(switchTextDiv, showHideDiv)
        {
          var std = document.getElementById(switchTextDiv);
          var shd = document.getElementById(showHideDiv);
          if (shd.style.display == "block")
          {
            shd.style.display = "none";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
          }
          else
          {
            if (shd.innerHTML.length <= 0)
            {
              shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
            }
            shd.style.display = "block";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
          }
        }
      </script>
    </head>
    <body>
      <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
        <span style="display: block; background-color: yellow">Show</span>
      </a>
      <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
    </body>
</html>

showhide_embedded.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript"> 
        function load()
        {
          var ts = document.getElementById("theString");
          ts.scrollIntoView(true);
        }
      </script>
    </head>
    <body onload="load()">
      <pre>
        some text 1
        some text 2
        some text 3
        some text 4
        some text 5
        <span id="theString" style="background-color: yellow">some text 6 highlight</span>
        some text 7
        some text 8
        some text 9
      </pre>
    </body>
</html>

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

For the query to be legal in SQL92, the name column must be omitted from the select list or named in the GROUP BY clause.

SQL99 and later permits such nonaggregates per optional feature T301 if they are functionally dependent on GROUP BY columns: If such a relationship exists between name and custid, the query is legal. This would be the case, for example, were custid a primary key of customers.

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.

via MySQL :: MySQL 5.7 Reference Manual :: 12.19.3 MySQL Handling of GROUP BY

You can solve it by changing the sql mode with this command:

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

and ... remember to reconnect the database!!!

Examples of good gotos in C or C++

I don't use goto's myself, however I did work with a person once that would use them in specific cases. If I remember correctly, his rationale was around performance issues - he also had specific rules for how. Always in the same function, and the label was always BELOW the goto statement.

How to find index position of an element in a list when contains returns true

int indexOf(Object o) This method returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

You can do something like this, very simple and efficient solution: What i did was actually use a parameter instead of basic placeholder, created a SqlParameter object and used another existing execution method. For e.g in your scenario:

string sql = "INSERT INTO mssqltable (varbinarycolumn) VALUES (@img)";
SqlParameter param = new SqlParameter("img", arraytoinsert); //where img is your parameter name in the query
ExecuteStoreCommand(sql, param);

This should work like a charm, provided you have an open sql connection established.

Why is a div with "display: table-cell;" not affected by margin?

Table cells don't respect margin, but you could use transparent borders instead:

div {
  display: table-cell;
  border: 5px solid transparent;
}

Note: you can't use percentages here... :(

Python, Unicode, and the Windows console

TL;DR:

print(yourstring.encode('ascii','replace'));

I ran into this myself, working on a Twitch chat (IRC) bot. (Python 2.7 latest)

I wanted to parse chat messages in order to respond...

msg = s.recv(1024).decode("utf-8")

but also print them safely to the console in a human-readable format:

print(msg.encode('ascii','replace'));

This corrected the issue of the bot throwing UnicodeEncodeError: 'charmap' errors and replaced the unicode characters with ?.

How to Implement Custom Table View Section Headers and Footers with Storyboard

I used to do the following to create header/footer views lazily:

  • Add a freeform view controller for the section header/footer to the storyboard
  • Handle all stuff for the header in the view controller
  • In the table view controller provide a mutable array of view controllers for the section headers/footers repopulated with [NSNull null]
  • In viewForHeaderInSection/viewForFooterInSection if view controller does not yet exist, create it with storyboards instantiateViewControllerWithIdentifier, remember it in the array and return the view controllers view

Get the Last Inserted Id Using Laravel Eloquent

You can get last inserted id with same object you call save method;

$data->save();
$inserted_id = $data->id;

So you can simply write:

if ($data->save()) {
    return Response::json(array('success' => true,'inserted_id'=>$data->id), 200);
}

Instagram how to get my user id from username?

Although it's not listed on the API doc page anymore, I found a thread that mentions that you can use self in place of user-id for the users/{user-id} endpoint and it'll return the currently authenticated user's info.

So, users/self is the same as an explicit call to users/{some-user-id} and contains the user's id as part of the payload. Once you're authenticated, just make a call to users/self and the result will include the currently authenticated user's id, like so:

{
    "data": {
        "id": "1574083",
        "username": "snoopdogg",
        "full_name": "Snoop Dogg",
        "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
        "bio": "This is my bio",
        "website": "http://snoopdogg.com",
        "counts": {
            "media": 1320,
            "follows": 420,
            "followed_by": 3410
        }
}

How to declare a global variable in C++

Declare extern int x; in file.h. And define int x; only in one cpp file.cpp.

How remove border around image in css?

it's a good idea to use a reset CSS. add this at the top of your CSS file

img, a {border:none, outline: none;}

hope this helps

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

For some people, the accepted answer is not working, I found this other answer and it is working for me: How can I pass a parameter to a setTimeout() callback?

var hello = "Hello World";
setTimeout(alert, 1000, hello); 

'hello' is the parameter being passed, you can pass all the parameters after the timeout time. Thanks to @Fabio Phms for the answer.

Should C# or C++ be chosen for learning Games Programming (consoles)?

C++ is the lingua franca of the console game industry. For better or worse, you must know it to be a professional console game programmer.

How to store a command in a variable in a shell script?

Use eval:

x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"

if else condition in blade file (laravel 5.3)

No curly braces required you can directly write

@if($user->status =='waiting')         
      <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>         
@else
      <td>{{ $user->status }}</td>        
@endif

Dynamic button click event handler

Some code for a variation on this problem. Using the above code got me my click events as needed, but I was then stuck trying to work out which button had been clicked. My scenario is I have a dynamic amount of tab pages. On each tab page are (all dynamically created) 2 charts, 2 DGVs and a pair of radio buttons. Each control has a unique name relative to the tab, but there could be 20 radio buttons with the same name if I had 20 tab pages. The radio buttons switch between which of the 2 graphs and DGVs you get to see. Here is the code for when one of the radio buttons gets checked (There's a nearly identical block that swaps the charts and DGVs back):

   Private Sub radioFit_Components_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    If sender.name = "radioFit_Components" And sender.visible Then
        If sender.checked Then
            For Each ctrl As Control In TabControl1.SelectedTab.Controls
                Select Case ctrl.Name
                    Case "embChartSSE_Components"
                        ctrl.BringToFront()
                    Case "embChartSSE_Fit_Curve"
                        ctrl.SendToBack()
                    Case "dgvFit_Components"
                        ctrl.BringToFront()
                End Select
            Next

        End If
    End If

End Sub

This code will fire for any of the tab pages and swap the charts and DGVs over on any of the tab pages. The sender.visible check is to stop the code firing when the form is being created.

Difference between abstract class and interface in Python

In a more basic way to explain: An interface is sort of like an empty muffin pan. It's a class file with a set of method definitions that have no code.

An abstract class is the same thing, but not all functions need to be empty. Some can have code. It's not strictly empty.

Why differentiate: There's not much practical difference in Python, but on the planning level for a large project, it could be more common to talk about interfaces, since there's no code. Especially if you're working with Java programmers who are accustomed to the term.

RecyclerView onClick

Don't reinvent the wheel! The code for this specific use case is included in the Master/Detail Flow starter project that comes with Android Studio.

From Android Studio select:

  1. File > New > New Project....
  2. In the Phone and Tablet tab select Master/Detail Flow as shown below.

enter image description here

  1. Create the project as either Kotlin or Java.
  2. Profit.

I am not going to include here the code from google's ootb the demo project, but I'll outline the main design approaches in the sample provided by google:

  • the item OnClickListener is created ONLY ONCE, and is assigned to a field in your RecyclerView.Adapter implementation.
  • in the onBindViewHolder() you should set the same, pre-created onClickListener object on your ViewHolder instance with holder.itemView.setOnClickListener(mOnClickListener) (AVOID creating a new instance on every method call!); if you need to capture clicks on some specific elements inside the ViewHolder then extend ViewHolder and expose the elements you need as fields so that you can attach whatever listeners you need in onBindViewHolder() — and once again, do NOT re-create the listeners on every method call — initialise them as instance fields and attach them as needed.
  • you can use .setTag() in order to pass state to your viewHolder, e.g. holder.itemView.setTag(mValues.get(position)); as used in the demo.

What is the difference between "INNER JOIN" and "OUTER JOIN"?

1.Inner Join: Also called as Join. It returns the rows present in both the Left table, and right table only if there is a match. Otherwise, it returns zero records.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
INNER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output1

2.Full Outer Join: Also called as Full Join. It returns all the rows present in both the Left table, and right table.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
FULL OUTER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output2

3.Left Outer join: Or simply called as Left Join. It returns all the rows present in the Left table and matching rows from the right table (if any).

4.Right Outer Join: Also called as Right Join. It returns matching rows from the left table (if any), and all the rows present in the Right table.

joins

Advantages of Joins

  1. Executes faster.

How to check sbt version?

From within the sbt shell

sbt:venkat> about
[info] This is sbt 1.3.3
...

jQuery if statement to check visibility

 $('#column-left form').hide();
 $('.show-search').click(function() {
    $('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
    $('#column-left form').hide(); 
    if(!($('#column-left form').is(":visible"))) {
        $("#offers").show();
    } else {
        $('#offers').hide();
    }
  });

Eloquent get only one column as an array

I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().

// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();

These methods can also be called on a Collection for example

// <= Laravel 5.1
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->lists('word_one');

// >= Laravel 5.2
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->pluck('word_one');

Altering a column to be nullable

This depends on what SQL Engine you are using, in Sybase your command works fine:

ALTER TABLE Merchant_Pending_Functions 
Modify NumberOfLocations NULL;

Run R script from command line

One more way of running an R script from the command line would be:

R < scriptName.R --no-save  

or with --save.

See also What's the best way to use R scripts on the command line (terminal)?.

How can I declare enums using java

Quite simply as follows:

/**
 * @author The Elite Gentleman
 *
 */
public enum MyEnum {
    ONE("one"), TWO("two")
    ;
    private final String value;

    private MyEnum(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return getValue();
    }
}

For more info, visit Enum Types from Oracle Java Tutorials. Also, bear in mind that enums have private constructor.


Update, since you've updated your post, I've changed my value from an int to a String.
Related: Java String enum.

Postgresql - change the size of a varchar column to lower length

There's a description of how to do this at Resize a column in a PostgreSQL table without changing data. You have to hack the database catalog data. The only way to do this officially is with ALTER TABLE, and as you've noted that change will lock and rewrite the entire table while it's running.

Make sure you read the Character Types section of the docs before changing this. All sorts of weird cases to be aware of here. The length check is done when values are stored into the rows. If you hack a lower limit in there, that will not reduce the size of existing values at all. You would be wise to do a scan over the whole table looking for rows where the length of the field is >40 characters after making the change. You'll need to figure out how to truncate those manually--so you're back some locks just on oversize ones--because if someone tries to update anything on that row it's going to reject it as too big now, at the point it goes to store the new version of the row. Hilarity ensues for the user.

VARCHAR is a terrible type that exists in PostgreSQL only to comply with its associated terrible part of the SQL standard. If you don't care about multi-database compatibility, consider storing your data as TEXT and add a constraint to limits its length. Constraints you can change around without this table lock/rewrite problem, and they can do more integrity checking than just the weak length check.

Inserting code in this LaTeX document with indentation

Here is how to add inline code:

You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command

\newcommand{\code}[1]{\texttt{#1}}

Also, note that code blocks can be loaded from other files with

\lstinputlisting[breaklines]{source.c}

breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.

Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:

\documentclass{article}

\usepackage{minted}

\begin{document}
  This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

Tracking changes in Windows registry

PhiLho has mentioned AutoRuns in passing, but I think it deserves elaboration.

It doesn't scan the whole registry, just the parts containing references to things which get loaded automatically (EXEs, DLLs, drivers etc.) which is probably what you are interested in. It doesn't track changes but can export to a text file, so you can run it before and after installation and do a diff.

Checking if a textbox is empty in Javascript

function valid(id)
    {
        var textVal=document.getElementById(id).value;
        if (!textVal.match("Tryit") 
        {
            alert("Field says Tryit");
            return false;
        } 
        else 
        {
            return true;
        }
     }

Use this for expressing things

IE7 Z-Index Layering Issues

This bug seems to be somewhat of a separate issue than the standard separate stacking context IE bug. I had a similar issue with multiple stacked inputs (essentially a table with an autocompleter in each row). The only solution I found was to give each cell a decreasing z-index value.

creating Hashmap from a JSON String

In Java we can do it using the following statement . We need to use Jackson ObjectMapper for the same and provide the HashMap.class as the mapping class. Finally store the result as a HashMap object.

HashMap<String,String> hashMap = new ObjectMapper().readValue(jsonString, HashMap.class);

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

What is the most efficient way to store tags in a database?

One item is going to have many tags. And one tag will belong to many items. This implies to me that you'll quite possibly need an intermediary table to overcome the many-to-many obstacle.

Something like:

Table: Items
Columns: Item_ID, Item_Title, Content

Table: Tags
Columns: Tag_ID, Tag_Title

Table: Items_Tags
Columns: Item_ID, Tag_ID

It might be that your web app is very very popular and need de-normalizing down the road, but it's pointless muddying the waters too early.

How much does it cost to develop an iPhone application?

I am a very good iPhone app developer, and I charge over $150 per hour for my services. I have a ton of experience building iPhone apps and their server side components. I have also been called in on several occasions to fix offshore developed apps. Here's my take.

  • Design costs money, good design costs lots of money. Expect several designer weeks of work per app screen. Offshore teams do not do design.
  • Server development and infrastructure is critical if the app is to succeed. A slow server response, or an overloaded server will hamper your app, and crimp sales and satisfaction. The server side of the equation will cost the most and take the most time to develop. Those who offshore their server development will find that quality and uptime are both terrible, in my experience.
  • App development if done right takes time too. A professional developer will ensure all HIG rules are followed, the app is properly structured and contains no known errors, it performs well, and it passes the app store validations. Offshore teams just cut code.

I'm just about to release a shopping app for a client. The design work was done by 2 client in-house designers over 2 weeks, quick because they had all the image assets already. Think 2 people x 10 days x 8 hours = ~$24,000. The server side had to be modified to provide data for the iPhone app. We used their in-house team and in-house platform and in-house API, 2 developers, 4 weeks, or about $50,000 and that's because they already have a web shop and API. Cost them about $400,000 to get there (excluding platform). And I wrote the app side in 3 weeks, given that a lot of my code is duplicated from previous projects, another ~$25,000, the cheapest app I ever did.

Total spent: ~$100,000, and that's insanely cheap!

And they will give this away for free so clients will buy from their store from their iPhones.

For your app, Peter, if you have the servers and the APIs and the design, I'd guess at $30,000 to $60,000 depending on complexity. If you do not have the design, double it. If you do not have the APIs, double again...

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

Good beginners tutorial to socket.io?

To start with Socket.IO I suggest you read first the example on the main page:

http://socket.io/

On the server side, read the "How to use" on the GitHub source page:

https://github.com/Automattic/socket.io

And on the client side:

https://github.com/Automattic/socket.io-client

Finally you need to read this great tutorial:

http://howtonode.org/websockets-socketio

Hint: At the end of this blog post, you will have some links pointing on source code that could be some help.

How do I set default values for functions parameters in Matlab?

After becoming aware of ASSIGNIN (thanks to this answer by b3) and EVALIN I wrote two functions to finally obtain a very simple calling structure:

setParameterDefault('fTrue', inline('0'));

Here's the listing:

function setParameterDefault(pname, defval)
% setParameterDefault(pname, defval)
% Author: Tobias Kienzler (https://stackoverflow.com/users/321973)
% sets the parameter NAMED pname to the value defval if it is undefined or
% empty

if ~isParameterDefined('pname')
    error('paramDef:noPname', 'No parameter name defined!');
elseif ~isvarname(pname)
    error('paramDef:pnameNotChar', 'pname is not a valid varname!');
elseif ~isParameterDefined('defval')
    error('paramDef:noDefval', ['No default value for ' pname ' defined!']);
end;

% isParameterNotDefined copy&pasted since evalin can't handle caller's
% caller...
if ~evalin('caller',  ['exist(''' pname ''', ''var'') && ~isempty(' pname ')'])
    callername = evalin('caller', 'mfilename');
    warnMsg = ['Setting ' pname ' to default value'];
    if isscalar(defval) || ischar(defval) || isvector(defval)
        warnMsg = [warnMsg ' (' num2str(defval) ')'];
    end;
    warnMsg = [warnMsg '!'];
    warning([callername ':paramDef:assigning'], warnMsg);
    assignin('caller', pname, defval);
end

and

function b = isParameterDefined(pname)
% b = isParameterDefined(pname)
% Author: Tobias Kienzler (https://stackoverflow.com/users/321973)
% returns true if a parameter NAMED pname exists in the caller's workspace
% and if it is not empty

b = evalin('caller',  ['exist(''' pname ''', ''var'') && ~isempty(' pname ')']) ;

How to add a custom HTTP header to every WCF call?

This works for me

TestService.ReconstitutionClient _serv = new TestService.TestClient();

using (OperationContextScope contextScope = new OperationContextScope(_serv.InnerChannel))
{
   HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();

   requestMessage.Headers["apiKey"] = ConfigurationManager.AppSettings["apikey"]; 
   OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = 
      requestMessage;
   _serv.Method(Testarg);
}

laravel the requested url was not found on this server

Make sure you have mod_rewrite enabled.

restart apache

and clear cookies of your browser for read again at .htaccess

Can't push to GitHub because of large file which I already deleted

I have tried all above methods but none of them work for me.

Then I came up with my own solution.

  1. First of all, you need a clean, up-to-date local repo. Delete all the fucking large files.

  2. Now create a new folder OUTSIDE of your repo folder and use "Git create repository here" to make it a new Git repository, let's call it new_local_repo. This is it! All above methods said you have to clean the history..., well, I'm sick of that, let's create a new repo which has no history at all!

  3. Copy the files from your old, fucked up local repo to the new, beautiful repo. Note that the green logo on the folder icon will disappear, this is promising because this is a new repo!

  4. Commit to the local branch and then push to remote new branch. Let's call it new_remote_branch. If you don't know how to push from a new local repo, Google it.

  5. Congrats! You have pushed your clean, up-to-date code to GitHub. If you don't need the remote master branch anymore, you can make your new_remote_branch as new master branch. If you don't know how to do it, Google it.

  6. Last step, it's time to delete the fucked up old local repo. In the future you only use the new_local_repo.

Remove all git files from a directory?

How to remove all .git directories under a folder in Linux.

Run this find command, it will list all .git directories under the current folder:

find . -type d -name ".git" \
&& find . -name ".gitignore" \
&& find . -name ".gitmodules"

Prints:

./.git
./.gitmodules
./foobar/.git
./footbar2/.git
./footbar2/.gitignore

There should only be like 3 or 4 .git directories because git only has one .git folder for every project. You can rm -rf yourpath each of the above by hand.

If you feel like removing them all in one command and living dangerously:

//Retrieve all the files named ".git" and pump them into 'rm -rf'
//WARNING if you don't understand why/how this command works, DO NOT run it!

( find . -type d -name ".git" \
  && find . -name ".gitignore" \
  && find . -name ".gitmodules" ) | xargs rm -rf

//WARNING, if you accidentally pipe a `.` or `/` or other wildcard
//into xargs rm -rf, then the next question you will have is: "why is
//the bash ls command not found?  Requiring an OS reinstall.

Laravel view not found exception

I had the same error. I created a directory under views direcotry named users and created an index.blade.php file in it. When calling this file you should write users.index to indicate your path. Or just create index.blade.php file under views. hope this will help someone who gets the same problem

Complex numbers usage in python

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

How can getContentResolver() be called in Android?

getContentResolver() is method of class android.content.Context, so to call it you definitely need an instance of Context ( Activity or Service for example).

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

Using set_time_limit(0) is useless when using php-fpm or similar process manager.

Bottomline is not to use set_time_limit when using php-fpm, to increase your execution timeout, check this tutorial.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

pass $connect as your first parameter in mysqli_real_escape_string for this first make connection then do rest.read here http://php.net/manual/en/mysqli.real-escape-string.php

How can I trim beginning and ending double quotes from a string?

Kotlin

In Kotlin you can use String.removeSurrounding(delimiter: CharSequence)

E.g.

string.removeSurrounding("\"")

Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter. Otherwise returns this string unchanged.

The source code looks like this:

public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)

public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
    if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
        return substring(prefix.length, length - suffix.length)
    }
    return this
}

Vertically align text next to an image?

On a button in jQuery mobile, for instance, you can tweak it a bit by applying this style to the image:

.btn-image {
    vertical-align:middle;
    margin:0 0 3px 0;
}

How to use CMAKE_INSTALL_PREFIX

That should be (see the docs):

cmake -DCMAKE_INSTALL_PREFIX=/usr ..

How to find length of dictionary values

To find all of the lengths of the values in a dictionary you can do this:

lengths = [len(v) for v in d.values()]

How can I add an item to a IEnumerable<T> collection?

Others have already given great explanations regarding why you can not (and should not!) be able to add items to an IEnumerable. I will only add that if you are looking to continue coding to an interface that represents a collection and want an add method, you should code to ICollection or IList. As an added bonanza, these interfaces implement IEnumerable.

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

Split (explode) pandas dataframe string entry to separate rows

Similar question as: pandas: How do I split text in a column into multiple rows?

You could do:

>> a=pd.DataFrame({"var1":"a,b,c d,e,f".split(),"var2":[1,2]})
>> s = a.var1.str.split(",").apply(pd.Series, 1).stack()
>> s.index = s.index.droplevel(-1)
>> del a['var1']
>> a.join(s)
   var2 var1
0     1    a
0     1    b
0     1    c
1     2    d
1     2    e
1     2    f

How can I add raw data body to an axios request?

axios({
  method: 'post',     //put
  url: url,
  headers: {'Authorization': 'Bearer'+token}, 
  data: {
     firstName: 'Keshav', // This is the body part
     lastName: 'Gera'
  }
});

If (Array.Length == 0)

Jon Skeet answered correctly. Just remember that the order of the test in the "IF" is important. Check for the null before the length. I also prefer to put the null on the left side of the equal which is a habit I got from Java that made the code more efficient and fast… I don't think it's important in a lot of application today, but it's a good practice!

if (null == array || array.Length == 0)

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I configured the app.config with the tool for EntLib configuration and set up my LoggingConfiguration block. Then I copied this into the DotNetConfig.xsd. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.

<xs:element name="loggingConfiguration">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="listeners">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:attribute name="fileName" type="xs:string" use="required" />
                <xs:attribute name="footer" type="xs:string" use="required" />
                <xs:attribute name="formatter" type="xs:string" use="required" />
                <xs:attribute name="header" type="xs:string" use="required" />
                <xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
                <xs:attribute name="rollInterval" type="xs:string" use="required" />
                <xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
                <xs:attribute name="timeStampPattern" type="xs:string" use="required" />
                <xs:attribute name="listenerDataType" type="xs:string" use="required" />
                <xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
                <xs:attribute name="filter" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="formatters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="template" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="logFilters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="enabled" type="xs:boolean" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="categorySources">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="specialSources">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="allEvents">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="notProcessed">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="errors">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
    <xs:attribute name="defaultCategory" type="xs:string" use="required" />
    <xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
  </xs:complexType>
</xs:element>

Get gateway ip address in android

Go to terminal

$ adb -s UDID shell
$ ip addr | grep inet 
or
$ netcfg | grep inet

Split string on whitespace in Python

import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

Installing Pandas on Mac OSX

Try

pip3 install pandas 

from terminal. Maybe your original pip install pandas is referencing anaconda distribution

Name [jdbc/mydb] is not bound in this Context

For those who use Tomcat with Bitronix, this will fix the problem:

The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.

In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:

(if you already used them, make sure your references are correct):

  • btm.root
  • bitronix.tm.configuration

e.g.

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Now, restart your server and check the log.

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

Docker can't connect to docker daemon

I also got the issue "Cannot connect to the Docker daemon. Is the docker daemon running on this host?".

I had forgot to use sudo. Hope it will help some of us.

$:docker images
Cannot connect to the Docker daemon. Is the docker daemon running on this host?

$:sudo docker images
REPOSITORY   TAG   IMAGE ID   CREATED   SIZE

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

Sleep function in ORACLE

Seems the java procedure/function could work. But why don't you compile your function under a user like the application schema or a admin account that has this grant and just grant your developer account execute on it. That way the definer rights are used.

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

I got the same error when upgraded angular from 6 to 8.

Simple update angular cli to latest version & node version to 10+.

1) Visit this link to get the latest node version. Angular 8 requires 10+.
2) Execute npm i @angular/cli@latest to update cli.


This is what I have currently

enter image description here

The name does not exist in the namespace error in XAML

A combination of two ideas in this thread worked for me, so I'll post what I did in the hopes that it helps someone else over the next 5 years that this problem continues. I'm using VS2017 Community)

  1. Delete reference to dll
  2. Clean, Rebuild, Build
  3. Close VS, Unblock the dll (see note below), Delete shadow cache
  4. Open VS, Clean, Rebuild, Build
  5. Restore reference to dll
  6. Clean, Rebuild, Build

I may not have the order exactly right in steps 2, 4, and 6 but I was grasping at straws after spending nearly 2 hours with this problem. I think the key for me was the combination of removing the reference, unblocking the dll and deleting the shadow cache.

(Note for step 3 - The dll I'm using was written by a coworker/mentor of mine, so I know it's safe. Careful with this step if you don't know the source of your dll)

I'll be bookmarking this thread for posterity, since it appears that MS has no desire to clean this stuff up. WPF is hard enough to learn on it's own, and having to hack through stuff like this when you've done everything right is infuriating.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Take a look at FileSaver.js. It provides a handy saveAs function which takes care of most browser specific quirks.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

I had the same issue trying to install jquery-rails. The fix was

sudo apt-get install zlibc zlib1g zlib1g-dev

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

ActionLink htmlAttributes

The problem is that your anonymous object property data-icon has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:

Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new {@class="ui-btn-right", data_icon="gear"})

Use the overload that takes in a dictionary:

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

mysql - move rows from one table to another

I had to solve the same issue and this is what I used as solution.

To use this solution the source and destination table must be identical, and the must have an id unique and autoincrement in first table (so that the same id is never reused).

Lets say table1 and table2 have this structure

|id|field1|field2

You can make those two query :

INSERT INTO table2 SELECT * FROM table1 WHERE

DELETE FROM table1 WHERE table1.id in (SELECT table2.id FROM table2)

How to check if a user likes my Facebook Page or URL using Facebook's API

You can use (PHP)

$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);

That will return one of three:

  • string true string false json
  • formatted response of error if token
  • or page_id are not valid

I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:

function isFan(){
    global $facebook;
    $request = $facebook->getSignedRequest();
    return $request['page']['liked'];
}

Create a symbolic link of directory in Ubuntu

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

How do I base64 encode a string efficiently using Excel VBA?

As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.

I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As Variant
  Dim objNode As Variant

  Set objXML = CreateObject("MSXML2.DOMDocument")
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text

  Set objNode = Nothing
  Set objXML = Nothing
End Function

react-native :app:installDebug FAILED

I had the same issue with wrong AVD settings. Probably, "Target Android 6.0" was wrong choice.

Next settings were changed to fix ":app:installDebug FAILED" issue: System Image: Marshmallow , API 23, ABI x86, Target Google API.

see the detail information about this here: RN Android Setup

Remove all special characters, punctuation and spaces from string

This can be done without regex:

>>> string = "Special $#! characters   spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'

You can use str.isalnum:

S.isalnum() -> bool

Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.

If you insist on using regex, other solutions will do fine. However note that if it can be done without using a regular expression, that's the best way to go about it.

How to remove hashbang from url?

window.router = new VueRouter({
   hashbang: false,
   //abstract: true,
  history: true,
    mode: 'html5',
  linkActiveClass: 'active',
  transitionOnLoad: true,
  root: '/'
});

and server is properly configured In apache you should write the url rewrite

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
 </IfModule>

Removing address bar from browser (to view on Android)

The one below works for me every time..

This site also has a few other suggestions, but this no-nonsense, no-worry one is available in a github:gist and answers your question (pasted here for convenience):

function hideAddressBar()
{
  if(!window.location.hash)
  {
      if(document.height < window.outerHeight)
      {
          document.body.style.height = (window.outerHeight + 50) + 'px';
      }

      setTimeout( function(){ window.scrollTo(0, 1); }, 50 );
  }
}

window.addEventListener("load", function(){ if(!window.pageYOffset){ hideAddressBar(); } } );
window.addEventListener("orientationchange", hideAddressBar );

As far as I can tell, the combination of extra height added to the page (which caused problems for you) and the scrollTo() statement make the address bar disappear.

From the same site the 'simplest' solution to hiding the address bar is using the scrollTo() method:

window.addEventListener("load", function() { window.scrollTo(0, 1); });

This will hide the address bar until the user scrolls.

This site places the same method inside a timeout function (the justification is not explained, but it claims the code doesn't work well without it):

// When ready...
window.addEventListener("load",function() {
  // Set a timeout...
  setTimeout(function(){
    // Hide the address bar!
     window.scrollTo(0, 1);
  }, 0);
});

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

Error in plot.window(...) : need finite 'xlim' values

This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.

For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'

How do you detect Credit card type based on number?

Stripe has provided this fantastic javascript library for card scheme detection. Let me add few code snippets and show you how to use it.

Firstly Include it to your web page as

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.payment/1.2.3/jquery.payment.js " ></script>

Secondly use the function cardType for detecting the card scheme.

$(document).ready(function() {              
            var type = $.payment.cardType("4242 4242 4242 4242"); //test card number
            console.log(type);                                   
}); 

Here are the reference links for more examples and demos.

  1. Stripe blog for jquery.payment.js
  2. Github repository

No module named setuptools

The question mentions Windows, and the accepted answer also works for Ubuntu, but for those who found this question coming from a Redhat flavor of Linux, this did the trick:

sudo yum install -y python-setuptools

How can I store JavaScript variable output into a PHP variable?

The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

<script>
  var a="Hello";
  window.location.href = window.location.href+'?a='+a;
</script>

Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

<?php 
  $variable = $_GET['a'];
?>

Pure css close button

Hi you can used this code in pure css

as like this

css

.arrow {
cursor: pointer;
color: white;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.arrow:before{
 content: "×";
}

HTML

<a href="#" class="arrow"> 
</a>

? Live demo http://jsfiddle.net/rohitazad/VzZhU/

How do I clone into a non-empty directory?

I liked Dale's answer, and I also added

git clone --depth 2 --no-checkout repo-to-clone existing-dir/existing-dir.tmp
git branch dev_new214
git checkout dev_new214
git add .
git commit
git checkout dev
git merge dev_new214

The shallow depth avoided a lot of extra early dev commits. The new branch gave us a good visual history that there was some new code from this server that was placed in. That is the perfect use branches in my opinion. My thanks to the great insight of all the people who posted here.

Serialize and Deserialize Json and Json Array in Unity

you have to add [System.Serializable] to PlayerItem class ,like this:

using System;
[System.Serializable]
public class PlayerItem   {
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

Python MySQLdb TypeError: not all arguments converted during string formatting

I don't understand the first two answers. I think they must be version-dependent. I cannot reproduce them on MySQLdb 1.2.3, which comes with Ubuntu 14.04LTS. Let's try them. First, we verify that MySQL doesn't accept double-apostrophes:

mysql> select * from methods limit 1;
+----------+--------------------+------------+
| MethodID | MethodDescription  | MethodLink |
+----------+--------------------+------------+
|       32 | Autonomous Sensing | NULL       |
+----------+--------------------+------------+
1 row in set (0.01 sec)

mysql> select * from methods where MethodID = ''32'';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9999'' ' at line 1

Nope. Let's try the example that Mandatory posted using the query constructor inside /usr/lib/python2.7/dist-packages/MySQLdb/cursors.py where I opened "con" as a connection to my database.

>>> search = "test"
>>> "SELECT * FROM records WHERE email LIKE '%s'" % con.literal(search)
"SELECT * FROM records WHERE email LIKE ''test''"
>>> 

Nope, the double apostrophes cause it to fail. Let's try Mike Graham's first comment, where he suggests leaving off the apostrophes quoting the %s:

>>> "SELECT * FROM records WHERE email LIKE %s" % con.literal(search)
"SELECT * FROM records WHERE email LIKE 'test'"
>>> 

Yep, that will work, but Mike's second comment and the documentation says that the argument to execute (processed by con.literal) must be a tuple (search,) or a list [search]. You can try them, but you'll find no difference from the output above.

The best answer is ksg97031's.

Best way to get value from Collection by index

I agree with Matthew Flaschen's answer and just wanted to show examples of the options for the case you cannot switch to List (because a library returns you a Collection):

List list = new ArrayList(theCollection);
list.get(5);

Or

Object[] list2 = theCollection.toArray();
doSomethingWith(list[2]);

If you know what generics is I can provide samples for that too.

Edit: It's another question what the intent and semantics of the original collection is.

CSS: Change image src on img:hover

There is another simple way using HTML and CSS only!

Just wrap your <img> tag with div like so:

<div class="image-wrapper">
    <img src="http://dummyimage.com/100x100/000/fff">
</div>

Then, in your CSS file hide the img and set the background image for the wrapping div element:

.image-wrapper:hover {
    background-image: url(http://dummyimage.com/100x100/eb00eb/fff);
    background-size: contain;
    background-repeat: no-repeat;
}

.image-wrapper:hover img {
    display: none;
}


Et voilà!

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

I faced the same problem on Mac OS X and with Miniconda. After trying many of the proposed solutions for hours I found that I needed to correctly set Condas environment – specifically requests environment variable – to use the Root certificate that my company provided rather than the generic ones that Conda provides.

Here is how I solved it:

  1. Open Chrome, got to any website, click on the lock icon on the left of the URL. Click on «Certificate» on the dropdown. In the next window you see a stack of certificates. The uppermost (aka top line in window) is the root certificate (e.g. Zscaler Root CA in my case, yours will very likely be a different one).

enter image description here

  1. Open Mac OS keychain, click on «Certificates» and choose among the many certificates the root certificate that you just identified. Export this to any folder of your choosing.
  2. Convert this certificate with openssl: openssl x509 -inform der -in /path/to/your/certificate.cer -out /path/to/converted/certificate.pem
  3. For a quick check set your shell to acknowledge the certificate: export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem
  4. To set this permanently open your shell profile (.bshrs or e.g. .zshrc) and add this line: export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem. Now exit your terminal/shell and reopen. Check again.

You should be set and Conda should work fine.

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

Windows batch - concatenate multiple text files into one

Try this:

@echo off
set yyyy=%date:~6,4%
set mm=%date:~3,2%
set dd=%date:~0,2%

set /p temp= "Enter the name of text file: "
FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%temp%.txt

This code ask you to set the name of the file after "day_" where you can input the date. If you want to name your file like the actual date you can do this:

FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%yyyy%-%mm%-%dd%.txt

gpg: no valid OpenPGP data found

you forgot sudo ... try with sudo and you will get OK

sudo wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -

Convert a String to int?

Well, no. Why there should be? Just discard the string if you don't need it anymore.

&str is more useful than String when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String, you can pass it to where an &str is expected, but if you have &str, you can only pass it to functions expecting String if you make a new allocation.

You can find more on the differences between these two and when to use them in the official strings guide.

How to define a circle shape in an Android XML drawable file?

You can try this -

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:innerRadiusRatio="700"
    android:thickness="100dp"
    android:useLevel="false">

    <solid android:color="#CCC" />

</shape>

Also, you can adjust the radius of the circle by adjusting android:thickness.

enter image description here

Mocking methods of local scope objects with Mockito

The answer from @edutesoy points to the documentation of PowerMockito and mentions constructor mocking as a hint but doesn't mention how to apply that to the current problem in the question.

Here is a solution based on that. Taking the code from the question:

public class MyClass {
    void method1 {
        MyObject obj1 = new MyObject();
        obj1.method1();
    }
}

The following test will create a mock of the MyObject instance class via preparing the class that instantiates it (in this example I am calling it MyClass) with PowerMock and letting PowerMockito to stub the constructor of MyObject class, then letting you stub the MyObject instance method1() call:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
    @Test
    public void testMethod1() {      
        MyObject myObjectMock = mock(MyObject.class);
        when(myObjectMock.method1()).thenReturn(<whatever you want to return>);   
        PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock);
        
        MyClass objectTested = new MyClass();
        objectTested.method1();
        
        ... // your assertions or verification here 
    }
}

With that your internal method1() call will return what you want.

If you like the one-liners you can make the code shorter by creating the mock and the stub inline:

MyObject myObjectMock = when(mock(MyObject.class).method1()).thenReturn(<whatever you want>).getMock();   

Find an element by class name, from a known parent element

var element = $("#parentDiv .myClassNameOfInterest")

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

JQuery Find #ID, RemoveClass and AddClass

jQuery('#testID2').find('.test2').replaceWith('.test3');

Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

You need to do this:

jQuery('#testID2').addClass('test3').removeClass('test2');

This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

HTML not loading CSS file

Use the following steps to load .CSS file its very simple.

<link rel="stylesheet" href="path_here.css">

note: 1--> don't forget to write "stylesheet" in rel attribute. 2--> use correct path e.g: D:\folder1\forlder2\folder3\file.css"

Now where ever directory you are in, you can load your .css file exactly path you mention.

Regards! Muhammad Majid.

How to execute .sql file using powershell?

Quoting from Import the SQLPS Module on MSDN,

The recommended way to manage SQL Server from PowerShell is to import the sqlps module into a Windows PowerShell 2.0 environment.

So, yes, you could use the Add-PSSnapin approach detailed by Christian, but it is also useful to appreciate the recommended sqlps module approach.

The simplest case assumes you have SQL Server 2012: sqlps is included in the installation so you simply load the module like any other (typically in your profile) via Import-Module sqlps. You can check if the module is available on your system with Get-Module -ListAvailable.

If you do not have SQL Server 2012, then all you need do is download the sqlps module into your modules directory so Get-Module/Import-Module will find it. Curiously, Microsoft does not make this module available for download! However, Chad Miller has kindly packaged up the requisite pieces and provided this module download. Unzip it under your ...Documents\WindowsPowerShell\Modules directory and proceed with the import.

It is interesting to note that the module approach and the snapin approach are not identical. If you load the snapins then run Get-PSSnapin (without the -Registered parameter, to show only what you have loaded) you will see the SQL snapins. If, on the other hand, you load the sqlps module Get-PSSnapin will not show the snapins loaded, so the various blog entries that test for the Invoke-Sqlcmd cmdlet by only examining snapins could be giving a false negative result.

2012.10.06 Update

For the complete story on the sqlps module vs. the sqlps mini-shell vs. SQL Server snap-ins, take a look at my two-part mini-series Practical PowerShell for SQL Server Developers and DBAs recently published on Simple-Talk.com where I have, according to one reader's comment, successfully "de-confused" the issue. :-)

How to use the toString method in Java?

Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use

 System.out.println(myObject);

or

System.out.println("text " + myObject);

What are the differences between WCF and ASMX web services?

Keith Elder nicely compares ASMX to WCF here. Check it out.

Another comparison of ASMX and WCF can be found here - I don't 100% agree with all the points there, but it might give you an idea.

WCF is basically "ASMX on stereoids" - it can be all that ASMX could - plus a lot more!.

ASMX is:

  • easy and simple to write and configure
  • only available in IIS
  • only callable from HTTP

WCF can be:

  • hosted in IIS, a Windows Service, a Winforms application, a console app - you have total freedom
  • used with HTTP (REST and SOAP), TCP/IP, MSMQ and many more protocols

In short: WCF is here to replace ASMX fully.

Check out the WCF Developer Center on MSDN.

Update: link seems to be dead - try this: What Is Windows Communication Foundation?

How to calculate the width of a text string of a specific font and font-size?

This simple extension in Swift works well.

extension String {
    func size(OfFont font: UIFont) -> CGSize {
        return (self as NSString).size(attributes: [NSFontAttributeName: font])
    }
}

Usage:

let string = "hello world!"
let font = UIFont.systemFont(ofSize: 12)
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32}

Git resolve conflict using --ours/--theirs for all files

Just grep through the working directory and send the output through the xargs command:

grep -lr '<<<<<<<' . | xargs git checkout --ours

or

grep -lr '<<<<<<<' . | xargs git checkout --theirs

How this works: grep will search through every file in the current directory (the .) and subdirectories recursively (the -r flag) looking for conflict markers (the string '<<<<<<<')

the -l or --files-with-matches flag causes grep to output only the filename where the string was found. Scanning stops after first match, so each matched file is only output once.

The matched file names are then piped to xargs, a utility that breaks up the piped input stream into individual arguments for git checkout --ours or --theirs

More at this link.

Since it would be very inconvenient to have to type this every time at the command line, if you do find yourself using it a lot, it might not be a bad idea to create an alias for your shell of choice: Bash is the usual one.

This method should work through at least Git versions 2.4.x

CSS: Force float to do a whole new line

You can wrap them in a div and give the div a set width (the width of the widest image + margin maybe?) and then float the divs. Then, set the images to the center of their containing divs. Your margins between images won't be consistent for the differently sized images but it'll lay out much more nicely on the page.

How to replace a character from a String in SQL?

This will replace all ? with ':

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
WHERE city LIKE '%?%'

If you need to update more than one column, you can either change city each time you execute to a different column name, or list the columns like so:

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
      ,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'

Creating a blocking Queue<T> in .NET?

"How can this be improved?"

Well, you need to look at every method in your class and consider what would happen if another thread was simultaneously calling that method or any other method. For example, you put a lock in the Remove method, but not in the Add method. What happens if one thread Adds at the same time as another thread Removes? Bad things.

Also consider that a method can return a second object that provides access to the first object's internal data - for example, GetEnumerator. Imagine one thread is going through that enumerator, another thread is modifying the list at the same time. Not good.

A good rule of thumb is to make this simpler to get right by cutting down the number of methods in the class to the absolute minimum.

In particular, don't inherit another container class, because you will expose all of that class's methods, providing a way for the caller to corrupt the internal data, or to see partially complete changes to the data (just as bad, because the data appears corrupted at that moment). Hide all the details and be completely ruthless about how you allow access to them.

I'd strongly advise you to use off-the-shelf solutions - get a book about threading or use 3rd party library. Otherwise, given what you're attempting, you're going to be debugging your code for a long time.

Also, wouldn't it make more sense for Remove to return an item (say, the one that was added first, as it's a queue), rather than the caller choosing a specific item? And when the queue is empty, perhaps Remove should also block.

Update: Marc's answer actually implements all these suggestions! :) But I'll leave this here as it may be helpful to understand why his version is such an improvement.

Receive result from DialogFragment

For anyone still reading this: setTargetFragment() has been deprecated. It is now recommended to use the FragmentResultListener API like this:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setFragmentResultListener("requestKey") { key, bundle ->
        val result = bundle.getString("resultKey")
        // Do something with the result...
    }

    ...

    // Somewhere show your dialog
    MyDialogFragment.newInstance().show(parentFragmentManager, "tag")
}

Then in your MyDialogFragment set the result:

button.setOnClickListener{
    val result = "some string"
    setFragmentResult("requestKey", bundleOf("resultKey" to result))
    dismiss()
}

What is the preferred syntax for defining enums in JavaScript?

UPDATE

Thanks for all the upvotes everyone, but I don't think my answer below is the best way to write enums in JavaScript anymore. See my blog post for more details: Enums in JavaScript.


Alerting the name is already possible:

if (currentColor == my.namespace.ColorEnum.RED) {
   // alert name of currentColor (RED: 0)
   var col = my.namespace.ColorEnum;
   for (var name in col) {
     if (col[name] == col.RED)
       alert(name);
   }
}

Alternatively, you could make the values objects, so you can have the cake and eat it too:

var SIZE = {
  SMALL : {value: 0, name: "Small", code: "S"}, 
  MEDIUM: {value: 1, name: "Medium", code: "M"}, 
  LARGE : {value: 2, name: "Large", code: "L"}
};

var currentSize = SIZE.MEDIUM;
if (currentSize == SIZE.MEDIUM) {
  // this alerts: "1: Medium"
  alert(currentSize.value + ": " + currentSize.name);
}

In JavaScript, as it is a dynamic language, it is even possible to add enum values to the set later:

// Add EXTRALARGE size
SIZE.EXTRALARGE = {value: 3, name: "Extra Large", code: "XL"};

Remember, the fields of the enum (value, name and code in this example) are not needed for the identity check and are only there for convenience. Also the name of the size property itself does not need to be hard coded, but can also be set dynamically. So supposing you only know the name for your new enum value, you can still add it without problems:

// Add 'Extra Large' size, only knowing it's name
var name = "Extra Large";
SIZE[name] = {value: -1, name: name, code: "?"};

Of course this means that some assumptions can no longer be made (that value represents the correct order for the size for example).

Remember, in JavaScript an object is just like a map or hash table. A set of name-value pairs. You can loop through them or otherwise manipulate them without knowing much about them in advance.

Example

for (var sz in SIZE) {
  // sz will be the names of the objects in SIZE, so
  // 'SMALL', 'MEDIUM', 'LARGE', 'EXTRALARGE'
  var size = SIZE[sz]; // Get the object mapped to the name in sz
  for (var prop in size) {
    // Get all the properties of the size object, iterates over
    // 'value', 'name' and 'code'. You can inspect everything this way.        
  }
} 

And by the way, if you are interested in namespaces, you may want to have a look at my solution for simple but powerful namespace and dependency management for JavaScript: Packages JS

error: cast from 'void*' to 'int' loses precision

Again, all of the answers above missed the point badly. The OP wanted to convert a pointer value to a int value, instead, most the answers, one way or the other, tried to wrongly convert the content of arg points to to a int value. And, most of these will not even work on gcc4.

The correct answer is, if one does not mind losing data precision,

int x = *((int*)(&arg));

This works on GCC4.

The best way is, if one can, do not do such casting, instead, if the same memory address has to be shared for pointer and int (e.g. for saving RAM), use union, and make sure, if the mem address is treated as an int only if you know it was last set as an int.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Vava's answer is on the mark. If you use jQuery, then the $.each() function takes care of this, hence it is safer to use.

$.each(evtListeners, function(index, elem) {
    // your code
});