Programs & Examples On #Relational database

A relational database is a database consisting of relation variables (which are also called *relvars*, *R-tables* or just *tables*). The definition, manipulation and integrity rules of relational databases are based on relational operations equivalent to or similar to the Relational Algebra and Calculus. Relational database principles are the basis of a substantial part of data management theory and practice.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043

Foreign Key to multiple tables

Yet another option is to have, in Ticket, one column specifying the owning entity type (User or Group), second column with referenced User or Group id and NOT to use Foreign Keys but instead rely on a Trigger to enforce referential integrity.

Two advantages I see here over Nathan's excellent model (above):

  • More immediate clarity and simplicity.
  • Simpler queries to write.

What is the difference between Views and Materialized Views in Oracle?

View: View is just a named query. It doesn't store anything. When there is a query on view, it runs the query of the view definition. Actual data comes from table.

Materialised views: Stores data physically and get updated periodically. While querying MV, it gives data from MV.

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

This is an old question with valuable answers, but I was still a bit confused until I found a real life example that shows the issue with 3NF. Maybe not suitable for an 8-year old child but hope it helps.

Tomorrow I'll meet the teachers of my eldest daughter in one of those quarterly parent/teachers meetings. Here's what my diary looks like (names and rooms have been changed):

Teacher   | Date             | Room
----------|------------------|-----
Mr Smith  | 2018-12-18 18:15 | A12 
Mr Jones  | 2018-12-18 18:30 | B10 
Ms Doe    | 2018-12-18 18:45 | C21 
Ms Rogers | 2018-12-18 19:00 | A08 

There's only one teacher per room and they never move. If you have a look, you'll see that: (1) for every attribute Teacher, Date, Room, we have only one value per row. (2) super-keys are: (Teacher, Date, Room), (Teacher, Date) and (Date, Room) and candidate keys are obviously (Teacher, Date) and (Date, Room).

(Teacher, Room) is not a superkey because I will complete the table next quarter and I may have a row like this one (Mr Smith did not move!):

Teacher  | Date             | Room
---------|------------------| ----
Mr Smith | 2019-03-19 18:15 | A12

What can we conclude? (1) is an informal but correct formulation of 1NF. From (2) we see that there is no "non prime attribute": 2NF and 3NF are given for free.

My diary is 3NF. Good! No. Not really because no data modeler would accept this in a DB schema. The Room attribute is dependant on the Teacher attribute (again: teachers do not move!) but the schema does not reflect this fact. What would a sane data modeler do? Split the table in two:

Teacher   | Date
----------|-----------------
Mr Smith  | 2018-12-18 18:15
Mr Jones  | 2018-12-18 18:30
Ms Doe    | 2018-12-18 18:45
Ms Rogers | 2018-12-18 19:00

And

Teacher   | Room
----------|-----
Mr Smith  | A12
Mr Jones  | B10
Ms Doe    | C21
Ms Rogers | A08

But 3NF does not deal with prime attributes dependencies. This is the issue: 3NF compliance is not enough to ensure a sound table schema design under some circumstances.

With BCNF, you don't care if the attribute is a prime attribute or not in 2NF and 3NF rules. For every non trivial dependency (subsets are obviously determined by their supersets), the determinant is a complete super key. In other words, nothing is determined by something else than a complete super key (excluding trivial FDs). (See other answers for formal definition).

As soon as Room depends on Teacher, Room must be a subset of Teacher (that's not the case) or Teacher must be a super key (that's not the case in my diary, but thats the case when you split the table).

To summarize: BNCF is more strict, but in my opinion easier to grasp, than 3NF:

  • in most of cases, BCNF is identical to 3NF;
  • in other cases, BCNF is what you think/hope 3NF is.

How to create relationships in MySQL

If the tables are innodb you can create it like this:

CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY ( account_id ), 
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 
) ENGINE=INNODB;

You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.

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

A Primary key is a special kind of index in that:

there can be only one;
it cannot be nullable
it must be unique.

Candidate keys are selected from the set of super keys, the only thing we take care while selecting the candidate key is: It should not have any redundant attribute.

Example of an Employee table: Employee ( Employee ID, FullName, SSN, DeptID )

  1. Candidate Key: are individual columns in a table that qualifies for the uniqueness of all the rows. Here in Employee table EmployeeID & SSN are Candidate keys.

  2. Primary Key: are the columns you choose to maintain uniqueness in a table. Here in Employee table, you can choose either EmployeeID or SSN columns, EmployeeID is a preferable choice, as SSN is a secure value.

  3. Alternate Key: Candidate column other the Primary column, like if EmployeeID is PK then SSN would be the Alternate key.

  4. Super Key: If you add any other column/attribute to a Primary Key then it becomes a super key, like EmployeeID + FullName, is a Super Key.

  5. Composite Key: If a table does not have a single column that qualifies for a Candidate key, then you have to select 2 or more columns to make a row unique. Like if there is no EmployeeID or SSN columns, then you can make FullName + DateOfBirth as Composite primary Key. But still, there can be a narrow chance of duplicate row.

Why use multiple columns as primary keys (composite primary key)

The W3Schools example isn't saying when you should use compound primary keys, and is only giving example syntax using the same example table as for other keys.

Their choice of example is perhaps misleading you by combining a meaningless key (P_Id) and a natural key (LastName). This odd choice of primary key says that the following rows are valid according to the schema and are necessary to uniquely identify a student. Intuitively this doesn't make sense.

1234     Jobs
1234     Gates

Further Reading: The great primary-key debate or just Google meaningless primary keys or even peruse this SO question

FWIW - My 2 cents is to avoid multi-column primary keys and use a single generated id field (surrogate key) as the primary key and add additional (unique) constraints where necessary.

Difference between a theta join, equijoin and natural join

Natural is a subset of Equi which is a subset of Theta.

If I use the = sign on a theta join is it exactly the same as just using a natural join???

Not necessarily, but it would be an Equi. Natural means you are matching on all similarly named columns, Equi just means you are using '=' exclusively (and not 'less than', like, etc)

This is pure academia though, you could work with relational databases for years and never hear anyone use these terms.

Does the join order matter in SQL?

If you try joining C on a field from B before joining B, i.e.:

SELECT A.x, 
       A.y, 
       A.z 
FROM A 
   INNER JOIN C
       on B.x = C.x
   INNER JOIN B
       on A.x = B.x

your query will fail, so in this case the order matters.

What are the options for storing hierarchical data in a relational database?

This design was not mentioned yet:

Multiple lineage columns

Though it has limitations, if you can bear them, it's very simple and very efficient. Features:

  • Columns: one for each lineage level, refers to all the parents up to the root, levels below the current items' level are set to 0 (or NULL)
  • There is a fixed limit to how deep the hierarchy can be
  • Cheap ancestors, descendants, level
  • Cheap insert, delete, move of the leaves
  • Expensive insert, delete, move of the internal nodes

Here follows an example - taxonomic tree of birds so the hierarchy is Class/Order/Family/Genus/Species - species is the lowest level, 1 row = 1 taxon (which corresponds to species in the case of the leaf nodes):

CREATE TABLE `taxons` (
  `TaxonId` smallint(6) NOT NULL default '0',
  `ClassId` smallint(6) default NULL,
  `OrderId` smallint(6) default NULL,
  `FamilyId` smallint(6) default NULL,
  `GenusId` smallint(6) default NULL,
  `Name` varchar(150) NOT NULL default ''
);

and the example of the data:

+---------+---------+---------+----------+---------+-------------------------------+
| TaxonId | ClassId | OrderId | FamilyId | GenusId | Name                          |
+---------+---------+---------+----------+---------+-------------------------------+
|     254 |       0 |       0 |        0 |       0 | Aves                          |
|     255 |     254 |       0 |        0 |       0 | Gaviiformes                   |
|     256 |     254 |     255 |        0 |       0 | Gaviidae                      |
|     257 |     254 |     255 |      256 |       0 | Gavia                         |
|     258 |     254 |     255 |      256 |     257 | Gavia stellata                |
|     259 |     254 |     255 |      256 |     257 | Gavia arctica                 |
|     260 |     254 |     255 |      256 |     257 | Gavia immer                   |
|     261 |     254 |     255 |      256 |     257 | Gavia adamsii                 |
|     262 |     254 |       0 |        0 |       0 | Podicipediformes              |
|     263 |     254 |     262 |        0 |       0 | Podicipedidae                 |
|     264 |     254 |     262 |      263 |       0 | Tachybaptus                   |

This is great because this way you accomplish all the needed operations in a very easy way, as long as the internal categories don't change their level in the tree.

What is the difference between a Relational and Non-Relational Database?

The difference between relational and non-relational is exactly that. The relational database architecture provides with constraints objects such as primary keys, foreign keys, etc that allows one to tie two or more tables in a relation. This is good so that we normalize our tables which is to say split information about what the database represents into many different tables, once can keep the integrity of the data.

For example, say you have a series of table that houses information about an employee. You could not delete a record from a table without deleting all the records that pertain to such record from the other tables. In this way you implement data integrity. The non-relational database doesn't provide this constraints constructs that will allow you to implement data integrity.

Unless you don't implement this constraint in the front end application that is utilized to populate the databases' tables, you are implementing a mess that can be compared with the wild west.

Difference between one-to-many and many-to-one relationship

Yes, it a vice versa. It depends on which side of the relationship the entity is present on.

For example, if one department can employ for several employees then, department to employee is a one to many relationship (1 department employs many employees), while employee to department relationship is many to one (many employees work in one department).

More info on the relationship types:

Database Relationships - IBM DB2 documentation

NoSql vs Relational database

The biggest advantage of NoSQL over RDBMS is Scalability.
NoSQL databases can easily scale-out to many nodes, but for RDBMS it is very hard.
Scalability not only gives you more storage space but also much higher performance since many hosts work at the same time.

Collection was modified; enumeration operation may not execute

A more efficient way, in my opinion, is to have another list that you declare that you put anything that is "to be removed" into. Then after you finish your main loop (without the .ToList()), you do another loop over the "to be removed" list, removing each entry as it happens. So in your class you add:

private List<Guid> toBeRemoved = new List<Guid>();

Then you change it to:

public void NotifySubscribers(DataRecord sr)
{
    toBeRemoved.Clear();

    ...your unchanged code skipped...

   foreach ( Guid clientId in toBeRemoved )
   {
        try
        {
            subscribers.Remove(clientId);
        }
        catch(Exception e)
        {
            System.Diagnostics.Debug.WriteLine("Unsubscribe Error " + 
                e.Message);
        }
   }
}

...your unchanged code skipped...

public void UnsubscribeEvent(Guid clientId)
{
    toBeRemoved.Add( clientId );
}

This will not only solve your problem, it will prevent you from having to keep creating a list from your dictionary, which is expensive if there are a lot of subscribers in there. Assuming the list of subscribers to be removed on any given iteration is lower than the total number in the list, this should be faster. But of course feel free to profile it to be sure that's the case if there's any doubt in your specific usage situation.

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

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

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

Django Server Error: port is already in use

Sorry for comment in an old post but It may help people

Just type this on your terminal

killall -9 python3

It will kill all python3 running on your machine and it will free your all port. Greatly help me when to work in Django project.

Exception: Can't bind to 'ngFor' since it isn't a known native property

Use this

<div *ngFor="let talk of talks> 
   {{talk.title}} 
   {{talk.speaker}}
   <p>{{talk.description}} 
</div>

You need to specify variable to iterate over an array of an object

Change connection string & reload app.config at run time

//You can apply the logic in "Program.cs"

//Logic for getting new connection string
//****
//

MyDBName="mydb";

//
//****

//Assign new connection string to a variable
string newCnnStr = a="Data Source=.\SQLExpress;Initial Catalog=" + MyDBName + ";Persist Security Info=True;User ID=sa;Password=mypwd";

//And Finally replace the value of setting
Properties.Settings.Default["Nameof_ConnectionString_inSettingFile"] = newCnnStr;

//This method replaces the value at run time and also don't needs app.config for the same setting. It will have the va;ue till the application runs.

//It worked for me.

What is a predicate in c#?

In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.

I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.

Using css transform property in jQuery

$(".oSlider-rotate").slider({
     min: 10,
     max: 74,
     step: .01,
     value: 24,
     slide: function(e,ui){
                 $('.user-text').css('transform', 'scale(' + ui.value + ')')

            }                
  });

This will solve the issue

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

If you want to use that on localhost, then use WAMP.

Then click on tray icon>PHP Services> and there enable the followings:

  • SOAP
  • php_openssl
  • openssl
  • curl

p.s. some free web-hosting may not have those options

Convert objective-c typedef to its string equivalent

My solution:

edit: I've added even a better solution at the end, using Modern Obj-C

1.
Put names as keys in an array.
Make sure the indexes are the appropriate enums, and in the right order (otherwise exception).
note: names is a property synthesized as *_names*;

code was not checked for compilation, but I used the same technique in my app.

typedef enum {
  JSON,
  XML,
  Atom,
  RSS
} FormatType;

+ (NSArray *)names
{
    static NSMutableArray * _names = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _names = [NSMutableArray arrayWithCapacity:4];
        [_names insertObject:@"JSON" atIndex:JSON];
        [_names insertObject:@"XML" atIndex:XML];
        [_names insertObject:@"Atom" atIndex:Atom];
        [_names insertObject:@"RSS" atIndex:RSS];
    });

    return _names;
}

+ (NSString *)nameForType:(FormatType)type
{
    return [[self names] objectAtIndex:type];
}


//

2.
Using Modern Obj-C you we can use a dictionary to tie descriptions to keys in the enum.
Order DOES NOT matter.

typedef NS_ENUM(NSUInteger, UserType) {
    UserTypeParent = 0,
    UserTypeStudent = 1,
    UserTypeTutor = 2,
    UserTypeUnknown = NSUIntegerMax
};  

@property (nonatomic) UserType type;

+ (NSDictionary *)typeDisplayNames
{
    return @{@(UserTypeParent) : @"Parent",
             @(UserTypeStudent) : @"Student",
             @(UserTypeTutor) : @"Tutor",
             @(UserTypeUnknown) : @"Unknown"};
}

- (NSString *)typeDisplayName
{
    return [[self class] typeDisplayNames][@(self.type)];
}


Usage (in a class instance method):

NSLog(@"%@", [self typeDisplayName]);


How to validate a file upload field using Javascript/jquery

In Firefox at least, the DOM inspector is telling me that the File input elements have a property called files. You should be able to check its length.

document.getElementById('myFileInput').files.length

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

How to sort Counter by value? - python

Yes:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})

Using the sorted keyword key and a lambda function:

>>> sorted(x.items(), key=lambda i: i[1])
[('b', 3), ('a', 5), ('c', 7)]
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

This works for all dictionaries. However Counter has a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common():

>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common()))  # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]

You can also specify how many items you want to see:

>>> x.most_common(2)  # specify number you want
[('c', 7), ('a', 5)]

git pull aborted with error filename too long

As someone that has ran into this problem constantly with java repositories on Windows, the best solution is to install Cygwin (https://www.cygwin.com/) and use its git installation under all > devel > git.

The reason this is the best solution I have come across is since Cygwin manages the long path names so other provided commands benefit. Ex: find, cp and rm. Trust me, the real problem begins when you have to delete path names that are too long in Windows.

Receiver not registered exception error?

The root of your problem is located here:

 unregisterReceiver(batteryNotifyReceiver);

If the receiver was already unregistered (probably in the code that you didn't include in this post) or was not registered, then call to unregisterReceiver throws IllegalArgumentException. In your case you need to just put special try/catch for this exception and ignore it (assuming you can't or don't want to control number of times you call unregisterReceiver on the same recevier).

Copying Code from Inspect Element in Google Chrome

You can copy by inspect element and target the div you want to copy. Just press ctrl+c and then your div will be copy and paste in your code it will run easily.

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

How to return a PNG image from Jersey REST service method to the browser

in regard of answer from @Perception, its true to be very memory-consuming when working with byte arrays, but you could also simply write back into the outputstream

@Path("/picture")
public class ProfilePicture {
  @GET
  @Path("/thumbnail")
  @Produces("image/png")
  public StreamingOutput getThumbNail() {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException, WebApplicationException {
        //... read your stream and write into os
      }
    };
  }
}

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

how to convert numeric to nvarchar in sql command

declare @MyNumber int
set @MyNumber = 123
select 'My number is ' + CAST(@MyNumber as nvarchar(20))

How can you flush a write using a file descriptor?

You have two choices:

  1. Use fileno() to obtain the file descriptor associated with the stdio stream pointer

  2. Don't use <stdio.h> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write() call won't even return until the lower-level IO has completed (in theory).

For device-level IO I'd say it's pretty unusual to use stdio. I'd strongly recommend using the lower-level open(), read() and write() functions instead (based on your later reply):

int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);

How to fix request failed on channel 0

shell request failed on channel 0

mean you don't have shell or remote commands access, fix your user permission on server to have shell access or if you just want tunneling use -N and -T options

Multiple Buttons' OnClickListener() android

You could set the property:

android:onClick="buttonClicked"

in the xml file for each of those buttons, and use this in the java code:

public void buttonClicked(View view) {

    if (view.getId() == R.id.button1) {
        // button1 action
    } else if (view.getId() == R.id.button2) {
        //button2 action
    } else if (view.getId() == R.id.button3) {
        //button3 action
    }

}

Batch script loop

(EDITED) I made it so it stops after 100 times

@echo off
goto actual
set /a loopcount=0
:actual
set /a loopcount=%loopcount% + 1
echo %random% %random% %random% %random%
timeout 1 /nobreak>nul
if %loopcount%== 100 goto stop
goto actual
:stop
exit

This will generate 4 random numbers ever 1 second 100 times. Take out the "timeout 1 /nobreak>nul" to make it go super fast.

How do I format a date with Dart?

If someone wants to convert a date in string format to some other string format first use DateTime.parse("2019-09-30") then pass it to DateFormat("date pattern").format() like

dateFormate = DateFormat("dd-MM-yyyy").format(DateTime.parse("2019-09-30"));

Reference: Dart - How to change format of simple date string which is in yyyy-MM-dd to dd-MM-yyyy

Search in lists of lists by given index

I was searching for a deep find for dictionaries and didn't find one. Based on this article I was able to create the following. Thanks and Enjoy!!

def deapFind( theList, key, value ):
    result = False
    for x in theList:
        if( value == x[key] ):
            return True
    return result

theList = [{ "n": "aaa", "d": "bbb" }, { "n": "ccc", "d": "ddd" }]
print 'Result: ' + str (deapFind( theList, 'n', 'aaa'))

I'm using == instead of the in operator since in returns true for partial matches. IOW: searching aa on the n key returns true. I don't think that would be desired.

HTH

How to calculate cumulative normal distribution?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the cumulative distribution function (cdf - probability that a random sample X will be less than or equal to x) for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=0, sigma=1).cdf(1.96)
# 0.9750021048517796

Which can be simplified for the standard normal distribution (mu = 0 and sigma = 1):

NormalDist().cdf(1.96)
# 0.9750021048517796

NormalDist().cdf(-1.96)
# 0.024997895148220428

How to use radio on change event?

<input type="radio" name="radio"  value="upi">upi
<input type="radio" name="radio"  value="bankAcc">Bank

<script type="text/javascript">
$(document).ready(function() {
 $('input[type=radio][name=radio]').change(function() {
   if (this.value == 'upi') {
    //write your logic here

    }
  else if (this.value == 'bankAcc') {
    //write your logic here
 }
 });
 </script>

Setting up enviromental variables in Windows 10 to use java and javac

To find the env vars dialog in Windows 10:

Right Click Start
>>  Click Control Panel  (Or you may have System in the list)
>>  Click System
>>  Click Advanced system settings
>>  Go to the Advanced Tab
>>  Click the "Environment Variables..." button at the bottom of that dialog page.

Set a border around a StackPanel.

May be it will helpful:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>

What is the purpose of a self executing function in javascript?

Is there a parameter and the "Bunch of code" returns a function?

var a = function(x) { return function() { document.write(x); } }(something);

Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.

browser sessionStorage. share between tabs?

You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.

This code would need to exist on ALL tabs. It should execute before your other scripts.

// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
  if(!event) { event = window.event; } // ie suq
  if(!event.newValue) return;          // do nothing if no value to work with
  if (event.key == 'getSessionStorage') {
    // another tab asked for the sessionStorage -> send it
    localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
    // the other tab should now have it, so we're done with it.
    localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
  } else if (event.key == 'sessionStorage' && !sessionStorage.length) {
    // another tab sent data <- get it
    var data = JSON.parse(event.newValue);
    for (var key in data) {
      sessionStorage.setItem(key, data[key]);
    }
  }
};

// listen for changes to localStorage
if(window.addEventListener) {
  window.addEventListener("storage", sessionStorage_transfer, false);
} else {
  window.attachEvent("onstorage", sessionStorage_transfer);
};


// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
  localStorage.setItem('getSessionStorage', 'foobar');
  localStorage.removeItem('getSessionStorage', 'foobar');
};

I tested this in chrome, ff, safari, ie 11, ie 10, ie9

This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)

Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/

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

Run ScrollTop with offset of element by ID

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;   
if (!isNaN(top)) {
$("#app_scroler").click(function () {   
$('html, body').animate({
            scrollTop: top
        }, 100);
    });
}

if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;

How can I convert a comma-separated string to an array?

As @oportocala mentions, an empty string will not result in the expected empty array.

So to counter, do:

str
.split(',')
.map(entry => entry.trim())
.filter(entry => entry)

For an array of expected integers, do:

str
.split(',')
.map(entry => parseInt(entry))
.filter(entry => typeof entry ==='number')

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

I'm not exactly sure where my problem was, but I believe it was because I was using the same global packages from both npm and Yarn.

I uninstalled all the npm global packages, then when using yarn commands once again, the problem was gone.

To see global packages installed...

for npm:

npm ls -g --depth=0

for Yarn:

yarn global list

I then uninstalled each package I saw in the npm listing, using:

npm uninstall -g <package-name>

How to 'insert if not exists' in MySQL?

REPLACE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;

If the record exists, it will be overwritten; if it does not yet exist, it will be created.

In Java, remove empty elements from a list of Strings

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", "", "How"));
           Stream<String> stream = list .stream();
           Predicate<String> empty = empt->(empt.equals(""));
            Predicate<String> emptyRev = empty.negate();
           list=  stream.filter(emptyRev).collect(Collectors.toList());

OR

list =  list .stream().filter(empty->(!empty.equals(""))).collect(Collectors.toList());

How to search for an element in a golang slice

You can save the struct into a map by matching the struct Key and Value components to their fictive key and value parts on the map:

mapConfig := map[string]string{}
for _, v := range myconfig {
   mapConfig[v.Key] = v.Value
}

Then using the golang comma ok idiom you can test for the key presence:

if v, ok := mapConfig["key1"]; ok {
    fmt.Printf("%s exists", v)
}   

How do I set up access control in SVN?

Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.

Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:

  1. Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:

    [Users]
    username = password
    john = johns_password
    steve = steves_password
    
  2. In C:\svn_repos\my_repo\conf\svnserve.conf set:

    [general]
    password-db = passwd
    auth-access=read
    auth-access=write
    

This will force users to log in to read or write to this repository.

Follow these steps for each repository, only including the appropriate users in the passwd file for each repository.

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

Grep for beginning and end of line?

The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.

grep '^[-d]rwx.*[0-9]$' "$@"

See: Regular Expressions and grep for POSIX-standard details.

How to parse an RSS feed using JavaScript?

Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.

Detecting touch screen devices with Javascript

As already mentioned, a device may support both mouse and touch input. Very often, the question is not "what is supported" but "what is currently used".

For this case, you can simply register mouse events (including the hover listener) and touch events alike.

element.addEventListener('touchstart',onTouchStartCallback,false);

element.addEventListener('onmousedown',onMouseDownCallback,false);

...

JavaScript should automatically call the correct listener based on user input. So, in case of a touch event, onTouchStartCallback will be fired, emulating your hover code.

Note that a touch may fire both kinds of listeners, touch and mouse. However, the touch listener goes first and can prevent subsequent mouse listeners from firing by calling event.preventDefault().

function onTouchStartCallback(ev) {
    // Call preventDefault() to prevent any further handling
    ev.preventDefault();
    your code...
}

Further reading here.

How can I add a .npmrc file?

This issue is because of you having some local or private packages. For accessing those packages you have to create .npmrc file for this issue. Just refer the following link for your solution. https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment

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

It selects the next paragraph and indents the beginning of the paragraph from the left just as you might in Microsoft Word.

JPA eager fetch does not join

Two things occur to me.

First, are you sure you mean ManyToOne for address? That means multiple people will have the same address. If it's edited for one of them, it'll be edited for all of them. Is that your intent? 99% of the time addresses are "private" (in the sense that they belong to only one person).

Secondly, do you have any other eager relationships on the Person entity? If I recall correctly, Hibernate can only handle one eager relationship on an entity but that is possibly outdated information.

I say that because your understanding of how this should work is essentially correct from where I'm sitting.

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

MySQL - Make an existing Field Unique

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

is the right answer

the insert part

INSERT IGNORE INTO mytable ....

Deserialize JSON string to c# object

This may be useful:

var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);

Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use

myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);

Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).

Paste MS Excel data to SQL Server

I'd think some datbases can import data from CSV (comma separated values) files, wich you can export from exel. Or at least it's quite easy to use a csv parser (find one for your language, don't try to create one yourself - it's harder than it looks) to import it to the database.

I'm not familiar with MS SQL but it wouldn't suprise me if it does support it directly.

In any case I think the requrement must be that the structure in the Exel sheet and the database table is similar.

How to scroll page in flutter

Very easy if you are already using a statelessWidget checkOut my code

class _MyThirdPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Understanding Material-Cards'),
      ),
      body: SingleChildScrollView(
          child: Column(
        children: <Widget>[
          _buildStack(),
          _buildCard(),
          SingleCard(),
          _inkwellCard()
        ],
      )),
    );
  }
}

Can I check if Bootstrap Modal Shown / Hidden?

All Bootstrap versions:

var isShown = $('.modal').hasClass('in') || $('.modal').hasClass('show')

To just close it independent of state and version:

$('.modal button.close').click()

more info

Bootstrap 3 and before

var isShown = $('.modal').hasClass('in')

Bootstrap 4

var isShown = $('.modal').hasClass('show')

Way to get all alphabetic chars in an array in PHP?

<?php 

$array = Array();
for( $i = 65; $i < 91; $i++){
        $array[] = chr($i);
}

foreach( $array as $k => $v){
        echo "$k $v \n";
}

?>

$ php loop.php 
0 A 
1 B 
2 C 
3 D 
4 E 
5 F 
6 G 
7 H
...

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

How much memory can a 32 bit process access on a 64 bit operating system?

Nobody seems to touch upon the fact that if you have many different 32-bit applications, the wow64 subsystem can map them anywhere in memory above 4G, so on a 64-bit windows with sufficient memory, you can run many more 32-bit applications than on a native 32-bit system.

How can I convert radians to degrees with Python?

You can simply convert your radian result to degree by using

math.degrees and rounding appropriately to the required decimal places

for example

>>> round(math.degrees(math.asin(0.5)),2)
30.0
>>> 

sql searching multiple words in a string

Oracle SQL:

There is the "IN" Operator in Oracle SQL which can be used for that:

select 
    namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi'); 

JUnit Testing private variables?

If you create your test classes in a seperate folder which you then add to your build path,

Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.

But dont forget to remove the folder from the build path for your release build.

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

How to get the difference (only additions) between two files in linux

git diff path/file.css | grep -E "^\+" | grep -v '+++ b/' | cut -c 2-
  • grep -E "^\+" is from previous accepted answer, it is incomplete because leaves non-source stuff
  • grep -v '+++ b' removes non-source line with file name of later version
  • cut -c 2- removes column of + signs, also may use sed 's/^\+//'

comm or sdiff were not an option because of git.

Can I override and overload static methods in Java?

It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.

The best answer i found of this question is:

http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/

LINQ to SQL - Left Outer Join with multiple join conditions

Can be written using composite join key. Also if there is need to select properties from both left and right sides the LINQ can be written as

var result = context.Periods
    .Where(p => p.companyid == 100)
    .GroupJoin(
        context.Facts,
        p => new {p.id, otherid = 17},
        f => new {id = f.periodid, f.otherid},
        (p, f) => new {p, f})
    .SelectMany(
        pf => pf.f.DefaultIfEmpty(),
        (pf, f) => new MyJoinEntity
        {
            Id = pf.p.id,
            Value = f.value,
            // and so on...
        });

Android List View Drag and Drop sort

Am adding this answer for the purpose of those who google about this..

There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this

You can find it here also the sample code is available here.

What this code basically does is that it creates a dynamic listview by the extension of listview that supports cell dragging and swapping. So that you can use the DynamicListView instead of your basic ListView and that's it you have implemented a ListView with Drag and Drop.

When to use Interface and Model in TypeScript / Angular

Use Class instead of Interface that is what I discovered after all my research.

Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

from Angular Style Guide

Basically a Class can do all, what an Interface will do. So may never need to use an Interface.

Undefined symbols for architecture arm64

This solution is the only thing that worked for me: go to CordovaLib settings and add arm64 to Valid Architectures.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

I had similar problems because of .gitignore for the /storage folder on first machine, then cloned repository on second machine and laravel was revision to write down sessions cache

So, manually creating folder /storage/sessions might be an solution..

Iterating Over Dictionary Key Values Corresponding to List in Python

You can very easily iterate over dictionaries, too:

for team, scores in NL_East.iteritems():
    runs_scored = float(scores[0])
    runs_allowed = float(scores[1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print '%s: %.1f%%' % (team, win_percentage)

How to make a simple modal pop up form using jquery and html?

I have placed here complete bins for above query. you can check demo link too.

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

HTML

<div id="panel">
  <input type="button" class="button" value="1" id="btn1">
  <input type="button" class="button" value="2" id="btn2">
  <input type="button" class="button" value="3" id="btn3">
  <br>
  <input type="text" id="valueFromMyModal">
  <!-- Dialog Box-->
  <div class="dialog" id="myform">
    <form>
      <label id="valueFromMyButton">
      </label>
      <input type="text" id="name">
      <div align="center">
        <input type="button" value="Ok" id="btnOK">
      </div>
    </form>
  </div>
</div>

JQuery

$(function() {
    $(".button").click(function() {
        $("#myform #valueFromMyButton").text($(this).val().trim());
        $("#myform input[type=text]").val('');
        $("#myform").show(500);
    });
    $("#btnOK").click(function() {
        $("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
        $("#myform").hide(400);
    });
});

CSS

.button{
  border:1px solid #333;
  background:#6479fd;
}
.button:hover{
  background:#a4a9fd;
}
.dialog{
  border:5px solid #666;
  padding:10px;
  background:#3A3A3A;
  position:absolute;
  display:none;
}
.dialog label{
  display:inline-block;
  color:#cecece;
}
input[type=text]{
  border:1px solid #333;
  display:inline-block;
  margin:5px;
}
#btnOK{
  border:1px solid #000;
  background:#ff9999;
  margin:5px;
}

#btnOK:hover{
  border:1px solid #000;
  background:#ffacac;
}

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

Use dynamic variable names in `dplyr`

With rlang 0.4.0 we have curly-curly operators ({{}}) which makes this very easy.

library(dplyr)
library(rlang)

iris1 <- tbl_df(iris)

multipetal <- function(df, n) {
   varname <- paste("petal", n , sep=".")
   mutate(df, {{varname}} := Petal.Width * n)
}

multipetal(iris1, 4)

# A tibble: 150 x 6
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.4
#          <dbl>       <dbl>        <dbl>       <dbl> <fct>     <dbl>
# 1          5.1         3.5          1.4         0.2 setosa      0.8
# 2          4.9         3            1.4         0.2 setosa      0.8
# 3          4.7         3.2          1.3         0.2 setosa      0.8
# 4          4.6         3.1          1.5         0.2 setosa      0.8
# 5          5           3.6          1.4         0.2 setosa      0.8
# 6          5.4         3.9          1.7         0.4 setosa      1.6
# 7          4.6         3.4          1.4         0.3 setosa      1.2
# 8          5           3.4          1.5         0.2 setosa      0.8
# 9          4.4         2.9          1.4         0.2 setosa      0.8
#10          4.9         3.1          1.5         0.1 setosa      0.4
# … with 140 more rows

We can also pass quoted/unquoted variable names to be assigned as column names.

multipetal <- function(df, name, n) {
   mutate(df, {{name}} := Petal.Width * n)
}

multipetal(iris1, temp, 3)

# A tibble: 150 x 6
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species  temp
#          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <dbl>
# 1          5.1         3.5          1.4         0.2 setosa  0.6  
# 2          4.9         3            1.4         0.2 setosa  0.6  
# 3          4.7         3.2          1.3         0.2 setosa  0.6  
# 4          4.6         3.1          1.5         0.2 setosa  0.6  
# 5          5           3.6          1.4         0.2 setosa  0.6  
# 6          5.4         3.9          1.7         0.4 setosa  1.2  
# 7          4.6         3.4          1.4         0.3 setosa  0.900
# 8          5           3.4          1.5         0.2 setosa  0.6  
# 9          4.4         2.9          1.4         0.2 setosa  0.6  
#10          4.9         3.1          1.5         0.1 setosa  0.3  
# … with 140 more rows

It works the same with

multipetal(iris1, "temp", 3)

Where can I find "make" program for Mac OS X Lion?

Have you installed Xcode and the developer tools? I think make, along with gcc and friends, is installed with that and not before. Xcode 4.1 for Lion is free.

How do I list all remote branches in Git 1.7+?

remote show shows all the branches on the remote, including those that are not tracked locally and even those that have not yet been fetched.

git remote show <remote-name>

It also tries to show the status of the branches relative to your local repository:

> git remote show origin
* remote origin
  Fetch URL: C:/git/.\remote_repo.git
  Push  URL: C:/git/.\remote_repo.git
  HEAD branch: master
  Remote branches:
    branch_that_is_not_even_fetched new (next fetch will store in remotes/origin)
    branch_that_is_not_tracked      tracked
    branch_that_is_tracked          tracked
    master                          tracked
  Local branches configured for 'git pull':
    branch_that_is_tracked merges with remote branch_that_is_tracked
    master                 merges with remote master
  Local refs configured for 'git push':
    branch_that_is_tracked pushes to branch_that_is_tracked (fast-forwardable)
    master                 pushes to master                 (up to date)

Python: OSError: [Errno 2] No such file or directory: ''

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

How to create Haar Cascade (.xml file) to use in OpenCV?

How to create CascadeClassifier :

  1. Open this link : https://github.com/opencv/opencv/tree/master/data/haarcascades
  2. Right click on where you find "haarcascade_frontalface_default.xml"
  3. Click on "Save link as"
  4. Save it into the same folder in which your file is.
  5. Include this line in your file face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Check if string begins with something?

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

Set today's date as default date in jQuery UI datepicker

Its very simple you just add this script,

$("#mydate").datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date());

Here, setDate set today date & dateFormat define which format you want set or show.

Hope its simple script work..

T-SQL Subquery Max(Date) and Joins

Something like this

SELECT * 
FROM MyParts 
LEFT JOIN 
(
SELECT MAX(PriceDate), PartID FROM MyPrice group by PartID
) myprice
 ON MyParts.Partid = MyPrice.Partid 

If you know your partid or can restrict it put it inside the join.

   SELECT myprice.partid, myprice.partdate, myprice2.Price, * 
    FROM MyParts 
    LEFT JOIN 
    (
    SELECT MAX(PriceDate), PartID FROM MyPrice group by PartID
    ) myprice
     ON MyParts.Partid = MyPrice.Partid 
    Inner Join MyPrice myprice2
    on myprice2.pricedate = myprice.pricedate
    and myprice2.partid = myprice.partid

PHP - Copy image to my server direct from URL

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);

you must have allow_url_fopen set to on

Close application and launch home screen on Android

You are wrong. There is one way to kill an application. In a class with super class Application, we use some field, for example, killApp. When we start the splash screen (first activity) in onResume(), we set a parameter for false for field killApp. In every activity which we have when onResume() is called in the end, we call something like that:

if(AppClass.killApp())
    finish();

Every activity which is getting to the screen have to call onResume(). When it is called, we have to check if our field killApp is true. If it is true, current activities call finish(). To invoke the full action, we use the next construction. For example, in the action for a button:

AppClass.setkillApplication(true);
   finish();
   return;

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

How to increment a variable on a for loop in jinja template?

Here's my solution:

Put all the counters in a dictionary:

{% set counter = {
    'counter1': 0,
    'counter2': 0,
    'etc': 0,
    } %}

Define a macro to increment them easily:

{% macro increment(dct, key, inc=1)%}
    {% if dct.update({key: dct[key] + inc}) %} {% endif %}
{% endmacro %}

Now, whenever you want to increment the 'counter1' counter, just do:

{{ increment(counter, 'counter1') }}

Is there a numpy builtin to reject outliers from a list

Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less.

Building on eumiro's answer:

def reject_outliers(data, m = 2.):
    d = np.abs(data - np.median(data))
    mdev = np.median(d)
    s = d/mdev if mdev else 0.
    return data[s<m]

Here I have replace the mean with the more robust median and the standard deviation with the median absolute distance to the median. I then scaled the distances by their (again) median value so that m is on a reasonable relative scale.

Note that for the data[s<m] syntax to work, data must be a numpy array.

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

How do I log a Python error with debug information?

Quoting

What if your application does logging some other way – not using the logging module?

Now, traceback could be used here.

import traceback

def log_traceback(ex, ex_traceback=None):
    if ex_traceback is None:
        ex_traceback = ex.__traceback__
    tb_lines = [ line.rstrip('\n') for line in
                 traceback.format_exception(ex.__class__, ex, ex_traceback)]
    exception_logger.log(tb_lines)
  • Use it in Python 2:

    try:
        # your function call is here
    except Exception as ex:
        _, _, ex_traceback = sys.exc_info()
        log_traceback(ex, ex_traceback)
    
  • Use it in Python 3:

    try:
        x = get_number()
    except Exception as ex:
        log_traceback(ex)
    

Inserting data to table (mysqli insert)

Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.

According to the mysqli_query documentation, the first parameter must be a connection string:

$link = mysqli_connect("localhost","root","","web_table");

mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)") 
or die(mysqli_error($link));

Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.

How to fix 'android.os.NetworkOnMainThreadException'?

This happens in Android 3.0 and above. From Android 3.0 and above, they have restricted using network operations (functions that access the Internet) from running in the main thread/UI thread (what spawns from your on create and on resume methods in the activity).

This is to encourage using separate threads for network operations. See AsyncTask for more details on how to perform network activities the right way.

What is the best way to conditionally apply attributes in AngularJS?

You can prefix attributes with ng-attr to eval an Angular expression. When the result of the expressions undefined this removes the value from the attribute.

<a ng-attr-href="{{value || undefined}}">Hello World</a>

Will produce (when value is false)

<a ng-attr-href="{{value || undefined}}" href>Hello World</a>

So don't use false because that will produce the word "false" as the value.

<a ng-attr-href="{{value || false}}" href="false">Hello World</a>

When using this trick in a directive. The attributes for the directive will be false if they are missing a value.

For example, the above would be false.

function post($scope, $el, $attr) {
      var url = $attr['href'] || false;
      alert(url === false);
}

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.

How to define a preprocessor symbol in Xcode

It's under "GCC 4.2 Preprocessing" (or just put "prepro" in the search box)...

...however, for the life of me I can't get it to work.

I have my standard Debug and Release configurations, and I want to define DEBUG=1 in the debugging configuration. But after adding it as a value:

(in the settings window) > Preprocessor Macros : DEBUG=1

#if DEBUG
    printf("DEBUG is set!");
#endif 

...never prints/gets called. It's driving me crazy...

Good examples using java.util.logging

I would suggest that you use Apache's commons logging utility. It is highly scalable and supports separate log files for different loggers. See here.

Python Dictionary contains List as Value - How to update?

Probably something like this:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

How to make function decorators and chain them together?

And of course you can return lambdas as well from a decorator function:

def makebold(f): 
    return lambda: "<b>" + f() + "</b>"
def makeitalic(f): 
    return lambda: "<i>" + f() + "</i>"

@makebold
@makeitalic
def say():
    return "Hello"

print say()

How to create a release signed apk file using Gradle?

I managed to solve it adding this code, and building with gradle build:

android {
    ...
    signingConfigs {
        release {
            storeFile file("release.keystore")
            storePassword "******"
            keyAlias "******"
            keyPassword "******"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
}

This generates a signed release apk file.

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

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

I used a two step process to change rows with "blank" values to "Null" values as place holders.

UPDATE [TableName] SET [TableName].[ColumnName] = "0"
WHERE ((([TableName].[ColumnName])=""));

UPDATE [TableName] SET [TableName].[ColumnName] = "Null"
WHERE ((([TableName].[ColumnName])="0"));

Android difference between Two Dates

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Usage:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Output:

dateDifference: 2

Kotlin Version:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
    return try {
        DurationUnit.DAYS.convert(
            format.parse(newDate).time - format.parse(oldDate).time,
            DurationUnit.MILLISECONDS
        )
    } catch (e: Exception) {
        e.printStackTrace()
        0
    }
}

Are multiple `.gitignore`s frowned on?

As a tangential note, one case where the ability to have multiple .gitignore files is very useful is if you want an extra directory in your working copy that you never intend to commit. Just put a 1-byte .gitignore (containing just a single asterisk) in that directory and it will never show up in git status etc.

Scala how can I count the number of occurrences in a list

Here is another option:

scala> val list = List(1,2,4,2,4,7,3,2,4)
list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)

scala> list.groupBy(x => x) map { case (k,v) => k-> v.length }
res74: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)

wordpress contactform7 textarea cols and rows change in smaller screens

I was able to get this work. I added the following to my custom CSS:

.wpcf7-form textarea{ 
    width: 100% !important;
    height:50px;
}

Get a file name from a path

A slow but straight forward regex solution:

    std::string file = std::regex_replace(path, std::regex("(.*\\/)|(\\..*)"), "");

Count indexes using "for" in Python

Just use

for i in range(0, 5):
    print i

to iterate through your data set and print each value.

For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange

jQuery Validate Plugin - How to create a simple custom rule?

Step 1 Included the cdn like

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

     <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

Step 2 Code Like

  $(document).ready(function(){
        $("#submit").click(function () {
              $('#myform').validate({ // initialize the plugin
                rules: {
                    id: {
                        required: true,
                        email: true
                    },
                    password: {
                        required: true,
                        minlength: 1
                    }
                },
                messages: {
                    id: {
                        required: "Enter Email Id"

                    },
                    password: {
                        required: "Enter Email Password"

                    }
                },
                submitHandler: function (form) { // for demo
                    alert('valid form submitted'); // for demo
                    return false; // for demo
                }
            });
       }):
  }); 

Adding Python Path on Windows 7

You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)

You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%.

http://localhost/phpMyAdmin/ unable to connect

http://localhost:(port number of phpmyadmin)/phpmyadmin/

For example: http://localhost:8080/phpmyadmin/

It works great!

PHP Date Format to Month Name and Year

You could use:

echo date('F Y', strtotime('20130814'));

which should do the trick.

Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.

Why should I prefer to use member initialization lists?

Just to add some additional info to demonstrate how much difference the member initialization list can mak. In the leetcode 303 Range Sum Query - Immutable, https://leetcode.com/problems/range-sum-query-immutable/, where you need to construct and initialize to zero a vector with certain size. Here is two different implementation and speed comparison.

Without member initialization list, to get AC it cost me about 212 ms.

class NumArray {
public:
vector<int> preSum;
NumArray(vector<int> nums) {
    preSum = vector<int>(nums.size()+1, 0);
    int ps = 0;
    for (int i = 0; i < nums.size(); i++)
    {
        ps += nums[i];
        preSum[i+1] = ps;
    }
}

int sumRange(int i, int j) {
    return preSum[j+1] - preSum[i];
}
};

Now using member initialization list, the time to get AC is about 108 ms. With this simple example, it is quite obvious that, member initialization list is way more efficient. All the measurement is from the running time from LC.

class NumArray {
public:
vector<int> preSum;
NumArray(vector<int> nums) : preSum(nums.size()+1, 0) { 
    int ps = 0;
    for (int i = 0; i < nums.size(); i++)
    {
        ps += nums[i];
        preSum[i+1] = ps;
    }
}

int sumRange(int i, int j) {
    return preSum[j+1] - preSum[i];
}
};

Using union and order by clause in mysql

This is because You're sorting entire result-set, You should sort, every part of union separately, or You can use ORDER BY (Something ie. subquery distance) THEN (something ie row id) clause

How to position a Bootstrap popover?

Simply add an attribute to your popover! See my JSFiddle if you're in a hurry.

We want to add an ID or a class to a particular popover so that we may customize it the way we want via CSS.

Please note that we don't want to customize all popovers! This is terrible idea.

Here is a simple example - display the popover like this:

enter image description here

_x000D_
_x000D_
// We add the id 'my-popover'_x000D_
$("#my-button").popover({_x000D_
    html : true,_x000D_
    placement: 'bottom'_x000D_
}).data('bs.popover').tip().attr('id', 'my-popover');
_x000D_
#my-popover {_x000D_
    left: -169px!important;_x000D_
}_x000D_
#my-popover .arrow {_x000D_
    left: 90%_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button id="my-button" data-toggle="popover">My Button</button>
_x000D_
_x000D_
_x000D_

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

if you are interested in a ready solution then you may look at HumanizerCpp library (https://github.com/trodevel/HumanizerCpp) - it is a port of C# Humanizer library and it does exactly what you want.

It can even convert to ordinals and currently supports 3 languages: English, German and Russian.

Example:

const INumberToWordsConverter * e = Configurator::GetNumberToWordsConverter( "en" );

std::cout << e->Convert( 123 ) << std::endl;
std::cout << e->Convert( 1234 ) << std::endl;
std::cout << e->Convert( 12345 ) << std::endl;
std::cout << e->Convert( 123456 ) << std::endl;

std::cout << std::endl;
std::cout << e->ConvertToOrdinal( 1001 ) << std::endl;
std::cout << e->ConvertToOrdinal( 1021 ) << std::endl;


const INumberToWordsConverter * g = Configurator::GetNumberToWordsConverter( "de" );

std::cout << std::endl;
std::cout << g->Convert( 123456 ) << std::endl;

const INumberToWordsConverter * r = Configurator::GetNumberToWordsConverter( "ru" );

std::cout << r->ConvertToOrdinal( 1112 ) << std::endl;

Output:

one hundred and twenty-three
one thousand two hundred and thirty-four
twelve thousand three hundred and forty-five
one hundred and twenty-three thousand four hundred and fifty-six

thousand and first
thousand and twenty-first

einhundertdreiundzwanzigtausendvierhundertsechsundfünfzig
???? ?????? ??? ???????????

In any case you may take a look at the source code and reuse in your project or try to understand the logic. It is written in pure C++ without external libraries.

Regards, Serge

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

In Mongoose, how do I sort by date? (node.js)

Post.find().sort({date:-1}, function(err, posts){
});

Should work as well

EDIT:

You can also try using this if you get the error sort() only takes 1 Argument :

Post.find({}, {
    '_id': 0,    // select keys to return here
}, {sort: '-date'}, function(err, posts) {
    // use it here
});

Why won't eclipse switch the compiler to Java 8?

It cause eclipse kepler SR1 does not support new Java™ 8 language enhancements like lambda expression.

From information here: http://www.eclipse.org/downloads/java8/
I think you should use kepler SR2 with support plugin, or change to Eclipse Luna.


Updated link 16/09/2016: https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler

eslint: error Parsing error: The keyword 'const' is reserved

you also can add this inline instead of config, just add it to the same file before you add your own disable stuff

/* eslint-env es6 */
/* eslint-disable no-console */

my case was disable a file and eslint-disable were not working for me alone

/* eslint-env es6 */
/* eslint-disable */

OraOLEDB.Oracle provider is not registered on the local machine

If you can't change compile use x64, try uninstall x64 version of odac and install 32bit version. Then, don't forget to add install directory like C:\oracle and also the child directory C:\oracle\bin to the PATH environment variable. This worked out for me in .net 4 application.

Find the IP address of the client in an SSH session

an older thread with a lot of answers, but none are quite what i was looking for, so i'm contributing mine:

sshpid=$$
sshloop=0
while [ "$sshloop" = "0" ]; do
        if [ "$(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT)" ];
then
                read sshClientIP sshClientSport sshClientDport <<< $(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT | cut -d= -f2)
                sshloop=1
        else
                sshpid=$(cat /proc/${sshpid}/status | grep PPid | awk '{print $2}')
                [ "$sshpid" = "0" ] && sshClientIP="localhost" && sshloop=1
        fi
done

this method is compatible with direct ssh, sudoed users, and screen sessions. it will trail up through the process tree until it finds a pid with the SSH_CLIENT variable, then record its IP as $sshClientIP. if it gets too far up the tree, it will record the IP as 'localhost' and leave the loop.

Check if Variable is Empty - Angular 2

user:Array[]=[1,2,3];
if(this.user.length)
{
    console.log("user has contents");
}
else{
    console.log("user is empty");
}

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

How do I reverse an int array in Java?

In case of Java 8 we can also use IntStream to reverse the array of integers as:

int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
                      .toArray(); //Output: [5, 4, 3, 2, 1]

Create line after text with css

This is the most easy way I found to achieve the result: Just use hr tag before the text, and set the margin top for text. Very short and easy to understand! jsfiddle

_x000D_
_x000D_
h2 {_x000D_
  background-color: #ffffff;_x000D_
  margin-top: -22px;_x000D_
  width: 25%;_x000D_
}_x000D_
_x000D_
hr {_x000D_
  border: 1px solid #e9a216;_x000D_
}
_x000D_
<br>_x000D_
_x000D_
<hr>_x000D_
<h2>ABOUT US</h2>
_x000D_
_x000D_
_x000D_

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"
done

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"
done

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"
done

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
done
for i in "$list"; do
    echo $i
done
for i in ${array[@]}; do
    echo $i
done

Change color of Label in C#

I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:

myLabel.ForeColor = System.Drawing.Color.Red;

Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:

myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)

Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".

An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.

A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.

Git copy changes from one branch to another

This is 2 step process

  • git checkout BranchB ( destination branch is BranchB, so we need the head on this branch)
  • git merge BranchA (it will merge BranchB with BranchA. Here you have merged code in branch B)

If you want to push your branch code to remote repo then do

  • git push origin master (it will push your BranchB code to remote repo)

How to get a password from a shell script without echoing

You can also prompt for a password without setting a variable in the current shell by doing something like this:

$(read -s;echo $REPLY)

For instance:

my-command --set password=$(read -sp "Password: ";echo $REPLY)

You can add several of these prompted values with line break, doing this:

my-command --set user=$(read -sp "`echo $'\n '`User: ";echo $REPLY) --set password=$(read -sp "`echo $'\n '`Password: ";echo $REPLY)

Why does "return list.sort()" return None, not the list?

Python has two kinds of sorts: a sort method (or "member function") and a sort function. The sort method operates on the contents of the object named -- think of it as an action that the object is taking to re-order itself. The sort function is an operation over the data represented by an object and returns a new object with the same contents in a sorted order.

Given a list of integers named l the list itself will be reordered if we call l.sort():

>>> l = [1, 5, 2341, 467, 213, 123]
>>> l.sort()
>>> l
[1, 5, 123, 213, 467, 2341]

This method has no return value. But what if we try to assign the result of l.sort()?

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = l.sort()
>>> print(r)
None

r now equals actually nothing. This is one of those weird, somewhat annoying details that a programmer is likely to forget about after a period of absence from Python (which is why I am writing this, so I don't forget again).

The function sorted(), on the other hand, will not do anything to the contents of l, but will return a new, sorted list with the same contents as l:

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = sorted(l)
>>> l
[1, 5, 2341, 467, 213, 123]
>>> r
[1, 5, 123, 213, 467, 2341]

Be aware that the returned value is not a deep copy, so be cautious about side-effecty operations over elements contained within the list as usual:

>>> spam = [8, 2, 4, 7]
>>> eggs = [3, 1, 4, 5]
>>> l = [spam, eggs]
>>> r = sorted(l)
>>> l
[[8, 2, 4, 7], [3, 1, 4, 5]]
>>> r
[[3, 1, 4, 5], [8, 2, 4, 7]]
>>> spam.sort()
>>> eggs.sort()
>>> l
[[2, 4, 7, 8], [1, 3, 4, 5]]
>>> r
[[1, 3, 4, 5], [2, 4, 7, 8]]

Get folder name of the file in Python

I'm using 2 ways to get the same response: one of them use:

   os.path.basename(filename)

due to errors that I found in my script I changed to:

Path = filename[:(len(filename)-len(os.path.basename(filename)))]

it's a workaround due to python's '\\'

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Swing + SwingX + Miglayout is my combination of choice. Miglayout is so much simpler than Swings perceived 200 different layout managers and much more powerful. Also, it provides you with the ability to "debug" your layouts, which is especially handy when creating complex layouts.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Try the following

  1. download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

  2. Unzip the file and Run intelhaxm-android.exe.

  3. Run silent_install.bat.

In my computer Win10 x64 - VS2015 it worked

Sort a List of objects by multiple fields

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
            }
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

1 = false and 0 = true?

There's no good reason for 1 to be true and 0 to be false; that's just the way things have always been notated. So from a logical perspective, the function in your API isn't "wrong", per se.

That said, it's normally not advisable to work against the idioms of whatever language or framework you're using without a damn good reason to do so, so whoever wrote this function was probably pretty bone-headed, assuming it's not simply a bug.

How to write a full path in a batch file having a folder name with space?

start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"

You may try this, I did it finally, it works!

How to delete all files and folders in a directory?

We can also show love for LINQ:

using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);

directory.EnumerateFiles()
    .ToList().ForEach(f => f.Delete());

directory.EnumerateDirectories()
    .ToList().ForEach(d => d.Delete(true));

Note that my solution here is not performant, because I am using Get*().ToList().ForEach(...) which generates the same IEnumerable twice. I use an extension method to avoid this issue:

using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);

directory.EnumerateFiles()
    .ForEachInEnumerable(f => f.Delete());

directory.EnumerateDirectories()
    .ForEachInEnumerable(d => d.Delete(true));

This is the extension method:

/// <summary>
/// Extensions for <see cref="System.Collections.Generic.IEnumerable"/>.
/// </summary>
public static class IEnumerableOfTExtensions
{
    /// <summary>
    /// Performs the <see cref="System.Action"/>
    /// on each item in the enumerable object.
    /// </summary>
    /// <typeparam name="TEnumerable">The type of the enumerable.</typeparam>
    /// <param name="enumerable">The enumerable.</param>
    /// <param name="action">The action.</param>
    /// <remarks>
    /// “I am philosophically opposed to providing such a method, for two reasons.
    /// …The first reason is that doing so violates the functional programming principles
    /// that all the other sequence operators are based upon. Clearly the sole purpose of a call
    /// to this method is to cause side effects.”
    /// —Eric Lippert, “foreach” vs “ForEach” [http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx]
    /// </remarks>
    public static void ForEachInEnumerable<TEnumerable>(this IEnumerable<TEnumerable> enumerable, Action<TEnumerable> action)
    {
        foreach (var item in enumerable)
        {
            action(item);
        }
    }
}

Can I do Model->where('id', ARRAY) multiple where conditions?

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Quite a painful problem for me too. Just spent about an hour trying to build and re-build - no joy. In the end I had to do this:

  1. Upgrade the base SDK to the latest ( in my case iOS 5 )
  2. Restart xCode
  3. Clean & Build
  4. It worked!

I guess it's a bunch of jargon about arm6 , arm7 as it looked like my project was valid for both, at least the settings seemed to say so ) , my guess is this is a cynical way to bamboozle us with the technicalities, which we don't understand, so we just take the easy option and target the latest iOS ( good for Apple with more people being up-to-date ) ....

Java OCR implementation

We have tested a few OCR engines with Java like Tesseract,Asprise, Abbyy etc. In our analysis, Abbyy gave the best results.

CSS disable text selection

Just wanted to summarize everything:

.unselectable {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

<div class="unselectable" unselectable="yes" onselectstart="return false;"/>

Difference between the System.Array.CopyTo() and System.Array.Clone()

Array.Clone() would perform technically deep copy, when pass the array of int or string to a method as a reference.

For example

int[] numbers = new int[] { -11, 12, -42, 0, 1, 90, 68, 6, -9 }; 

SortByAscending(numbers); // Sort the array in ascending order by clone the numbers array to local new array.
SortByDescending(numbers); // Same as Ascending order Clone

Even if the methods sort the array of numbers but it wont affect the actual reference passed to the sorting methods.i.e the number array will be in same unsorted initial format in line no 1.

Note: The Clone should be done in the sorting methods.

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Plenty of responses already, but you can use this:

Sub runQry(qDefName)
    Dim db As DAO.Database, qd As QueryDef, par As Parameter

    Set db = CurrentDb
    Set qd = db.QueryDefs(qDefName)

    On Error Resume Next
    For Each par In qd.Parameters
        Err.Clear
        par.Value = Eval(par.Name)          'try evaluating param
        If Err.Number <> 0 Then             'failed ?
            par.Value = InputBox(par.Name)  'ask for value
        End If
    Next par
    On Error GoTo 0

    qd.Execute dbFailOnError
End Sub

Sub runQry_test()
    runQry "test"  'qryDef name
End Sub

jQuery "on create" event for dynamically-created elements

This could be done with DOM4 MutationObservers but will only work in Firefox 14+/Chrome 18+ (for now).

However there is an "epic hack" (author's words not mine!) that works in all browsers that support CSS3 animations which are: IE10, Firefox 5+, Chrome 3+, Opera 12, Android 2.0+, Safari 4+. See the demo from the blog. The hack is to use a CSS3 animation event with a given name that is observed and acted upon in JavaScript.

How to check for an active Internet connection on iOS or macOS?

There is also another method to check Internet connection using the iPhone SDK.

Try to implement the following code for the network connection.

#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>

/**
     Checking for network availability. It returns
     YES if the network is available.
*/
+ (BOOL) connectedToNetwork
{

    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability =
        SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }

    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);

    return (isReachable && !needsConnection) ? YES : NO;
}

Why I can't access remote Jupyter Notebook server?

Alternatively you can just create a tunnel to the server:

ssh -i <your_key> <user@server-instance> -L 8888:127.0.0.1:8888

Then just open 127.0.0.1:8888 in your browser.

You also omit the -i <your_key> if you don't have an identity_file.

How to delete duplicate rows in SQL Server?

Another way of removing dublicated rows without loosing information in one step is like following:

delete from dublicated_table t1 (nolock)
join (
    select t2.dublicated_field
    , min(len(t2.field_kept)) as min_field_kept
    from dublicated_table t2 (nolock)
    group by t2.dublicated_field having COUNT(*)>1
) t3 
on t1.dublicated_field=t3.dublicated_field 
    and len(t1.field_kept)=t3.min_field_kept

Select rows from a data frame based on values in a vector

Similar to above, using filter from dplyr:

filter(df, fct %in% vc)

Java, "Variable name" cannot be resolved to a variable

If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)

The two variables you are having trouble with are passed as parameters to the constructor.

The error message is because 'hours' is out of scope in the setter.

How to change MenuItem icon in ActionBar programmatically

Lalith's answer is correct.

You may also try this approach:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            invalidateOptionsMenu();
        }
    });

 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem settingsItem = menu.findItem(R.id.action_settings);
    // set your desired icon here based on a flag if you like
    settingsItem.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher)); 

    return super.onPrepareOptionsMenu(menu);
 }

How to append one DataTable to another DataTable

Merge takes a DataTable, Load requires an IDataReader - so depending on what your data layer gives you access to, use the required method. My understanding is that Load will internally call Merge, but not 100% sure about that.

If you have two DataTables, use Merge.

Ternary operation in CoffeeScript

CoffeeScript has no ternary operator. That's what the docs say.

You can still use a syntax like

a = true then 5 else 10

It's way much clearer.

Select elements by attribute in CSS

Is it possible to select elements in CSS by their HTML5 data attributes? This can easily be answered just by trying it, and the answer is, of course, yes. But this invariably leads us to the next question, 'Should we select elements in CSS by their HTML5 data attributes?' There are conflicting opinions on this.

In the 'no' camp is (or at least was, back in 2014) CSS legend Harry Roberts. In the article, Naming UI components in OOCSS, he wrote:

It’s important to note that although we can style HTML via its data-* attributes, we probably shouldn’t. data-* attributes are meant for holding data in markup, not for selecting on. This, from the HTML Living Standard (emphasis mine):

"Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements."

The W3C spec was frustratingly vague on this point, but based purely on what it did and didn't say, I think Harry's conclusion was perfectly reasonable.

Since then, plenty of articles have suggested that it's perfectly appropriate to use custom data attributes as styling hooks, including MDN's guide, Using data attributes. There's even a CSS methodology called CUBE CSS which has adopted the data attribute hook as the preferred way of adding styles to component 'exceptions' (known as modifiers in BEM).

Thankfully, the WHATWG HTML Living Standard has since added a few more words and even some examples (emphasis mine):

Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements.

In this example, custom data attributes are used to store the result of a feature detection for PaymentRequest, which could be used in CSS to style a checkout page differently.

Authors should carefully design such extensions so that when the attributes are ignored and any associated CSS dropped, the page is still usable.


TL;DR: Yes, it's okay to use data-* attributes in CSS selectors, provided the page is still usable without them.

Combine two (or more) PDF's

Here is a single function that will merge X amount of PDFs using PDFSharp

using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

public static void MergePDFs(string targetPath, params string[] pdfs) {
    using(PdfDocument targetDoc = new PdfDocument()){
        foreach (string pdf in pdfs) {
            using (PdfDocument pdfDoc = PdfReader.Open(pdf, PdfDocumentOpenMode.Import)) {
                for (int i = 0; i < pdfDoc.PageCount; i++) {
                    targetDoc.AddPage(pdfDoc.Pages[i]);
                }
            }
        }
        targetDoc.Save(targetPath);
    }
}

keytool error Keystore was tampered with, or password was incorrect

For me I solved it by changing passwords from Arabic letter to English letter, but first I went to the folder and deleted the generated key then it works.

Are there best practices for (Java) package organization?

Are there best practices with regards to the organisation of packages in Java and what goes in them?

Not really no. There are lots of ideas, and lots opinions, but real "best practice" is to use your common sense!

(Please read No best Practices for a perspective on "best practices" and the people who promote them.)

However, there is one principal that probably has broad acceptance. Your package structure should reflect your application's (informal) module structure, and you should aim to minimize (or ideally entirely avoid) any cyclic dependencies between modules.

(Cyclic dependencies between classes in a package / module are just fine, but inter-package cycles tend to make it hard understand your application's architecture, and can be a barrier to code reuse. In particular, if you use Maven you will find that cyclic inter-package / inter-module dependencies mean that the whole interconnected mess has to be one Maven artifact.)

I should also add that there is one widely accepted best practice for package names. And that is that your package names should start with your organization's domain name in reverse order. If you follow this rule, you reduce the likelihood of problems caused by your (full) class names clashing with other peoples'.

How to show "if" condition on a sequence diagram?

In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx

Prompt Dialog in Windows Forms

Based on the work of Bas Brekelmans above, I have also created two derivations -> "input" dialogs that allow you to receive from the user both a text value and a boolean (TextBox and CheckBox):

public static class PromptForTextAndBoolean
{
    public static string ShowDialog(string caption, string text, string boolStr)
    {
        Form prompt = new Form();
        prompt.Width = 280;
        prompt.Height = 160;
        prompt.Text = caption;
        Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
        TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
        CheckBox ckbx = new CheckBox() { Left = 16, Top = 60, Width = 240, Text = boolStr };
        Button confirmation = new Button() { Text = "Okay!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textLabel);
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(ckbx);
        prompt.Controls.Add(confirmation);
        prompt.AcceptButton = confirmation;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        prompt.ShowDialog();
        return string.Format("{0};{1}", textBox.Text, ckbx.Checked.ToString());
    }
}

...and text along with a selection of one of multiple options (TextBox and ComboBox):

public static class PromptForTextAndSelection
{
    public static string ShowDialog(string caption, string text, string selStr)
    {
        Form prompt = new Form();
        prompt.Width = 280;
        prompt.Height = 160;
        prompt.Text = caption;
        Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
        TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
        Label selLabel = new Label() { Left = 16, Top = 66, Width = 88, Text = selStr };
        ComboBox cmbx = new ComboBox() { Left = 112, Top = 64, Width = 144 };
        cmbx.Items.Add("Dark Grey");
        cmbx.Items.Add("Orange");
        cmbx.Items.Add("None");
        Button confirmation = new Button() { Text = "In Ordnung!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textLabel);
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(selLabel);
        prompt.Controls.Add(cmbx);
        prompt.Controls.Add(confirmation);
        prompt.AcceptButton = confirmation;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        prompt.ShowDialog();
        return string.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString());
    }
}

Both require the same usings:

using System;
using System.Windows.Forms;

Call them like so:

Call them like so:

PromptForTextAndBoolean.ShowDialog("Jazz", "What text should accompany the checkbox?", "Allow Scat Singing"); 

PromptForTextAndSelection.ShowDialog("Rock", "What should the name of the band be?", "Beret color to wear");

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

Try docker inspect, for example:

$ docker inspect --type=image treeder/hello.rb:nada
Error: No such image: treeder/hello.rb:nada
[]

But now with an image that exists, you'll get a bunch of information, eg:

$ docker inspect --type=image treeder/hello.rb:latest
[
{
    "Id": "85c5116a2835521de2c52f10ab5dda0ff002a4a12aa476c141aace9bc67f43ad",
    "Parent": "ecf63f5eb5e89e5974875da3998d72abc0d3d0e4ae2354887fffba037b356ad5",
    "Comment": "",
    "Created": "2015-09-23T22:06:38.86684783Z",
    ...
}
]

And it's in a nice json format.

Append to string variable

Like this:

var str = 'blah blah blah';
str += ' blah';

str += ' ' + 'and some more blah';

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

TrNgGrid is working great so far. Here are the reasons I prefer it to ng-grid and moved to this component

  • It makes table elements so it can be bootswatched and use all the power of bootstrap .css (ng-grid uses jQuery UI themes).

  • Simple, well documented grid options.

  • Server size paging works

Difference between const reference and normal parameter

The difference is more prominent when you are passing a big struct/class.

struct MyData {
    int a,b,c,d,e,f,g,h;
    long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);

when you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. if you are using const reference, you pass it by reference and the original data is not copied.

in both cases, the original data cannot be modified from inside the function.

EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.

Adding Http Headers to HttpClient

When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

This method is deprecated now from now starting with Android Q.

Try This will really help.

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {// if build version is less than Q try the old traditional method
                    if (!wifiManager.isWifiEnabled()) {
                        wifiManager.setWifiEnabled(true);
                        btnOnOff.setText("Wifi ONN");
                    } else {
                        wifiManager.setWifiEnabled(false);
                        btnOnOff.setText("Wifi OFF");
                    }
                } else {// if it is Android Q and above go for the newer way    NOTE: You can also use this code for less than android Q also
                    Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
                    startActivityForResult(panelIntent, 1);
                }

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

A module is a single file (or files) that are imported under one import and used. e.g.

import my_module

A package is a collection of modules in directories that give a package hierarchy.

from my_package.timing.danger.internets import function_of_love

Documentation for modules

Introduction to packages

Linux: is there a read or recv from socket with timeout?

You can use the setsockopt function to set a timeout on receive operations:

SO_RCVTIMEO

Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.

// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Reportedly on Windows this should be done before calling bind. I have verified by experiment that it can be done either before or after bind on Linux and OS X.

Remove blue border from css custom-styled button in Chrome

Simply write outline:none;. No need to use pseudo element focus

Using jQuery, Restricting File Size Before Uploading

I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:

LimitRequestBody 2097152

This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).

Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:

Requested content-length of 4000107 is larger than the configured limit of 2097152

And it will also display this message back in the web browser:

<h1>Request Entity Too Large</h1>

So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.

By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...

Redirect 413 413.html

...and provide a more graceful error result back.

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

I had to add:

secureTextEntry={true}

Along with

password={true}

As of 0.55

enable/disable zoom in Android WebView

I've looked at the source code for WebView and I concluded that there is no elegant way to accomplish what you are asking.

What I ended up doing was subclassing WebView and overriding OnTouchEvent. In OnTouchEvent for ACTION_DOWN, I check how many pointers there are using MotionEvent.getPointerCount(). If there is more than one pointer, I call setSupportZoom(true), otherwise I call setSupportZoom(false). I then call the super.OnTouchEvent().

This will effectively disable zooming when scrolling (thus disabling the zoom controls) and enable zooming when the user is about to pinch zoom. Not a nice way of doing it, but it has worked well for me so far.

Note that getPointerCount() was introduced in 2.1 so you'll have to do some extra stuff if you support 1.6.

How to enter a multi-line command

  1. Use a semi-colon ; to separate command
  2. Replace double backslash \\ on any backslashes \.
  3. Use "' for passing safe address to switch command like "'PATH'".

This ps1 command install locale pfx certificate.

powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"

How do I read a string entered by the user in C?

On BSD systems and Android you can also use fgetln:

#include <stdio.h>

char *
fgetln(FILE *stream, size_t *len);

Like so:

size_t line_len;
const char *line = fgetln(stdin, &line_len);

The line is not null terminated and contains \n (or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream. You are allowed to modify the returned line buffer.

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

Why is "npm install" really slow?

One of the simple solution to speed up your npm install is to spin up a high powered machine on AWS and use that to compile your project and ship the code back to you.

I was experimenting with it and I found that there was a very high decrease in the time to run npm install. I found a tool to execute the above command easily https://stormyapp.com

'uint32_t' identifier not found error

On Windows I usually use windows types. To use it you have to include <Windows.h>.

In this case uint32_t is UINT32 or just UINT.

All types definitions are here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx

Listing files in a specific "folder" of a AWS S3 bucket

you can check the type. s3 has a special application/x-directory

bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Thanks to Vinod for the well presented answer.

I got the same error as Mick Byrne when I followed the steps above. Turning it back to All Unassigned sorted it but I had to tweak a few other things as well:

  • Add the user my site was running under to the users on the Security Tab in SMTP Virtual Server.
  • Changed the value in the mailSettings > network > host attribute in my web.config to the specific server IP (for example 192.168.100.120) as opposed to localhost (which was pointing at 127.0.0.1 in the hosts file).

Hope this saves someone a few mins of messing about.

How do I get row id of a row in sql server

SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id is an IDENTITY column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON). If employee_id is an IDENTITY column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:

SELECT 
   ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID, 
   EMPLOYEE_ID,
   EMPLOYEE_NAME 
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;

You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).

ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743 
-- wow, who named this?
  ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES() - e.g. you may have to revisit your code and define a proper, explicit column list.

How to refresh token with Google API client?

here is the snippet to set token, before that make sure the access type should be set to offline

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['access_token'] = $client->getAccessToken();
}

To refresh token

$google_token= json_decode($_SESSION['access_token']);
$client->refreshToken($google_token->refresh_token);

this will refresh your token, you have to update it in session for that you can do

 $_SESSION['access_token']= $client->getAccessToken()

Linq : select value in a datatable column

var name = from DataRow dr in tblClassCode.Rows where (long)dr["ID"] == Convert.ToInt32(i) select (int)dr["Name"]).FirstOrDefault().ToString() 

How to run mvim (MacVim) from Terminal?

This works for me:

? brew link --overwrite macvim
Linking /usr/local/Cellar/macvim/8.0-146_1... 12 symlinks created

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

How do you set, clear, and toggle a single bit?

Try one of these functions in the C language to change n bit:

char bitfield;

// Start at 0th position

void chang_n_bit(int n, int value)
{
    bitfield = (bitfield | (1 << n)) & (~( (1 << n) ^ (value << n) ));
}

Or

void chang_n_bit(int n, int value)
{
    bitfield = (bitfield | (1 << n)) & ((value << n) | ((~0) ^ (1 << n)));
}

Or

void chang_n_bit(int n, int value)
{
    if(value)
        bitfield |= 1 << n;
    else
        bitfield &= ~0 ^ (1 << n);
}

char get_n_bit(int n)
{
    return (bitfield & (1 << n)) ? 1 : 0;
}

Meaning of delta or epsilon argument of assertEquals for double values

The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.

Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.

If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation

Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));

Or

Assert.assertEquals(0, Double.compareTo(expected, result));

Which can take these nuances into account.

I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.

React.js: Identifying different inputs with one onChange handler

The key of your state should be the same as the name of your input field. Then you can do this in the handleEvent method;

this.setState({
        [event.target.name]: event.target.value
});

Line continue character in C#

If you declared different variables then use following simple method:

Int salary=2000;

String abc="I Love Pakistan";

Double pi=3.14;

Console.Writeline=salary+"/n"+abc+"/n"+pi;
Console.readkey();

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

How to trigger a click on a link using jQuery

If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works:

$(document).on("click", "a", function(){
    $(this).text("It works!");
});

$(document).ready(function(){
    $("a").trigger("click");
});

Are you trying to cause the user to navigate to a certain point on the webpage by clicking the anchor, or are you trying to trigger events bound to it? Maybe you haven't actually bound the click event successfully to the event?

Also this:

$('#titleee').find('a').trigger('click');

is the equivalent of this:

$('#titleee a').trigger('click');

No need to call find. :)

Read a XML (from a string) and get some fields - Problems reading XML

I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).

        string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
        XElement xmlroot = XElement.Parse(textXml);
        string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;

Making a DateTime field in a database automatic?

Yes, here's an example:

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

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

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

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

Then create a trigger for updating the updatedDate column:

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

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

In your entity class, when you declare mapping from user to roles, try specifying the fetchType to EAGER. Some thing like this:

@OneToMany(fetch=FetchType.EAGER)
public Collection<Role> getRoleSet(){
 ...
}

UPDATE: Recent comments this answer's received make me revisit this. It's been a while since I answered, when I only started working with Hibernate. What Rafael and Mukus say are reasonable. If you have a large collection, you shouldn't use eager fetching. It jointly selects all data mapped to your entry and loads to memory. An alternative to this is to still use lazy fetching and open a Hibernate session each time you need to work on the related collection, i.e, each time you need to invoke getRoleSet method. This way, Hibernate will execute the select query to database each time this method is invoked and doesn't keep the collection data in memory. You can refer to my post here for details: http://khuevu.github.io/2013/01/20/understand-hibernate.html

That's said, it can depend on your actual use case. If your collection data is small and you frequently need to query the data, you will better off using eager fetching. I think, in your specific case, a collection of role is probably quite small and suitable to use eager fetching.

Different CURRENT_TIMESTAMP and SYSDATE in oracle

Note: SYSDATE - returns only date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:

SELECT SYSDATE FROM DUAL; will return output similar to the following: 12/15/2017 12:42:39 PM

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example