Programs & Examples On #Lazy loading

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed.

What is lazy loading in Hibernate?

Say you have a parent and that parent has a collection of children. Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.

Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.

Also beware of the n+1-problem. Hibernate will not actually load all children when you access the collection. Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().

Hibernate: best practice to pull all lazy collections

Try use Gson library to convert objects to Json

Example with servlets :

  List<Party> parties = bean.getPartiesByIncidentId(incidentId);
        String json = "";
        try {
            json = new Gson().toJson(parties);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);

How to Lazy Load div background images

Lazy loading images using above mentioned plugins uses conventional way of attaching listener to scroll events or by making use of setInterval and is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.

Use Lozad.js (just 569 bytes with no dependencies), which uses InteractionObserver to lazy load images performantly.

Doctrine 2 ArrayCollection filter method

Doctrine now has Criteria which offers a single API for filtering collections with SQL and in PHP, depending on the context.

https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections

Update

This will achieve the result in the accepted answer, without getting everything from the database.

use Doctrine\Common\Collections\Criteria;

/**
 * @ORM\Entity
 */
class Member {
  // ...
  public function getCommentsFiltered($ids) {
    $criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));

    return $this->getComments()->matching($criteria); 
  }
}

How to convert a Hibernate proxy to a real entity object

The another workaround is to call

Hibernate.initialize(extractedObject.getSubojbectToUnproxy());

Just before closing the session.

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

The best way to handle the LazyInitializationException is to use the JOIN FETCH directive:

Query query = session.createQuery("""
    select m
    from Model m
    join fetch m.modelType
    where modelGroup.id = :modelGroupId
    """
);

Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:

Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException.

How to load images dynamically (or lazily) when users scrolls them into view

The Swiss Army knife of image lazy loading is YUI's ImageLoader.

Because there is more to this problem than simply watching the scroll position.

Entity framework linq query Include() multiple children entities

You might find this article of interest which is available at codeplex.com.

The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.

Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

How can I make a JPA OneToOne relation lazy

Here's something that has been working for me (without instrumentation):

Instead of using @OneToOne on both sides, I use @OneToMany in the inverse part of the relationship (the one with mappedBy). That makes the property a collection (List in the example below), but I translate it into an item in the getter, making it transparent to the clients.

This setup works lazily, that is, the selects are only made when getPrevious() or getNext() are called - and only one select for each call.

The table structure:

CREATE TABLE `TB_ISSUE` (
    `ID`            INT(9) NOT NULL AUTO_INCREMENT,
    `NAME`          VARCHAR(255) NULL,
    `PREVIOUS`      DECIMAL(9,2) NULL
    CONSTRAINT `PK_ISSUE` PRIMARY KEY (`ID`)
);
ALTER TABLE `TB_ISSUE` ADD CONSTRAINT `FK_ISSUE_ISSUE_PREVIOUS`
                 FOREIGN KEY (`PREVIOUS`) REFERENCES `TB_ISSUE` (`ID`);

The class:

@Entity
@Table(name = "TB_ISSUE") 
public class Issue {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer id;

    @Column
    private String name;

    @OneToOne(fetch=FetchType.LAZY)  // one to one, as expected
    @JoinColumn(name="previous")
    private Issue previous;

    // use @OneToMany instead of @OneToOne to "fake" the lazy loading
    @OneToMany(mappedBy="previous", fetch=FetchType.LAZY)
    // notice the type isnt Issue, but a collection (that will have 0 or 1 items)
    private List<Issue> next;

    public Integer getId() { return id; }
    public String getName() { return name; }

    public Issue getPrevious() { return previous; }
    // in the getter, transform the collection into an Issue for the clients
    public Issue getNext() { return next.isEmpty() ? null : next.get(0); }

}

How to make Twitter Bootstrap menu dropdown on hover rather than click

This is probably a stupid idea, but to just remove the arrow pointing down, you can delete the

<b class="caret"></b>

This does nothing for the up pointing one, though...

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

How to remove all debug logging calls before building the release version of an Android app?

I'm posting this solution which applies specifically for Android Studio users. I also recently discovered Timber and have imported it successfully into my app by doing the following:

Put the latest version of the library into your build.gradle:

compile 'com.jakewharton.timber:timber:4.1.1'

Then in Android Studios, go to Edit -> Find -> Replace in Path...

Type in Log.e(TAG, or however you have defined your Log messages into the "Text to find" textbox. Then you just replace it with Timber.e(

enter image description here

Click Find and then replace all.

Android Studios will now go through all your files in your project and replace all the Logs with Timbers.

The only problem I had with this method is that gradle does come up witha million error messages afterwards because it cannot find "Timber" in the imports for each of your java files. Just click on the errors and Android Studios will automatically import "Timber" into your java. Once you have done it for all your errors files, gradle will compile again.

You also need to put this piece of code in your onCreate method of your Application class:

    if (BuildConfig.DEBUG) {
        Timber.plant(new Timber.DebugTree());
    }

This will result in the app logging only when you are in development mode not in production. You can also have BuildConfig.RELEASE for logging in release mode.

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

How is malloc() implemented internally?

Simplistically malloc and free work like this:

malloc provides access to a process's heap. The heap is a construct in the C core library (commonly libc) that allows objects to obtain exclusive access to some space on the process's heap.

Each allocation on the heap is called a heap cell. This typically consists of a header that hold information on the size of the cell as well as a pointer to the next heap cell. This makes a heap effectively a linked list.

When one starts a process, the heap contains a single cell that contains all the heap space assigned on startup. This cell exists on the heap's free list.

When one calls malloc, memory is taken from the large heap cell, which is returned by malloc. The rest is formed into a new heap cell that consists of all the rest of the memory.

When one frees memory, the heap cell is added to the end of the heap's free list. Subsequent malloc's walk the free list looking for a cell of suitable size.

As can be expected the heap can get fragmented and the heap manager may from time to time, try to merge adjacent heap cells.

When there is no memory left on the free list for a desired allocation, malloc calls brk or sbrk which are the system calls requesting more memory pages from the operating system.

Now there are a few modification to optimize heap operations.

  • For large memory allocations (typically > 512 bytes, the heap manager may go straight to the OS and allocate a full memory page.
  • The heap may specify a minimum size of allocation to prevent large amounts of fragmentation.
  • The heap may also divide itself into bins one for small allocations and one for larger allocations to make larger allocations quicker.
  • There are also clever mechanisms for optimizing multi-threaded heap allocation.

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

Your gradle files might be corrupted. Try running

./gradlew --refresh-dependencies

in the terminal inside android studio.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I had a similar problem that I resolved by defining my button array outside of the dialog declaration.

var buttonArray = {};
buttonArray["Ok"] = function() { $( this ).dialog( "close" );}

Your options would become:

modal: true,
autoOpen: false,
buttons: buttonArray

What is the difference between 'typedef' and 'using' in C++11?

All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.


Typedef declarations can, whereas alias declarations cannot, be used as initialization statements

But, with the first two non-template examples, are there any other subtle differences in the standard?

  • Differences in semantics: none.
  • Differences in allowed contexts: some(1).

(1) In addition to the examples of alias templates, which has already been mentioned in the original post.

Same semantics

As governed by [dcl.typedef]/2 [extract, emphasis mine]

[dcl.typedef]/2 A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. Such a typedef-name has the same semantics as if it were introduced by the typedef specifier. [...]

a typedef-name introduced by an alias-declaration has the same semantics as if it were introduced by the typedef declaration.

Subtle difference in allowed contexts

However, this does not imply that the two variations have the same restrictions with regard to the contexts in which they may be used. And indeed, albeit a corner case, a typedef declaration is an init-statement and may thus be used in contexts which allow initialization statements

// C++11 (C++03) (init. statement in for loop iteration statements).
for(typedef int Foo; Foo{} != 0;) {}

// C++17 (if and switch initialization statements).
if (typedef int Foo; true) { (void)Foo{}; }
//  ^^^^^^^^^^^^^^^ init-statement

switch(typedef int Foo; 0) { case 0: (void)Foo{}; }
//     ^^^^^^^^^^^^^^^ init-statement

// C++20 (range-based for loop initialization statements).
std::vector<int> v{1, 2, 3};
for(typedef int Foo; Foo f : v) { (void)f; }
//  ^^^^^^^^^^^^^^^ init-statement

for(typedef struct { int x; int y;} P;
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ init-statement
    auto [x, y] : {P{1, 1}, {1, 2}, {3, 5}}) { (void)x; (void)y; }

whereas an alias-declaration is not an init-statement, and thus may not be used in contexts which allows initialization statements

// C++ 11.
for(using Foo = int; Foo{} != 0;) {}
//  ^^^^^^^^^^^^^^^ error: expected expression

// C++17 (initialization expressions in switch and if statements).
if (using Foo = int; true) { (void)Foo{}; }
//  ^^^^^^^^^^^^^^^ error: expected expression

switch(using Foo = int; 0) { case 0: (void)Foo{}; }
//     ^^^^^^^^^^^^^^^ error: expected expression

// C++20 (range-based for loop initialization statements).
std::vector<int> v{1, 2, 3};
for(using Foo = int; Foo f : v) { (void)f; }
//  ^^^^^^^^^^^^^^^ error: expected expression

How can I use pointers in Java?

you can have pointers for literals as well. You have to implement them yourself. It is pretty basic for experts ;). Use an array of int/object/long/byte and voila you have the basics for implementing pointers. Now any int value can be a pointer to that array int[]. You can increment the pointer, you can decrement the pointer, you can multiply the pointer. You indeed have pointer arithmetics! That's the only way to implements 1000 int attributes classes and have a generic method that applies to all attributes. You can also use a byte[] array instead of an int[]

However I do wish Java would let you pass literal values by reference. Something along the lines

//(* telling you it is a pointer) public void myMethod(int* intValue);

Importing a long list of constants to a Python file

And ofcourse you can do:

# a.py
MY_CONSTANT = ...

# b.py
from a import *
print MY_CONSTANT

How do I find what Java version Tomcat6 is using?

You can use the Tomcat manager app to find out which JRE and OS versions Tomcat is using. Given a user tomcat with password password with a role of manager:

Tomcat 6:

curl http://tomcat:password@localhost:8080/manager/serverinfo

Tomcat 7/8:

curl http://tomcat:password@localhost:8080/manager/text/serverinfo

Using Django time/date widgets in custom form

In Django 10. myproject/urls.py: at the beginning of urlpatterns

  from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
.
.
.]

In my template.html:

{% load staticfiles %}

    <script src="{% static "js/jquery-2.2.3.min.js" %}"></script>
    <script src="{% static "js/bootstrap.min.js" %}"></script>
    {# Loading internazionalization for js #}
    {% load i18n admin_modify %}
    <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/jquery.init.js" %}"></script>

    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/base.css" %}">
    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/forms.css" %}">
    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/login.css" %}">
    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/widgets.css" %}">



    <script type="text/javascript" src="{% static "/admin/js/core.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/SelectFilter2.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/admin/RelatedObjectLookups.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/actions.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/calendar.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/admin/DateTimeShortcuts.js" %}"></script>

Validating IPv4 addresses with regexp

Above answers are valid but what if the ip address is not at the end of line and is in between text.. This regex will even work on that.

code: '\b((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.)){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\b'

input text file:

ip address 0.0.0.0 asfasf
 sad sa 255.255.255.255 cvjnzx
zxckjzbxk  999.999.999.999 jshbczxcbx
sjaasbfj 192.168.0.1 asdkjaksb
oyo 123241.24121.1234.3423 yo
yo 0000.0000.0000.0000 y
aw1a.21asd2.21ad.21d2
yo 254.254.254.254 y0
172.24.1.210 asfjas
200.200.200.200
000.000.000.000
007.08.09.210
010.10.30.110

output text:

0.0.0.0
255.255.255.255
192.168.0.1
254.254.254.254
172.24.1.210
200.200.200.200

How do I perform an IF...THEN in an SQL SELECT?

SELECT
if((obsolete = 'N' OR instock = 'Y'), 1, 0) AS saleable, *
FROM
product;

How to calculate growth with a positive and negative number?

This article offers a detailed explanation for why the (b - a)/ABS(a) formula makes sense. It is counter-intuitive at first, but once you play with the underlying arithmetic, it starts to make sense. As you get used to it eventually, it changes the way you look at percentages.

How to convert integer into date object python?

Here is what I believe answers the question (Python 3, with type hints):

from datetime import date


def int2date(argdate: int) -> date:
    """
    If you have date as an integer, use this method to obtain a datetime.date object.

    Parameters
    ----------
    argdate : int
      Date as a regular integer value (example: 20160618)

    Returns
    -------
    dateandtime.date
      A date object which corresponds to the given value `argdate`.
    """
    year = int(argdate / 10000)
    month = int((argdate % 10000) / 100)
    day = int(argdate % 100)

    return date(year, month, day)


print(int2date(20160618))

The code above produces the expected 2016-06-18.

How to convert a string to an integer in JavaScript?

Please see the below example.It will help clear your doubt

Example                  Result

parseInt("4")            4
parseInt("5aaa")         5
parseInt("4.33333")      4
parseInt("aaa");         NaN (means "Not a Number")

by using parseint function It will only give op of integer present and not the string

Factory Pattern. When to use factory methods?

One situation where I personally find separate Factory classes to make sense is when the final object you are trying to create relies on several other objects. E.g, in PHP: Suppose you have a House object, which in turn has a Kitchen and a LivingRoom object, and the LivingRoom object has a TV object inside as well.

The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your House fails creating you will probably spend some time trying to isolate exactly what is failing.

The alternative is to do the following (dependency injection, if you like the fancy term):

$TVObj = new TV($param1, $param2, $param3);
$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
$KitchenroomObj = new Kitchen($param1, $param2);
$HouseObj = new House($LivingroomObj, $KitchenroomObj);

Here if the process of creating a House fails there is only one place to look, but having to use this chunk every time one wants a new House is far from convenient. Enter the Factories:

class HouseFactory {
    public function create() {
        $TVObj = new TV($param1, $param2, $param3);
        $LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
        $KitchenroomObj = new Kitchen($param1, $param2);
        $HouseObj = new House($LivingroomObj, $KitchenroomObj);

        return $HouseObj;
    }
}

$houseFactory = new HouseFactory();
$HouseObj = $houseFactory->create();

Thanks to the factory here the process of creating a House is abstracted (in that you don't need to create and set up every single dependency when you just want to create a House) and at the same time centralized which makes it easier to maintain. There are other reasons why using separate Factories can be beneficial (e.g. testability) but I find this specific use case to illustrate best how Factory classes can be useful.

Convert a Pandas DataFrame to a dictionary

Should a dictionary like:

{'red': '0.500', 'yellow': '0.250, 'blue': '0.125'}

be required out of a dataframe like:

        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

simplest way would be to do:

dict(df.values)

working snippet below:

import pandas as pd
df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
dict(df.values)

how to set the query timeout from SQL connection string

See:- ConnectionStrings content on this subject. There is no default command timeout property.

Hello World in Python

In python 3.x. you use

print("Hello, World")

In Python 2.x. you use

print "Hello, World!"

reCAPTCHA ERROR: Invalid domain for site key

Try to add domains without http:// and https:// e.g. example.com

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

What does "Content-type: application/json; charset=utf-8" really mean?

The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.

Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding. Designating the encoding is somewhat redundant for JSON, since the default (only?) encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.

Does this encoding limit the characters that can be in the message body?

No. You can send anything you want in the header and the body. But, if the two don't match, you may get wrong results. If you specify in the header that the content is UTF-8 encoded but you're actually sending Latin1 encoded content, the receiver may produce garbage data, trying to interpret Latin1 encoded data as UTF-8. If of course you specify that you're sending Latin1 encoded data and you're actually doing so, then yes, you're limited to the 256 characters you can encode in Latin1.

How do I programmatically "restart" an Android app?

I've found that this works on API 29 and later - for the purpose of killing and restarting the app as if the user had launched it when it wasn't running.

public void restartApplication(final @NonNull Activity activity) {
   // Systems at 29/Q and later don't allow relaunch, but System.exit(0) on
   // all supported systems will relaunch ... but by killing the process, then
   // restarting the process with the back stack intact. We must make sure that
   // the launch activity is the only thing in the back stack before exiting.
   final PackageManager pm = activity.getPackageManager();
   final Intent intent = pm.getLaunchIntentForPackage(activity.getPackageName());
   activity.finishAffinity(); // Finishes all activities.
   activity.startActivity(intent);    // Start the launch activity
   System.exit(0);    // System finishes and automatically relaunches us.
}

That was done when the launcher activity in the app has this:

<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

I've seen comments claiming that a category of DEFAULT is needed, but I haven't found that to be the case. I have confirmed that the Application object in my app is re-created, so I believe that the process really has been killed and restarted.

The only purpose for which I use this is to restart the app after the user has enabled or disabled crash reporting for Firebase Crashlytics. According to their docs, the app has to be restarted (process killed and re-created) for that change to take effect.

Ignore mapping one property with Automapper

You can do this:

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.Ignore());

Or, in latest version of Automapper, you simply want to tell Automapper to not validate the field

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

How to save a data.frame in R?

Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.

write.csv(Data_output, "output.csv", row.names = F, quote = F)

credit to Peter and Ilja, UMCG, the Netherlands

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

How to clear https proxy setting of NPM?

I had the same problem once.
Follow these steps to delete proxy values:

1.To delete proxy in npm:
(-g is Important)
npm config delete proxy -g
npm config delete http-proxy -g
npm config delete https-proxy -g

Check the npm config file using:
npm config list

2.To delete system proxy: set HTTP_PROXY=null set HTTPS_PROXY=null

Now close the command line and open it to refresh the variables(proxy).

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

Scenario/Test steps:
1. Open a browser and navigate to TestURL
2. Scroll down some pixel and scroll up

For Scroll down:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");

OR, you can do as follows:

jse.executeScript("scroll(0, 250);");

For Scroll up:

jse.executeScript("window.scrollBy(0,-250)");
OR,
jse.executeScript("scroll(0, -250);");

Scroll to the bottom of the page:

Scenario/Test steps:
1. Open a browser and navigate to TestURL
2. Scroll to the bottom of the page

Way 1: By using JavaScriptExecutor

jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Way 2: By pressing ctrl+end

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.END);

Way 3: By using Java Robot class

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_CONTROL);

Limit String Length

Do a little homework with the php online manual's string functions. You'll want to use strlen in a comparison setting, substr to cut it if you need to, and the concatenation operator with "..." or "&hellip;"

Can we pass model as a parameter in RedirectToAction?

Yes you can pass the model that you have shown using

return RedirectToAction("GetStudent", "Student", student1 );

assuming student1 is an instance of Student

which will generate the following url (assuming your using the default routes and the value of student1 are ID=4 and Name="Amit")

.../Student/GetStudent/4?Name=Amit

Internally the RedirectToAction() method builds a RouteValueDictionary by using the .ToString() value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student contained a property List<string> Subjects, then that property would result in a query string value of

....&Subjects=System.Collections.Generic.List'1[System.String]

and binding would fail and that property would be null

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

Node.js project naming conventions for files & folders

According to me: For files, use lower camel case if module.exports is an object, I mean a singleton module. This is also applicable to JSON files as they are also in a way single ton. Use upper camel case if module.exports returns a constructor function where it acts like a class.

For folders use short names. If there is need to have multiple words, let it be completely lower case separated by "-" so that it works across all platforms consistently.

What is the difference between a candidate key and a primary key?

Think of a table of vehicles with an integer Primary Key.

The registration number would be a candidate key.

In the real world registration numbers are subject change so it depends somewhat on the circumstances what might qualify as a candidate key.

Detect Click into Iframe using JavaScript

This works for me on all browsers (included Firefox)

https://gist.github.com/jaydson/1780598

https://jsfiddle.net/sidanmor/v6m9exsw/

_x000D_
_x000D_
var myConfObj = {_x000D_
  iframeMouseOver : false_x000D_
}_x000D_
window.addEventListener('blur',function(){_x000D_
  if(myConfObj.iframeMouseOver){_x000D_
    console.log('Wow! Iframe Click!');_x000D_
  }_x000D_
});_x000D_
_x000D_
document.getElementById('idanmorblog').addEventListener('mouseover',function(){_x000D_
   myConfObj.iframeMouseOver = true;_x000D_
});_x000D_
document.getElementById('idanmorblog').addEventListener('mouseout',function(){_x000D_
    myConfObj.iframeMouseOver = false;_x000D_
});
_x000D_
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
_x000D_
_x000D_
_x000D_

<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

Android Studio Gradle Already disposed Module

Note: this is purely an IDEA/AS issue, gradlew clean | Build > Clean | Build > Rebuild will just waste your time.

Most of the solutions here are blind stabbings in the dark. Here's what I found to be the root cause:

  1. Some of the .iml files may be missing (maybe because we deleted it), check if the module erroring has .iml.
  2. If it is missing, check if .idea/modules.xml has an entry for that module

While syncing I noticed that IDEA/AS tries to put a new duplicate entry into .idea/modules.xml while there's already one. This duplicate entry is probably disposed of twice while the sync tries to reset the modules in memory.

Quick Solution: In order to make it work the easiest is to delete .idea/modules.xml along with the .iml files. Additionally may worth deleting .idea/modules/ folder if it exists. Restart Android Studio (no need to clear cache) and force a Gradle sync from Gradle view or toolbar to recreate the files.

How to List All Redis Databases?

Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli:

$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1

How to get html table td cell value by JavaScript?

I gave the table an id so I could find it. On onload (when the page is loaded by the browser), I set onclick event handlers to all rows of the table. Those handlers alert the content of the first cell.

<!DOCTYPE html>
<html>
    <head>
        <script>
            var p = {
                onload: function() {
                    var rows = document.getElementById("mytable").rows;
                    for(var i = 0, ceiling = rows.length; i < ceiling; i++) {
                        rows[i].onclick = function() {
                            alert(this.cells[0].innerHTML);
                        }
                    }
                }
            };
        </script>
    </head>
    <body onload="p.onload()">
        <table id="mytable">
            <tr>
                <td>0</td>
                <td>row 1 cell 2</td>
            </tr>
            <tr>
                <td>1</td>
                <td>row 2 cell 2</td>
            </tr>
        </table>    
    </body>
</html> 

Angular 2 : No NgModule metadata found

I found that the cause of this problem in my case, was that I've combined my Angular app with a node.js application in the same source tree, and in the root tsconfig.json I had:

"files": [ "./node_modules/@types/node/index.d.ts" ]

I changed this to

"compilerOptions": { "types": ["node"] }

And then to prevent node types being uses in your angular app, add this to tsconfig.app.json:

"compilerOptions": { "types": [] }

How to replace blank (null ) values with 0 for all records?

UPDATE table SET column=0 WHERE column IS NULL

Merge, update, and pull Git branches without using checkouts

I wrote a shell function for a similar use case I encounter daily on projects. This is basically a shortcut for keeping local branches up to date with a common branch like develop before opening a PR, etc.

Posting this even though you don't want to use checkout, in case others don't mind that constraint.

glmh ("git pull and merge here") will automatically checkout branchB, pull the latest, re-checkout branchA, and merge branchB.

Doesn't address the need to keep a local copy of branchA, but could easily be modified to do so by adding a step before checking out branchB. Something like...

git branch ${branchA}-no-branchB ${branchA}

For simple fast-forward merges, this skips to the commit message prompt.

For non fast-forward merges, this places your branch in the conflict resolution state (you likely need to intervene).

To setup, add to .bashrc or .zshrc, etc:

glmh() {
    branchB=$1
    [ $# -eq 0 ] && { branchB="develop" }
    branchA="$(git branch | grep '*' | sed 's/* //g')"
    git checkout ${branchB} && git pull
    git checkout ${branchA} && git merge ${branchB} 
}

Usage:

# No argument given, will assume "develop"
> glmh

# Pass an argument to pull and merge a specific branch
> glmh your-other-branch

Note: This is not robust enough to hand-off of args beyond branch name to git merge

text-overflow: ellipsis not working

Add this below code for where you likes to

example

p{
   display: block; /* Fallback for non-webkit */
   display: -webkit-box;
   max-width: 400px;
   margin: 0 auto;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;
   text-overflow: ellipsis;
 }

How to write connection string in web.config file and read from it?

Try this After open web.config file in application and add sample db connection in connectionStrings section like this

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >

Getting pids from ps -ef |grep keyword

ps -ef | grep KEYWORD | grep -v grep | awk '{print $2}'

How to reset (clear) form through JavaScript?

You could use the following:

$('[element]').trigger('reset')

How to serialize SqlAlchemy result to JSON?

Custom serialization and deserialization.

"from_json" (class method) builds a Model object based on json data.

"deserialize" could be called only on instance, and merge all data from json into Model instance.

"serialize" - recursive serialization

__write_only__ property is needed to define write only properties ("password_hash" for example).

class Serializable(object):
    __exclude__ = ('id',)
    __include__ = ()
    __write_only__ = ()

    @classmethod
    def from_json(cls, json, selfObj=None):
        if selfObj is None:
            self = cls()
        else:
            self = selfObj
        exclude = (cls.__exclude__ or ()) + Serializable.__exclude__
        include = cls.__include__ or ()
        if json:
            for prop, value in json.iteritems():
                # ignore all non user data, e.g. only
                if (not (prop in exclude) | (prop in include)) and isinstance(
                        getattr(cls, prop, None), QueryableAttribute):
                    setattr(self, prop, value)
        return self

    def deserialize(self, json):
        if not json:
            return None
        return self.__class__.from_json(json, selfObj=self)

    @classmethod
    def serialize_list(cls, object_list=[]):
        output = []
        for li in object_list:
            if isinstance(li, Serializable):
                output.append(li.serialize())
            else:
                output.append(li)
        return output

    def serialize(self, **kwargs):

        # init write only props
        if len(getattr(self.__class__, '__write_only__', ())) == 0:
            self.__class__.__write_only__ = ()
        dictionary = {}
        expand = kwargs.get('expand', ()) or ()
        prop = 'props'
        if expand:
            # expand all the fields
            for key in expand:
                getattr(self, key)
        iterable = self.__dict__.items()
        is_custom_property_set = False
        # include only properties passed as parameter
        if (prop in kwargs) and (kwargs.get(prop, None) is not None):
            is_custom_property_set = True
            iterable = kwargs.get(prop, None)
        # loop trough all accessible properties
        for key in iterable:
            accessor = key
            if isinstance(key, tuple):
                accessor = key[0]
            if not (accessor in self.__class__.__write_only__) and not accessor.startswith('_'):
                # force select from db to be able get relationships
                if is_custom_property_set:
                    getattr(self, accessor, None)
                if isinstance(self.__dict__.get(accessor), list):
                    dictionary[accessor] = self.__class__.serialize_list(object_list=self.__dict__.get(accessor))
                # check if those properties are read only
                elif isinstance(self.__dict__.get(accessor), Serializable):
                    dictionary[accessor] = self.__dict__.get(accessor).serialize()
                else:
                    dictionary[accessor] = self.__dict__.get(accessor)
        return dictionary

System.Drawing.Image to stream C#

public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }

bootstrap 3 - how do I place the brand in the center of the navbar?

I used two classes to achieve this and maintain responsiveness navbar-brand-left and navbar-brand-center. Keep in mind it utilises Sass / Less Bootstrap for line height, otherwise specify a hardcode px / rem height.

HTML

<nav class="navbar navbar-default">
  <div class="container-fluid">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="#" class="navbar-brand-left visible-xs visible-sm">Brand</a>
    </div>

    <div class="collapse navbar-collapse text-center" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><a href="#">About</a></li>
        <li><a href="#">How it works</a></li>
      </ul>
      <a href="#" class="navbar-brand-center hidden-xs hidden-sm">Brand</a>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Log in</a></li>
        <li><a href="#">Start now</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

CSS

.navbar-brand-left {
    display: inline-block;
    margin: 0;
    padding: 0;
    line-height: @navbar-height;
}

.navbar-brand-center {
    display: inline-block;
    margin: 0 auto;
    padding: 0;
    line-height: @navbar-height;
}

moment.js, how to get day of week number

Define "doesn't work".

_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const dow = date.day();_x000D_
console.log(dow);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

This prints "4", as expected.

Swap two items in List<T>

List<T> has a Reverse() method, however it only reverses the order of two (or more) consecutive items.

your_list.Reverse(index, 2);

Where the second parameter 2 indicates we are reversing the order of 2 items, starting with the item at the given index.

Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx

Output data from all columns in a dataframe in pandas

I know this is an old question, but I have just had a similar problem and I think what I did would work for you too.

I used the to_csv() method and wrote to stdout:

import sys

paramdata.to_csv(sys.stdout)

This should dump the whole dataframe whether it's nicely-printable or not, and you can use the to_csv parameters to configure column separators, whether the index is printed, etc.

Edit: It is now possible to use None as the target for .to_csv() with similar effect, which is arguably a lot nicer:

paramdata.to_csv(None)

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html

Best way to change font colour halfway through paragraph?

You can also simply add the font tag inside the p tag.

CSS sheet:

<style type="text/css">
   p { font:15px Arial; color:white; }
</style>

and in HTML page:

<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. 
    <font color="red"> 
          Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris     nisi ut aliquip ex ea commodo consequat. 
    </font>
Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>

It works for me. But, in case you need modification, see w3schools for more usage :)

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Your problem is in this line: Message messageObject = new Message ();
This error says that the Message class is not known at compile time.

So you need to import the Message class.

Something like this:

import package1.package2.Message;

Check this out.

http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

How do I align spans or divs horizontally?

You can use divs with the float: left; attribute which will make them appear horizontally next to each other, but then you may need to use clearing on the following elements to make sure they don't overlap.

What's the difference between a Python module and a Python package?

A late answer, yet another definition:

A package is represented by an imported top-entity which could either be a self-contained module, or the __init__.py special module as the top-entity from a set of modules within a sub directory structure.

So physically a package is a distribution unit, which provides one or more modules.

CheckBox in RecyclerView keeps on checking different items

I had the same problem in a RecyclerView list with switches, and solved it using @oguzhand answer, but with this code inside the checkedChangeListener:

if (buttonView.isPressed()) {
    if (isChecked) {
        group.setSelected(true);
    } else {
        group.setSelected(false);
    }
}else{
    if (isChecked) {
        buttonView.setChecked(false);
    } else {
        buttonView.setChecked(true);
    }
}

(Where 'group' is the entity I want to select/deselect)

How do I get the path of the Python script I am running in?

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment

for each inside a for each - Java

Your syntax is not correct. It should be like that:

for (Tweet tweet : tweets) {              
    for(long forId : idFromArray){
        long tweetId = tweet.getId();
        if(forId != tweetId){
            String twitterString = tweet.getText();
            db.insertTwitter(twitterString);
        }
    }
}

EDIT

This answer no longer really answers the question since it was updated ;)

'Source code does not match the bytecode' when debugging on a device

My app is compiled on API LEVEL 29, but debugging on real device on API LEVEL 28.I got the warning source code does not match the bytecode in AndroidStudio.I fixed it thought these steps:

  1. Go to Preferences>Instant Run: uncheck the instant run

  2. Go to Build>Clean Build

  3. Re-RUN the app

Now, the debug runs normal.

HTML Script tag: type or language (or omit both)?

HTML4/XHTML1 requires

<script type="...">...</script>

HTML5 faces the fact that there is only one scripting language on the web, and allows

<script>...</script>

The latter works in any browser that supports scripting (NN2+).

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

From Hadley Wickham:

From Hadley Wickham

My (crappy looking) modification to show using tidyverse / purrr:

enter image description here

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Set default format of datetimepicker as dd-MM-yyyy

You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.

Div Background Image Z-Index Issue

For z-index to work, you also need to give it a position:

header {
    width: 100%;
    height: 100px;
    background: url(../img/top.png) repeat-x;
    z-index: 110;
    position: relative;
}

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

How can I get a list of all classes within current module in Python?

I think that you can do something like this.

class custom(object):
    __custom__ = True
class Alpha(custom):
    something = 3
def GetClasses():
    return [x for x in globals() if hasattr(globals()[str(x)], '__custom__')]
print(GetClasses())`

if you need own classes

How do you run a Python script as a service in Windows?

https://www.chrisumbel.com/article/windows_services_in_python

  1. Follow up the PySvc.py

  2. changing the dll folder

I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll

From -> Python36\Lib\site-packages\pywin32_system32

To -> Python36\Lib\site-packages\win32

setx /M PATH "%PATH%;C:\Users\user\AppData\Local\Programs\Python\Python38-32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pywin32_system32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\win32
  1. changing the path to python folder by

cd C:\Users\user\AppData\Local\Programs\Python\Python38-32

  1. NET START PySvc
  2. NET STOP PySvc

Git with SSH on Windows

I fought with this problem for a few hours before stumbling on the obvious answer. The problem I had was I was using different ssh implementations between when I generated my keys and when I used git.

I used ssh-keygen from the command prompt to generate my keys and but when I tried "git clone ssh://..." I got the same results as you, a prompt for the password and the message "fatal: The remote end hung up unexpectedly".

Determine which ssh windows is using by executing the Windows "where" command.

C:\where ssh
C:\Program Files (x86)\Git\bin\ssh.exe

The second line tells you which exact program will be executed.

Next you need to determine which ssh that git is using. Find this by:

C:\set GIT_SSH
GIT_SSH=C:\Program Files\TortoiseSVN\bin\TortoisePlink.exe

And now you see the problem.

To correct this simply execute:

C:\set GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe

To check if changes are applied:

C:\set GIT_SSH
GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe

Now git will be able to use the keys that you generated earlier.

This fix is so far only for the current window. To fix it completely you need to change your environment variable.

  1. Open Windows explorer
  2. Right-click Computer and select Properties
  3. Click Advanced System Settings link on the left
  4. Click the Environment Variables... button
  5. In the system variables section select the GIT_SSH variable and press the Edit... button
  6. Update the variable value.
  7. Press OK to close all windows

Now any future command windows you open will have the correct settings.

Hope this helps.

Reading a resource file from within jar

Up until now (December 2017), this is the only solution I found which works both inside and outside the IDE.

Use PathMatchingResourcePatternResolver

Note: it works also in spring-boot

In this example I'm reading some files located in src/main/resources/my_folder:

try {
    // Get all the files under this inner resource folder: my_folder
    String scannedPackage = "my_folder/*";
    PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
    Resource[] resources = scanner.getResources(scannedPackage);

    if (resources == null || resources.length == 0)
        log.warn("Warning: could not find any resources in this scanned package: " + scannedPackage);
    else {
        for (Resource resource : resources) {
            log.info(resource.getFilename());
            // Read the file content (I used BufferedReader, but there are other solutions for that):
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                // ...
                // ...                      
            }
            bufferedReader.close();
        }
    }
} catch (Exception e) {
    throw new Exception("Failed to read the resources folder: " + e.getMessage(), e);
}

Visual Studio keyboard shortcut to display IntelliSense

In Visual Studio 2015 this shortcut opens a preview of the definition which even works through typedefs and #defines.

Ctrl + , (comma)

Enter image description here

How to clear cache in Yarn?

Also note that the cached directory is located in ~/.yarn-cache/:

yarn cache clean: cleans that directory

yarn cache list: shows the list of cached dependencies

yarn cache dir: prints out the path of your cached directory

Converting a string to JSON object

I had the same problem with a similar string like yours

{id:1,field1:"someField"},{id:2,field1:"someOtherField"}

The problem here is the structure of the string. The json parser wasn't recognizing that it needs to create 2 objects in this case. So what I did is kind of silly, I just re-structured my string and added the [] with this the parser recognized

var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)

Hope it helps,

If anyone has a more elegant approach please share.

In C, how should I read a text file and print all strings

Instead just directly print the characters onto the console because the text file maybe very large and you may require a lot of memory.

#include <stdio.h>
#include <stdlib.h>

int main() {

    FILE *f;
    char c;
    f=fopen("test.txt","rt");

    while((c=fgetc(f))!=EOF){
        printf("%c",c);
    }

    fclose(f);
    return 0;
}

Regular expression for only characters a-z, A-Z

Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:

var charactersOnly = "This contains only characters";
var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";

if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
  alert("Only characters");
}

if (nonCharacters.search(/[^a-zA-Z]+/)) {
  alert("There are non characters.");
}

The / starting and ending the regular expression signify that it's a regular expression. The search function takes both strings and regexes, so the / are necessary to specify a regex.

From the MDN Docs, the function returns -1 if there is no match.

Also note: that this works for only a-z, A-Z. If there are spaces, it will fail.

Android: Scale a Drawable or background image?

One option to try is to put the image in the drawable-nodpi folder and set background of a layout to the drawable resource id.

This definitely works with scaling down, I haven't tested with scaling up though.

IE prompts to open or save json result from server

Have you tried to send your ajax request using POST method ? You could also try to set content type to 'text/x-json' while returning result from the server.

return error message with actionResult

One approach would be to just use the ModelState:

ModelState.AddModelError("", "Error in cloud - GetPLUInfo" + ex.Message);

and then on the view do something like this:

@Html.ValidationSummary()

where you want the errors to display. If there are no errors, it won't display, but if there are you'll get a section that lists all the errors.

Sending email with gmail smtp with codeigniter email library

You need to enable SSL in your PHP config. Load up php.ini and find a line with the following:

;extension=php_openssl.dll

Uncomment it. :D

(by removing the semicolon from the statement)

extension=php_openssl.dll

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

Ran into this issue with spring boot and jvm 1.7 and 1.8. On AWS, we did not have the option to change the ServerName and ServerAlias to match (they are different) so we did the following:

In build.gradle we added the following:

System.setProperty("jsse.enableSNIExtension", "false")
bootRun.systemProperties = System.properties

That allowed us to bypass the issue with the "Unrecognized Name".

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

convert big endian to little endian in C [without using provided func]

If you need macros (e.g. embedded system):

#define SWAP_UINT16(x) (((x) >> 8) | ((x) << 8))
#define SWAP_UINT32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | ((x) << 24))

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

You just have to remove the bindings before you use 'applyBindings' again.

ko.cleanNode($element[0]);

should do the trick. HTH.

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

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

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

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Convert Dictionary to Data Frame

col_dict_df = pd.Series(col_dict).to_frame('new_col').reset_index()

Give new name to Column

col_dict_df.columns = ['col1', 'col2']

gcc warning" 'will be initialized after'

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

the order is important because if a is initialized before b , and a is depend on b. undefined behavior will appear.

What's the difference between session.persist() and session.save() in Hibernate?

I have done good research on the save() vs. persist() including running it on my local machine several times. All the previous explanations are confusing and incorrect. I compare save() and persist() methods below after a thorough research.

Save()

  1. Returns generated Id after saving. Its return type is Serializable;
  2. Saves the changes to the database outside of the transaction;
  3. Assigns the generated id to the entity you are persisting;
  4. session.save() for a detached object will create a new row in the table.

Persist()

  1. Does not return generated Id after saving. Its return type is void;
  2. Does not save the changes to the database outside of the transaction;
  3. Assigns the generated Id to the entity you are persisting;
  4. session.persist() for a detached object will throw a PersistentObjectException, as it is not allowed.

All these are tried/tested on Hibernate v4.0.1.

Java: int[] array vs int array[]

Both are the same. I usually use int[] array = new int[10];, because of better (contiguous) readability of the type int[].

how to define ssh private key for servers fetched by dynamic inventory in files

I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.

The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):

[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem

Here is the patch for ec2.py:

204a205,206
>     'ssh_key_path': '~/.ssh',
>     'ssh_key_suffix': '.pem',
422a425,428
>         # SSH key setup
>         self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
>         self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
> 
1490a1497
>         instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)

Remove rows with all or some NAs (missing values) in data.frame

Also check complete.cases :

> final[complete.cases(final), ]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
6 ENSG00000221312    0    1    2    3    2

na.omit is nicer for just removing all NA's. complete.cases allows partial selection by including only certain columns of the dataframe:

> final[complete.cases(final[ , 5:6]),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

Your solution can't work. If you insist on using is.na, then you have to do something like:

> final[rowSums(is.na(final[ , 5:6])) == 0, ]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

but using complete.cases is quite a lot more clear, and faster.

How to add extra whitespace in PHP?

is this for display purposes? if so you really should consider separating your display form your logic and use style sheets for formatting. being server side php should really allow providing and accepting data. while you could surely use php to do what you are asking I am a very firm believer in keeping display and logic with as much separation as possible. with styles you can do all of your typesetting.

give output class wrappers and style accordingly.

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

Relative imports for the billionth time

This is really a problem within python. The origin of confusion is that people mistakenly takes the relative import as path relative which is not.

For example when you write in faa.py:

from .. import foo

This has a meaning only if faa.py was identified and loaded by python, during execution, as a part of a package. In that case,the module's name for faa.py would be for example some_packagename.faa. If the file was loaded just because it is in the current directory, when python is run, then its name would not refer to any package and eventually relative import would fail.

A simple solution to refer modules in the current directory, is to use this:

if __package__ is None or __package__ == '':
    # uses current directory visibility
    import foo
else:
    # uses current package visibility
    from . import foo

How to mount host volumes into docker containers in Dockerfile during build

As you run the container, a directory on your host is created and mounted into the container. You can find out what directory this is with

$ docker inspect --format "{{ .Volumes }}" <ID>
map[/export:/var/lib/docker/vfs/dir/<VOLUME ID...>]

If you want to mount a directory from your host inside your container, you have to use the -v parameter and specify the directory. In your case this would be:

docker run -v /export:/export data

SO you would use the hosts folder inside your container.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to call a function from another controller in angularjs?

The best approach for you to communicate between the two controllers is to use events.

See the scope documentation

In this check out $on, $broadcast and $emit.

What does ||= (or-equals) mean in Ruby?

a ||= b is a conditional assignment operator. It means if a is undefined or falsey, then evaluate b and set a to the result. Equivalently, if a is defined and evaluates to truthy, then b is not evaluated, and no assignment takes place. For example:

a ||= nil # => nil
a ||= 0 # => 0
a ||= 2 # => 0

foo = false # => false
foo ||= true # => true
foo ||= false # => true

Confusingly, it looks similar to other assignment operators (such as +=), but behaves differently.

  • a += b translates to a = a + b
  • a ||= b roughly translates to a || a = b

It is a near-shorthand for a || a = b. The difference is that, when a is undefined, a || a = b would raise NameError, whereas a ||= b sets a to b. This distinction is unimportant if a and b are both local variables, but is significant if either is a getter/setter method of a class.

Further reading:

Getting list of tables, and fields in each, in a database

Tables ::

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

columns ::

SELECT * FROM INFORMATION_SCHEMA.COLUMNS 

or

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name'

When is layoutSubviews called?

Some of the points in BadPirate's answer are only partially true:

  1. For addSubView point

    addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.

    It depends on the view's (target view) autoresize mask. If it has autoresize mask ON, layoutSubview will be called on each addSubview. If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes.

    Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview.

    It is through this technique that the performance of the application also increases.

  2. For the device rotation point

    Rotating a device only calls layoutSubview on the parent view (the responding viewController's primary view)

    This can be true only when your VC is in the VC hierarchy (root at window.rootViewController), well this is most common case. In iOS 5, if you create a VC, but it is not added into any another VC, then this VC would not get any noticed when device rotate. Therefore its view would not get noticed by calling layoutSubviews.

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

How to get old Value with onchange() event in text box

element.defaultValue will give you the original value.

Please note that this only works on the initial value.

If you are needing this to persist the "old" value every time it changes, an expando property or similar method will meet your needs

how to modify an existing check constraint?

NO, you can't do it other way than so.

How to change href attribute using JavaScript after opening the link in a new window?

You can delay your code using setTimeout to execute after click

function changeLink(){
    setTimeout(function() {
        var link = document.getElementById("mylink");
        link.setAttribute('href', "http://facebook.com");
        document.getElementById("mylink").innerHTML = "facebook";
    }, 100);
}

Alternative to deprecated getCellType

From the documentation:

int getCellType() Deprecated. POI 3.15. Will return a CellType enum in the future.

Return the cell type. Will return CellType in version 4.0 of POI. For forwards compatibility, do not hard-code cell type literals in your code.

mysqldump exports only one table

try this. There are in general three ways to use mysqldump—

in order to dump a set of one or more tables,

shell> mysqldump [options] db_name [tbl_name ...]

a set of one or more complete databases

shell> mysqldump [options] --databases db_name ...

or an entire MySQL server—as shown here:

shell> mysqldump [options] --all-databases

How do I change the default schema in sql developer?

After you granted the permissions to the specified user you have to do this at filtering:

First step:

First Step to change default Tables

Second step:

Second Step to change default Tables

Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).

How to "test" NoneType in python?

It can also be done with isinstance as per Alex Hall's answer :

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

isinstance is also intuitive but there is the complication that it requires the line

NoneType = type(None)

which isn't needed for types like int and float.

Turn off textarea resizing

Just one extra option, if you want to revert the default behaviour for all textareas in the application, you could add the following to your CSS:

textarea:not([resize="true"]) {
  resize: none !important;
}

And do the following to enable where you want resizing:

<textarea resize="true"></textarea>

Have in mind this solution might not work in all browsers you may want to support. You can check the list of support for resize here: http://caniuse.com/#feat=css-resize

How to drop a list of rows from Pandas dataframe?

In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique. I had to deal with such a situation. What I did was to rename the duplicates in the index before I called drop(), a la:

dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)

where rename_duplicates() is a function I defined that went through the elements of index and renamed the duplicates. I used the same renaming pattern as pd.read_csv() uses on columns, i.e., "%s.%d" % (name, count), where name is the name of the row and count is how many times it has occurred previously.

MySQL config file location - redhat linux server

Default options are read from the following files in the given order:

/etc/mysql/my.cnf 
/etc/my.cnf 
~/.my.cnf 

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Here is mine simple and one line solution.

It searches not unique elements first, then makes found array unique with the use of Set.

So we have array of duplicates in the end.

_x000D_
_x000D_
var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];_x000D_
_x000D_
console.log([...new Set(_x000D_
  array.filter((value, index, self) => self.indexOf(value) !== index))]_x000D_
);
_x000D_
_x000D_
_x000D_

moment.js get current time in milliseconds?

See this link http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/

valueOf() is the function you're looking for.

Editing my answer (OP wants milliseconds of today, not since epoch)

You want the milliseconds() function OR you could go the route of moment().valueOf()

jQuery Multiple ID selectors

That should work, you may need a space after the commas.

Also, the function you call afterwards must support an array of objects, and not just a singleton object.

Asserting successive calls to a mock method

Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call with an assertion about call_count.

>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
    '%s call not found' % expected_string
AssertionError: mock(4) call not found

I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.

If you do care about order or you expect multiple identical calls, assert_has_calls might be more appropriate.

Edit

Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.

How to find the sum of an array of numbers

Use a for loop:

const array = [1, 2, 3, 4];
let result = 0;

for (let i = 0; i < array.length - 1; i++) {
  result += array[i];
}

console.log(result); // Should give 10

Or even a forEach loop:

const array = [1, 2, 3, 4];
let result = 0;

array.forEach(number => {
  result += number;
})

console.log(result); // Should give 10

For simplicity, use reduce:

const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);

console.log(result); // Should give 100

Permanently Set Postgresql Schema Path

(And if you have no admin access to the server)

ALTER ROLE <your_login_role> SET search_path TO a,b,c;

Two important things to know about:

  1. When a schema name is not simple, it needs to be wrapped in double quotes.
  2. The order in which you set default schemas a, b, c matters, as it is also the order in which the schemas will be looked up for tables. So if you have the same table name in more than one schema among the defaults, there will be no ambiguity, the server will always use the table from the first schema you specified for your search_path.

Linux Script to check if process is running and act on the result

I have adopted your script for my situation Jotne.

#! /bin/bash

logfile="/var/oscamlog/oscam1check.log"

case "$(pidof oscam1 | wc -w)" in

0)  echo "oscam1 not running, restarting oscam1:     $(date)" >> $logfile
    /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
    ;;
2)  echo "oscam1 running, all OK:     $(date)" >> $logfile
    ;;
*)  echo "multiple instances of oscam1 running. Stopping & restarting oscam1:     $(date)" >> $logfile
    kill $(pidof oscam1 | awk '{print $1}')
    ;;
esac

While I was testing, I ran into a problem.. I started 3 extra process's of oscam1 with this line: /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 which left me with 8 process for oscam1. the problem is this.. When I run the script, It only kills 2 process's at a time, so I would have to run it 3 times to get it down to 2 process..

Other than killall -9 oscam1 followed by /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1, in *)is there any better way to killall apart from the original process? So there would be zero downtime?

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

To sum up, 'valid' padding means no padding. The output size of the convolutional layer shrinks depending on the input size & kernel size.

On the contrary, 'same' padding means using padding. When the stride is set as 1, the output size of the convolutional layer maintains as the input size by appending a certain number of '0-border' around the input data when calculating convolution.

Hope this intuitive description helps.

Converting json results to a date

If you use jQuery

In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.

You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.

It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).

Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html

What is the difference between encode/decode?

The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.

unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so:

>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

The error messages are exactly the same.

For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding:

>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)

Used like this, str().encode() is also superfluous.

But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:

>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'

You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue.

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

Eclipse Intellisense?

I've get closer to VisualStudio-like behaviour by setting the "Autocomplete Trigger for Java" to

.(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

and setting delay to 0.

Now I'd like to realize how to make it autocomplete method name when I press ( as VS's Intellisense does.

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had similar problem while using in postman. for POST request under header section add these as

key:valuepair

Content-Type:application/json Accept:application/json

i hope it will work.

Equal sized table cells to fill the entire width of the containing table

Just use percentage widths and fixed table layout:

<table>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>
</table>

with

table { table-layout: fixed; }
td { width: 33%; }

Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.

Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.

"Actual or formal argument lists differs in length"

You try to instantiate an object of the Friends class like this:

Friends f = new Friends(friendsName, friendsAge);

The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:

Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);

Download all stock symbol list of a market

This may be old, but... if you change the link in google stock list as below:

https://www.google.com/finance?q=%5B(exchange%20%3D%3D%20%22NASDAQ%22)%5D&restype=company&noIL=1&num=30000

  • note for the noIL=1&num=30000

It means, starting for row 1 to 30000. It shows all results in one page.

You may automate it using any language or just export the table to excel.

Hope it helps.

Scala vs. Groovy vs. Clojure

I never had time to play with clojure. But for scala vs groovy, this is words from James Strachan - Groovy creator

"Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy."

You can read the whole story here

How do you style a TextInput in react native for password input

You can get the example and sample code at the official site, as following:

<TextInput password={true} style={styles.default} value="abc" />

Reference: http://facebook.github.io/react-native/docs/textinput.html

Find (and kill) process locking port 3000 on Mac

In your .bash_profile, create a shortcut for terminate the 3000 process:

terminate(){
  lsof -P | grep ':3000' | awk '{print $2}' | xargs kill -9 
}

Then, call $terminate if it's blocked.

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

The other answers gave me the right clues, but they didn't completely help.

Here's what worked for me:

$ git checkout email
$ git tag old-email-branch # This is optional
$ git reset --hard staging
$
$ # Using a custom commit message for the merge below
$ git merge -m 'Merge -s our where _ours_ is the branch staging' -s ours origin/email
$ git push origin email

Without the fourth step of merging with the ours strategy, the push is considered a non-fast-forward update and will be rejected (by GitHub).

How to use protractor to check if an element is visible?

To wait for visibility

const EC = protractor.ExpectedConditions;
browser.wait(EC.visibilityOf(element(by.css('.icon-spinner icon-spin ng-hide')))).then(function() {
  //do stuff
})

Xpath trick to only find visible elements

element(by.xpath('//i[not(contains(@style,"display:none")) and @class="icon-spinner icon-spin ng-hide"]))

Disabling same-origin policy in Safari

There is an option to disable cross-origin restrictions in Safari 9, different from local file restrictions as mentioned above.

Converting a double to an int in Javascript without rounding

I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.

A trick that avoids a function call entirely is

var truncated = ~~number;

The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).

edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:

var truncated = number|0;

Does "\d" in regex mean a digit?

This is just a guess, but I think your editor actually matches every single digit — 1 2 3 — but only odd matches are highlighted, to distinguish it from the case when the whole 123 string is matched.

Most regex consoles highlight contiguous matches with different colors, but due to the plugin settings, terminal limitations or for some other reason, only every other group might be highlighted in your case.

How to scroll to specific item using jQuery?

Contrary to what most people here are suggesting, I'd recommend you do use a plugin if you want to animate the move. Just animating scrollTop is not enough for a smooth user experience. See my answer here for the reasoning.

I have tried a number of plugins over the years, but eventually written one myself. You might want to give it a spin: jQuery.scrollable. Using that, the scroll action becomes

$container.scrollTo( targetPosition );

But that's not all. We need to fix the target position, too. The calculation you see in other answers,

$target.offset().top - $container.offset().top + $container.scrollTop()

mostly works but is not entirely correct. It doesn't handle the border of the scroll container properly. The target element is scrolled upwards too far, by the size of the border. Here is a demo.

Hence, a better way to calculate the target position is

var target = $target[0], 
    container = $container[0];

targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;

Again, have a look at the demo to see it in action.

For a function which returns the target position and works for both window and non-window scroll containers, feel free to use this gist. The comments in there explain how the position is calculated.

In the beginning, I have said it would be best to use a plugin for animated scrolling. You don't need a plugin, however, if you want to jump to the target without a transition. See the answer by @James for that, but make sure you calculate the target position correctly if there is a border around the container.

How can you profile a Python script?

To add on to https://stackoverflow.com/a/582337/1070617,

I wrote this module that allows you to use cProfile and view its output easily. More here: https://github.com/ymichael/cprofilev

$ python -m cprofilev /your/python/program
# Go to http://localhost:4000 to view collected statistics.

Also see: http://ymichael.com/2014/03/08/profiling-python-with-cprofile.html on how to make sense of the collected statistics.

In Python, can I call the main() of an imported module?

Martijen's answer makes sense, but it was missing something crucial that may seem obvious to others but was hard for me to figure out.

In the version where you use argparse, you need to have this line in the main body.

args = parser.parse_args(args)

Normally when you are using argparse just in a script you just write

args = parser.parse_args()

and parse_args find the arguments from the command line. But in this case the main function does not have access to the command line arguments, so you have to tell argparse what the arguments are.

Here is an example

import argparse
import sys

def x(x_center, y_center):
    print "X center:", x_center
    print "Y center:", y_center

def main(args):
    parser = argparse.ArgumentParser(description="Do something.")
    parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
    parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
    args = parser.parse_args(args)
    x(args.xcenter, args.ycenter)

if __name__ == '__main__':
    main(sys.argv[1:])

Assuming you named this mytest.py To run it you can either do any of these from the command line

python ./mytest.py -x 8
python ./mytest.py -x 8 -y 2
python ./mytest.py 

which returns respectively

X center: 8.0
Y center: 4

or

X center: 8.0
Y center: 2.0

or

X center: 2
Y center: 4

Or if you want to run from another python script you can do

import mytest
mytest.main(["-x","7","-y","6"]) 

which returns

X center: 7.0
Y center: 6.0

How to make Google Fonts work in IE?

You can try fontsforweb.com where fonts are working for all browsers, because they are provided in TTF, WOFF and EOT formats together with CSS code ready to be pasted on your page i.e.

@font-face{ 
    font-family: "gothambold1";
    src: url('http://fontsforweb.com/public/fonts/5903/gothambold1.eot');
    src: local("Gotham-Bold"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.woff') format("woff"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.ttf') format("truetype");
}
.fontsforweb_fontid_5903 {
    font-family: "gothambold1";
}

or you can download them zipped in a package with CSS file attached

then just add class to any element to apply that font i.e.

<h2 class="fontsforweb_fontid_5903">This will be written with Gotham Bold font and will work in all browsers</h2>

See it working: http://jsfiddle.net/SD4MP/

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

Sometimes you have to upgrade your Curl certificates to latest version not to have errors with https.

How to increase time in web.config for executing sql query

I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:

  • DB connection string Connect Timeout
  • httpRuntime executionTimeout
  • basicHttpBinding binding closeTimeout
  • basicHttpBinding binding sendTimeout
  • basicHttpBinding binding receiveTimeout
  • basicHttpBinding binding openTimeout

Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.

I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.

Some code:

namespace ROS.WebService.Common
{
  using System;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;

  public static class DataAccess
  {
    public static string ConnectionString { get; private set; }

    static DataAccess()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
    }

    public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
    {
      using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
      {
        using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
        {
          foreach (var p in sqlParams) cmd.Parameters.Add(p);
          cmd.Connection.Open();
          return cmd.ExecuteNonQuery();
        }
      }
    }
  }
}

Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout

Ansible - Save registered variable to file

---
- hosts: all
  tasks:
  - name: Gather Version
    debug:
     msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
  - name: Write  Version
    local_action: shell echo "This is  {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output

How does the keyword "use" work in PHP and can I import classes with it?

Namespace is use to define the path to a specific file containing a class e.g.

namespace album/className; 

class className{
//enter class properties and methods here
}

You can then include this specific class into another php file by using the keyword "use" like this:

use album/className;

class album extends classname {
//enter class properties and methods
}

NOTE: Do not use the path to the file containing the class to be implements, extends of use to instantiate an object but only use the namespace.

How to use external ".js" files

In your head element add

<script type="text/javascript" src="myscript.js"></script>

TypeError: Object of type 'bytes' is not JSON serializable

You are creating those bytes objects yourself:

item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)

Each of those t.encode(), l.encode() and d.encode() calls creates a bytes string. Do not do this, leave it to the JSON format to serialise these.

Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json module and the standard file object returned by the open() call to handle encoding.

You also don't need to convert your items list to a dictionary; it'll already be an object that can be JSON encoded directly:

class W3SchoolPipeline(object):    
    def __init__(self):
        self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(item) + '\n'
        self.file.write(line)
        return item

I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape') it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.

javascript regex : only english letters allowed

Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"

Here's a DEMO on how this regex works with test() and match().

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:

Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

How to check if an integer is in a given range?

if you are using Spring data you can also use the Range object from Spring.

range = new org.springframework.data.domain.Range(3, 8); range.contains(5) will return true.

Twitter Bootstrap add active class to li

Try this.

// Remove active for all items.
$('.page-sidebar-menu li').removeClass('active');

// highlight submenu item
$('li a[href="' + this.location.pathname + '"]').parent().addClass('active');

// Highlight parent menu item.
$('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active');

How to apply bold text style for an entire row using Apache POI?

This work for me

I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0); 
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);

How to count the number of occurrences of a character in an Oracle varchar value?

here is a solution that will function for both characters and substrings:

select (length('a') - nvl(length(replace('a','b')),0)) / length('b')
  from dual

where a is the string in which you search the occurrence of b

have a nice day!

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

How to repair a serialized string which has been corrupted by an incorrect byte count length?

I don't have enough reputation to comment, so I hope this is seen by people using the above "correct" answer:

Since php 5.5 the /e modifier in preg_replace() has been deprecated completely and the preg_match above will error out. The php documentation recommends using preg_match_callback in its place.

Please find the following solution as an alternative to the above proposed preg_match.

$fixed_data = preg_replace_callback ( '!s:(\d+):"(.*?)";!', function($match) {      
    return ($match[1] == strlen($match[2])) ? $match[0] : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
},$bad_data );

Interactive shell using Docker Compose

You can do docker-compose exec SERVICE_NAME sh on the command line. The SERVICE_NAME is defined in your docker-compose.yml. For example,

services:
    zookeeper:
        image: wurstmeister/zookeeper
        ports:
          - "2181:2181"

The SERVICE_NAME would be "zookeeper".

How to clone an InputStream?

You can't clone it, and how you are going to solve your problem depends on what the source of the data is.

One solution is to read all data from the InputStream into a byte array, and then create a ByteArrayInputStream around that byte array, and pass that input stream into your method.

Edit 1: That is, if the other method also needs to read the same data. I.e you want to "reset" the stream.

How to remove the Flutter debug banner?

Here are 3 ways to do it

  • 1 : On your MaterialApp set debugShowCheckedModeBanner to false.

     MaterialApp(
       debugShowCheckedModeBanner: false
     )
    

    The slow banner will also automatically be removed on release build.

  • 2 : If you are using Android Studio, you can find the option in the Flutter Inspector tab --> More Actions. enter image description here

  • 3 : There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false," code line in main. dart file. So I think these methods are effective:

    --> If you are using VS Code, then install "Dart DevTools" from extensions. After installation, you can easily find "Dart DevTools" text icon at the bottom of VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown.

enter image description here

For more info: How_to_remove_debug_banner_in_flutter_on_android_emulator

How to make a website secured with https

I think you are getting confused with your site Authentication and SSL.

If you need to get your site into SSL, then you would need to install a SSL certificate into your web server. You can buy a certificate for yourself from one of the places like Symantec etc. The certificate would contain your public/private key pair, along with other things.

You wont need to do anything in your source code, and you can still continue to use your Form Authntication (or any other) in your site. Its just that, any data communication that takes place between the web server and the client will encrypted and signed using your certificate. People would use secure-HTTP (https://) to access your site.

View this for more info --> http://en.wikipedia.org/wiki/Transport_Layer_Security

Dump a mysql database to a plaintext (CSV) backup from the command line

You can dump a whole database in one go with mysqldump's --tab option. You supply a directory path and it creates one .sql file with the CREATE TABLE DROP IF EXISTS syntax and a .txt file with the contents, tab separated. To create comma separated files you could use the following:

mysqldump --password  --fields-optionally-enclosed-by='"' --fields-terminated-by=',' --tab /tmp/path_to_dump/ database_name

That path needs to be writable by both the mysql user and the user running the command, so for simplicity I recommend chmod 777 /tmp/path_to_dump/ first.

What does the "+" (plus sign) CSS selector mean?

+ selector is called Adjacent Sibling Selector.

For example, the selector p + p, selects the p elements immediately following the p elements

It can be thought of as a looking outside selector which checks for the immediately following element.

Here is a sample snippet to make things more clear:

_x000D_
_x000D_
body {_x000D_
  font-family: Tahoma;_x000D_
  font-size: 12px;_x000D_
}_x000D_
p + p {_x000D_
  margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
  <p>Header paragraph</p>_x000D_
  <p>This is a paragraph</p>_x000D_
  <p>This is another paragraph</p>_x000D_
  <p>This is yet another paragraph</p>_x000D_
  <hr>_x000D_
  <p>Footer paragraph</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Since we are one the same topic, it is worth mentioning another selector, ~ selector, which is General Sibling Selector

For example, p ~ p selects all the p which follows the p doesn't matter where it is, but both p should be having the same parent.

Here is how it looks like with the same markup:

_x000D_
_x000D_
body {_x000D_
  font-family: Tahoma;_x000D_
  font-size: 12px;_x000D_
}_x000D_
p ~ p {_x000D_
  margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
  <p>Header paragraph</p>_x000D_
  <p>This is a paragraph</p>_x000D_
  <p>This is another paragraph</p>_x000D_
  <p>This is yet another paragraph</p>_x000D_
  <hr>_x000D_
  <p>Footer paragraph</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Notice that the last p is also matched in this sample.

"Eliminate render-blocking CSS in above-the-fold content"

The 2019 optimal solution for this is HTTP/2 Server Push.

You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.

My site https://r.je/ has a 100/100 score for both mobile and desktop.

The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.

You can use HTTP/2 push by setting the Link header.

Apache example (.htaccess):

Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"

For NGINX you can add the header to your location tag in the server configuration:

location = / {
    add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}

With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.

You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"

For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

The redirect function probably works by using the 'refresh' http header (and maybe using a 30X code as well). Once the headers have been sent to the client, there is not way for the server to append that redirect command, its too late.

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset) manually. The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.

Append an empty row in dataframe using pandas

Add a new pandas.Series using pandas.DataFrame.append().

If you wish to specify the name (AKA the "index") of the new row, use:

df.append(pandas.Series(name='NameOfNewRow'))

If you don't wish to name the new row, use:

df.append(pandas.Series(), ignore_index=True)

where df is your pandas.DataFrame.

Get the first key name of a JavaScript object

With Underscore.js, you could do

_.find( {"one": [1,2,3], "two": [4,5,6]} )

It will return [1,2,3]

How to comment out a block of Python code in Vim

There's a lot of comment plugins for vim - a number of which are multi-language - not just python. If you use a plugin manager like Vundle then you can search for them (once you've installed Vundle) using e.g.:

:PluginSearch comment

And you will get a window of results. Alternatively you can just search vim-scripts for comment plugins.

send Content-Type: application/json post with node.js

Mikeal's request module can do this easily:

var request = require('request');

var options = {
  uri: 'https://www.googleapis.com/urlshortener/v1/url',
  method: 'POST',
  json: {
    "longUrl": "http://www.google.com/"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:

  • Mis-aligned access might be a hard error (often SIGBUS).
  • Mis-aligned access might be a soft error.
    • Either corrected in hardware, for a modest performance-degradation.
    • Or corrected by emulation in software, for a severe performance-degradation.
    • In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.

Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):

struct X
{
    short s; /* 2 bytes */
             /* 2 padding bytes */
    int   i; /* 4 bytes */
    char  c; /* 1 byte */
             /* 3 padding bytes */
};

struct Y
{
    int   i; /* 4 bytes */
    char  c; /* 1 byte */
             /* 1 padding byte */
    short s; /* 2 bytes */
};

struct Z
{
    int   i; /* 4 bytes */
    short s; /* 2 bytes */
    char  c; /* 1 byte */
             /* 1 padding byte */
};

const int sizeX = sizeof(struct X); /* = 12 */
const int sizeY = sizeof(struct Y); /* = 8 */
const int sizeZ = sizeof(struct Z); /* = 8 */

One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure Z in the example above).

IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special #pragma statements to change the structure alignment settings.

How do I reverse an int array in Java?

Here is a simple implementation, to reverse array of any type, plus full/partial support.

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

Here is the corresponding Unit Test

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}

How to check if a Docker image with a specific tag exist locally?

In case you are trying to search for a docker image from a docker registry, I guess the easiest way to check if a docker image is present is by using the Docker V2 REST API Tags list service

Example:-

curl $CURLOPTS -H "Authorization: Bearer $token" "https://hub.docker.com:4443/v2/your-repo-name/tags/list"

if the above result returns 200Ok with a list of image tags, then we know that image exists

{"name":"your-repo-name","tags":["1.0.0.1533677221","1.0.0.1533740305","1.0.0.1535659921","1.0.0.1535665433","latest"]}

else if you see something like

{"errors":[{"code":"NAME_UNKNOWN","message":"repository name not known to registry","detail":{"name":"your-repo-name"}}]} 

then you know for sure that image doesn't exist.

Best Practice: Access form elements by HTML id or name attribute?

name field works well. It provides a reference to the elements.

parent.children - Will list all elements with a name field of the parent. parent.elements - Will list only form elements such as input-text, text-area, etc

_x000D_
_x000D_
var form = document.getElementById('form-1');_x000D_
console.log(form.children.firstname)_x000D_
console.log(form.elements.firstname)_x000D_
console.log(form.elements.progressBar); // undefined_x000D_
console.log(form.children.progressBar);_x000D_
console.log(form.elements.submit); // undefined
_x000D_
<form id="form-1">_x000D_
  <input type="text" name="firstname" />_x000D_
  <input type="file" name="file" />_x000D_
  <progress name="progressBar" value="20" min="0" max="100" />_x000D_
  <textarea name="address"></textarea>_x000D_
  <input type="submit" name="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note: For .elements to work, the parent needs to be a <form> tag. Whereas, .children will work on any HTML-element - such as <div>, <span>, etc.

Good Luck...

How to call on a function found on another file?

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Below is the exact code you need to make your sheet look exactly as it is in the attached PDF:

try
        {
            Excel.Application application;
            Excel.Workbook workBook;
            Excel.Worksheet workSheet;
            object misValue = System.Reflection.Missing.Value;

            application = new Excel.ApplicationClass();
            workBook = application.Workbooks.Add(misValue);
            workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);

            int i = 1;
            workSheet.Cells[i, 2] = "MSS Close Sheet"; 
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;               
            i++;
            workSheet.Cells[i, 2] = "MSS - " + dpsNoTextBox.Text;
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;
            workSheet.Cells[i, 2] = customerNameTextBox.Text;
            i++;                
            workSheet.Cells[i, 2] = "Opening Date : ";
            workSheet.Cells[i, 3] = openingDateTextBox.Value.ToShortDateString();
            i++;
            workSheet.Cells[i, 2] = "Closing Date : ";
            workSheet.Cells[i, 3] = closingDateTextBox.Value.ToShortDateString();
            i++;
            i++;
            i++;

            workSheet.Cells[i, 1] = "SL. No";
            workSheet.Cells[i, 2] = "Month";
            workSheet.Cells[i, 3] = "Amount Deposited";
            workSheet.Cells[i, 4] = "Fine";
            workSheet.Cells[i, 5] = "Cumulative Total";
            workSheet.Cells[i, 6] = "Profit + Cumulative Total";
            workSheet.Cells[i, 7] = "Profit @ " + profitRateComboBox.Text;
            WorkSheet.Cells[i, 1].EntireRow.Font.Bold = true;
            i++;



            /////////////////////////////////////////////////////////
            foreach (RecurringDeposit rd in RecurringDepositList)
            {
                workSheet.Cells[i, 1] = rd.SN.ToString();
                workSheet.Cells[i, 2] = rd.MonthYear;
                workSheet.Cells[i, 3] = rd.InstallmentSize.ToString();
                workSheet.Cells[i, 4] = "";
                workSheet.Cells[i, 5] = rd.CumulativeTotal.ToString();
                workSheet.Cells[i, 6] = rd.ProfitCumulative.ToString();
                workSheet.Cells[i, 7] = rd.Profit.ToString();
                i++;
            }
            //////////////////////////////////////////////////////


            ////////////////////////////////////////////////////////
            workSheet.Cells[i, 2] = "Total (" + RecurringDepositList.Count + " months installment)";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "a) Total Amount Deposited";
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "b) Fine";
            workSheet.Cells[i, 3] = "";
            i++;

            workSheet.Cells[i, 2] = "c) Total Pft Paid";
            workSheet.Cells[i, 3] = totalProfitPaidTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Sub Total";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (totalAmountDepositedTextBox.Value + totalProfitPaidTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Deduction";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;

            workSheet.Cells[i, 2] = "a) Excise Duty";
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "b) Income Tax on Pft. @ " + incomeTaxPercentageTextBox.Text;
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "c) Account Closing Charge ";
            workSheet.Cells[i, 3] = closingChargeCommaNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "d) Outstanding on BAIM(FO) ";
            workSheet.Cells[i, 3] = baimFOLowerTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Total Deduction ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (incomeTaxDeductionTextBox.Value + closingChargeCommaNumberTextBox.Value + baimFOTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Client Paid ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Current Balance ";
            workSheet.Cells[i, 3] = currentBalanceCommaNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "Exp. Pft paid on MSS A/C(PL67054)";
            workSheet.Cells[i, 6] = plTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Total Paid ";
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "IT on Pft (BDT16216)";
            workSheet.Cells[i, 6] = incomeTaxDeductionTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Difference";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (currentBalanceCommaNumberTextBox.Value - customerPayableNumberTextBox.Value).ToString("0.00");
            workSheet.Cells[i, 5] = "Account Closing Charge";
            workSheet.Cells[i, 6] = closingChargeCommaNumberTextBox.Value;
            i++;

            ///////////////////////////////////////////////////////////////

            workBook.SaveAs("D:\\" + dpsNoTextBox.Text.Trim() + "-" + customerNameTextBox.Text.Trim() + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            workBook.Close(true, misValue, misValue);
            application.Quit();

            releaseObject(workSheet);
            releaseObject(workBook);
            releaseObject(application);

Angular 4 - Select default value in dropdown [Reactive Forms]

Try like this :

component.html

<form [formGroup]="countryForm">
    <select id="country" formControlName="country">
        <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
    </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component {

    countries: string[] = ['USA', 'UK', 'Canada'];
    default: string = 'UK';

    countryForm: FormGroup;

    constructor() {
        this.countryForm = new FormGroup({
            country: new FormControl(null);
        });
        this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
    }
}

How do I trim whitespace from a string?

As pointed out in answers above

my_string.strip()

will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space .

For more flexibility use the following

  • Removes only leading whitespace chars: my_string.lstrip()
  • Removes only trailing whitespace chars: my_string.rstrip()
  • Removes specific whitespace chars: my_string.strip('\n') or my_string.lstrip('\n\r') or my_string.rstrip('\n\t') and so on.

More details are available in the docs.

Sort a Map<Key, Value> by values

posting my version of answer

List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
    Collections.sort(list, (obj1, obj2) -> obj2.getValue().compareTo(obj1.getValue()));
    Map<String, Integer> resultMap = new LinkedHashMap<>();
    list.forEach(arg0 -> {
        resultMap.put(arg0.getKey(), arg0.getValue());
    });
    System.out.println(resultMap);

Changing cell color using apache poi

Short version: Create styles only once, use them everywhere.

Long version: use a method to create the styles you need (beware of the limit on the amount of styles).

private static Map<String, CellStyle> styles;

private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        DataFormat df = wb.createDataFormat();

        CellStyle style;
        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeightInPoints((short) 12);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFont(headerFont);
        styles.put("style1", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("date_style", style);
        ...
        return styles;
    }

you can also use methods to do repetitive tasks while creating styles hashmap

private static CellStyle createBorderedStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        return style;
    }

then, in your "main" code, set the style from the styles map you have.

Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );

How do I kill the process currently using a port on localhost in Windows?

In case you want to do it using Python: check Is it possible in python to kill process that is listening on specific port, for example 8080?

The answer from Smunk works nicely. I repeat his code here:

from psutil import process_iter
from signal import SIGTERM # or SIGKILL

for proc in process_iter():
    for conns in proc.connections(kind='inet'):
        if conns.laddr.port == 8080:
            proc.send_signal(SIGTERM) # or SIGKILL
            continue

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

iOS: Multi-line UILabel in Auto Layout

Source: http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html

Intrinsic Content Size of Multi-Line Text

The intrinsic content size of UILabel and NSTextField is ambiguous for multi-line text. The height of the text depends on the width of the lines, which is yet to be determined when solving the constraints. In order to solve this problem, both classes have a new property called preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.

Since we usually don’t know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again.

- (void)layoutSubviews
{
    [super layoutSubviews];
    myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
    [super layoutSubviews];
}

The first call to [super layoutSubviews] is necessary for the label to get its frame set, while the second call is necessary to update the layout after the change. If we omit the second call we get a NSInternalInconsistencyException error, because we’ve made changes in the layout pass which require updating the constraints, but we didn’t trigger layout again.

We can also do this in a label subclass itself:

@implementation MyLabel
- (void)layoutSubviews
{
    self.preferredMaxLayoutWidth = self.frame.size.width;
    [super layoutSubviews];
}
@end

In this case, we don’t need to call [super layoutSubviews] first, because when layoutSubviews gets called, we already have a frame on the label itself.

To make this adjustment from the view controller level, we hook into viewDidLayoutSubviews. At this point the frames of the first Auto Layout pass are already set and we can use them to set the preferred maximum width.

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
    [self.view layoutIfNeeded];
}

Lastly, make sure that you don’t have an explicit height constraint on the label that has a higher priority than the label’s content compression resistance priority. Otherwise it will trump the calculated height of the content. Make sure to check all the constraints that can affect label's height.

UIWebView open links in Safari

The accepted answer does not work.

If your page loads URLs via Javascript, the navigationType will be UIWebViewNavigationTypeOther. Which, unfortunately, also includes background page loads such as analytics.

To detect page navigation, you need to compare the [request URL] to the [request mainDocumentURL].

This solution will work in all cases:

- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type
{
    if ([[request URL] isEqual:[request mainDocumentURL]])
    {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    else
    {       
        return YES;
    }
}

Deserializing JSON Object Array with Json.net

Using the accepted answer you have to access each record by using Customers[i].customer, and you need an extra CustomerJson class, which is a little annoying. If you don't want to do that, you can use the following:

public class CustomerList
{
    [JsonConverter(typeof(MyListConverter))]
    public List<Customer> customer { get; set; }
}

Note that I'm using a List<>, not an Array. Now create the following class:

class MyListConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Values())
        {
            var childToken = child.Children().First();
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(childToken.CreateReader(), newObject);
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}

How to write hello world in assembler under Windows?

NASM examples.

Calling libc stdio printf, implementing int main(){ return printf(message); }

; ----------------------------------------------------------------------------
; helloworld.asm
;
; This is a Win32 console program that writes "Hello, World" on one line and
; then exits.  It needs to be linked with a C library.
; ----------------------------------------------------------------------------

    global  _main
    extern  _printf

    section .text
_main:
    push    message
    call    _printf
    add     esp, 4
    ret
message:
    db  'Hello, World', 10, 0

Then run

nasm -fwin32 helloworld.asm
gcc helloworld.obj
a

There's also The Clueless Newbies Guide to Hello World in Nasm without the use of a C library. Then the code would look like this.

16-bit code with MS-DOS system calls: works in DOS emulators or in 32-bit Windows with NTVDM support. Can't be run "directly" (transparently) under any 64-bit Windows, because an x86-64 kernel can't use vm86 mode.

org 100h
mov dx,msg
mov ah,9
int 21h
mov ah,4Ch
int 21h
msg db 'Hello, World!',0Dh,0Ah,'$'

Build this into a .com executable so it will be loaded at cs:100h with all segment registers equal to each other (tiny memory model).

Good luck.

jQuery get content between <div> tags

This is probably what you need:

$('div').html();

demo

This says get the div and return all the contents inside it. See more here: http://api.jquery.com/html/

If you had many divs on the page and needed to target just one, you could set an id on the div and call it like so

$('#whatever').html();

where whatever is the id

EDIT

Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:

var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);

Demo Here

  1. get the length of the string.
  2. find out where the first div occurs
  3. slice the content there.

A child container failed during start java.util.concurrent.ExecutionException

This issue might also be caused by a broken Maven repository.

I observe the SEVERE: A child container failed during start message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml files), Eclipse starts downloading libraries specified in pom.xml into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.

So, this is how you could resolve the issue.

  1. Close your Eclipse.
  2. If you know which specific jar-file is broken in Maven repository, then delete that file.
  3. If you do not know which file is broken in Maven repository, then delete the whole repository (rm -rf $HOME/.m2).
  4. For each project, run mvn package in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.
  5. Open your Eclipse.

What is the iPhone 4 user-agent?

  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en_us) AppleWebKit/525.18.1 (KHTML, like Gecko)
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5

...for now

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {
}

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.

Update

The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 
    $_POST['postcode']

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
));

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");
}

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

pandas GroupBy columns with NaN (missing) values

One small point to Andy Hayden's solution – it doesn't work (anymore?) because np.nan == np.nan yields False, so the replace function doesn't actually do anything.

What worked for me was this:

df['b'] = df['b'].apply(lambda x: x if not np.isnan(x) else -1)

(At least that's the behavior for Pandas 0.19.2. Sorry to add it as a different answer, I do not have enough reputation to comment.)

Why is enum class preferred over plain enum?

It's worth noting, on top of these other answers, that C++20 solves one of the problems that enum class has: verbosity. Imagining a hypothetical enum class, Color.

void foo(Color c)
  switch (c) {
    case Color::Red: ...;
    case Color::Green: ...;
    case Color::Blue: ...;
    // etc
  }
}

This is verbose compared to the plain enum variation, where the names are in the global scope and therefore don't need to be prefixed with Color::.

However, in C++20 we can use using enum to introduce all of the names in an enum to the current scope, solving the problem.

void foo(Color c)
  using enum Color;
  switch (c) {
    case Red: ...;
    case Green: ...;
    case Blue: ...;
    // etc
  }
}

So now, there is no reason not to use enum class.

Allow docker container to connect to a local/host postgres database

In Ubuntu:

First You have to check that is the Docker Database port is Available in your system by following command -

sudo iptables -L -n

Sample OUTPUT:

Chain DOCKER (1 references)
target     prot opt source               destination         
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.2           tcp dpt:3306
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:80
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:22

Here 3306 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

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

Now, You can easily access the Docker Database from your local system by following configuration

  host: 172.17.0.2 
  adapter: mysql
  database: DATABASE_NAME
  port: 3307
  username: DATABASE_USER
  password: DATABASE_PASSWORD
  encoding: utf8

In CentOS:

First You have to check that is the Docker Database port is Available in your firewall by following command -

sudo firewall-cmd --list-all

Sample OUTPUT:

  target: default
  icmp-block-inversion: no
  interfaces: eno79841677
  sources: 
  services: dhcpv6-client ssh
  **ports: 3307/tcp**
  protocols: 
  masquerade: no
  forward-ports: 
  sourceports: 
  icmp-blocks: 
  rich rules:

Here 3307 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

sudo firewall-cmd --zone=public --add-port=3307/tcp

In server, You can add the port permanently

sudo firewall-cmd --permanent --add-port=3307/tcp
sudo firewall-cmd --reload

Now, You can easily access the Docker Database from your local system by the above configuration.