Programs & Examples On #Reactive programming

Reactive Programming is a programming paradigm oriented around data flows and the propagation of change.

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

What is (functional) reactive programming?

The paper Simply efficient functional reactivity by Conal Elliott (direct PDF, 233 KB) is a fairly good introduction. The corresponding library also works.

The paper is now superceded by another paper, Push-pull functional reactive programming (direct PDF, 286 KB).

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

Java character array initializer

char array[] = new String("Hi there").toCharArray();
for(char c : array)
    System.out.print(c + " ");

String in function parameter

Inside the function parameter list, char arr[] is absolutely equivalent to char *arr, so the pair of definitions and the pair of declarations are equivalent.

void function(char arr[]) { ... }
void function(char *arr)  { ... }

void function(char arr[]);
void function(char *arr);

The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.

Treat string literals as if they were static const char literal[] = "string literal"; and do not attempt to modify them.

LINQ Using Max() to select a single row

I don't see why you are grouping here.

Try this:

var maxValue = table.Max(x => x.Status)
var result = table.First(x => x.Status == maxValue);

An alternate approach that would iterate table only once would be this:

var result = table.OrderByDescending(x => x.Status).First();

This is helpful if table is an IEnumerable<T> that is not present in memory or that is calculated on the fly.

Highcharts - redraw() vs. new Highcharts.chart

@RobinL as mentioned in previous comments, you can use chart.series[n].setData(). First you need to make sure you’ve assigned a chart instance to the chart variable, that way it adopts all the properties and methods you need to access and manipulate the chart.

I’ve also used the second parameter of setData() and had it false, to prevent automatic rendering of the chart. This was because I have multiple data series, so I’ll rather update each of them, with render=false, and then running chart.redraw(). This multiplied performance (I’m having 10,000-100,000 data points and refreshing the data set every 50 milliseconds).

What is the difference between DSA and RSA?

With reference to man ssh-keygen, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.

In conclusion, a 2048 bit RSA key is currently the best choice.

MORE PRECAUTIONS TO TAKE

Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.

To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.

Deleting elements from std::set while iterating

I think using the STL method 'remove_if' from could help to prevent some weird issue when trying to attempt to delete the object that is wrapped by the iterator.

This solution may be less efficient.

Let's say we have some kind of container, like vector or a list called m_bullets:

Bullet::Ptr is a shared_pr<Bullet>

'it' is the iterator that 'remove_if' returns, the third argument is a lambda function that is executed on every element of the container. Because the container contains Bullet::Ptr, the lambda function needs to get that type(or a reference to that type) passed as an argument.

 auto it = std::remove_if(m_bullets.begin(), m_bullets.end(), [](Bullet::Ptr bullet){
    // dead bullets need to be removed from the container
    if (!bullet->isAlive()) {
        // lambda function returns true, thus this element is 'removed'
        return true;
    }
    else{
        // in the other case, that the bullet is still alive and we can do
        // stuff with it, like rendering and what not.
        bullet->render(); // while checking, we do render work at the same time
        // then we could either do another check or directly say that we don't
        // want the bullet to be removed.
        return false;
    }
});
// The interesting part is, that all of those objects were not really
// completely removed, as the space of the deleted objects does still 
// exist and needs to be removed if you do not want to manually fill it later 
// on with any other objects.
// erase dead bullets
m_bullets.erase(it, m_bullets.end());

'remove_if' removes the container where the lambda function returned true and shifts that content to the beginning of the container. The 'it' points to an undefined object that can be considered garbage. Objects from 'it' to m_bullets.end() can be erased, as they occupy memory, but contain garbage, thus the 'erase' method is called on that range.

MongoDB "root" user

There is a Superuser Roles: root, which is a Built-In Roles, may meet your need.

Remove an item from an IEnumerable<T> collection

There is now an extension method to convert the IEnumerable<> to a Dictionary<,> which then has a Remove method.

public readonly IEnumerable<User> Users = new User[]; // or however this would be initialized

// To take an item out of the collection
Users.ToDictionary(u => u.Id).Remove(1123);

// To take add an item to the collection
Users.ToList().Add(newuser);

Android : change button text and background color

Since API level 21 you can use :

android:backgroundTint="@android:color/white"

you only have to add this in your xml

Could not create the Java virtual machine

The problem got resolved when I edited the file /etc/bashrc with same contents as in /etc/profiles and in /etc/profiles.d/limits.sh and did a re-login.

How to customize <input type="file">?

It's much better if you just use a <label>, hide the <input>, and customize the label.

HTML:

<input type="file" id="input">
<label for="input" id="label">Choose File</label>

CSS:

input#input{
    display: none;
}
label#label{
    /* Customize your label here */
}

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

You can also receive this if you are attempting to execute React.Component with an erroneous () in your class definition.

export default class MyComponent extends React.Component() {}
                                                        ^^ REMOVE

Which I sometimes manage to do when I'm converting from a stateless functional component to a class.

WSDL/SOAP Test With soapui

A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.

The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.

jQuery remove special characters from string and more

Remove numbers, underscore, white-spaces and special characters from the string sentence.

str.replace(/[0-9`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'');

Demo

How to load my app from Eclipse to my Android phone instead of AVD

What I did, by reading all of above answers and it worked as well: 7 deadly steps

  1. Connect your android phone with the pc on which you are running eclipse/your map project.
  2. Let it install all the necessary drivers.. When done, open your smart phone, go to: Settings > Applications > Development > USB debugging and enable it on by clicking on the check button at the right side.
  3. Also, enable Settings > Unknowresoures
  4. Come back to eclipse on your pc. Right click on the project/application, Run As > Run configurations... >Choose Device>Target Select your device Run.
  5. Click on the Target tab from top. By default it is on the first tab Android
  6. Choose the second radio button which says Launch on all compatible deivces/AVDs. Then click Apply at the bottom and afterwards, click Run.
  7. Here you go, it will automatically install your application's .apk file into your smart phone and make it run over it., just like on emulator.

If you get it running, please help others too.

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

What is the best way to remove a table row with jQuery?

All you have to do is to remove the table row (<tr>) tag from your table. For example here is the code to remove the last row from the table:

$('#myTable tr:last').remove();

*Code above was taken from this jQuery Howto post.

Jquery click event not working after append method

The .on() method is used to delegate events to elements, dynamically added or already present in the DOM:

_x000D_
_x000D_
// STATIC-PARENT              on  EVENT    DYNAMIC-CHILD_x000D_
$('#registered_participants').on('click', '.new_participant_form', function() {_x000D_
_x000D_
  var $td = $(this).closest('tr').find('td');_x000D_
  var part_name = $td.eq(1).text();_x000D_
  console.log( part_name );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$('#add_new_participant').click(function() {_x000D_
_x000D_
  var first_name = $.trim( $('#f_name_participant').val() );_x000D_
  var last_name  = $.trim( $('#l_name_participant').val() );_x000D_
  var role       = $('#new_participant_role').val();_x000D_
  var email      = $('#email_participant').val();_x000D_
  _x000D_
  if(!first_name && !last_name) return;_x000D_
_x000D_
  $('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>' + first_name + ' ' + last_name + '</td><td>' + role + '</td><td>0% done</td></tr>');_x000D_
_x000D_
});
_x000D_
<table id="registered_participants" class="tablesorter">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Form</th>_x000D_
      <th>Name</th>_x000D_
      <th>Role</th>_x000D_
      <th>Progress </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td><a href="#" class="new_participant_form">Participant Registration</a></td>_x000D_
      <td>Smith Johnson</td>_x000D_
      <td>Parent</td>_x000D_
      <td>60% done</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<input type="text" id="f_name_participant" placeholder="Name">_x000D_
<input type="text" id="l_name_participant" placeholder="Surname">_x000D_
<select id="new_participant_role">_x000D_
  <option>Parent</option>_x000D_
  <option>Child</option>_x000D_
</select>_x000D_
<button id="add_new_participant">Add New Entry</button>_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Read more: http://api.jquery.com/on/

How do I script a "yes" response for installing programs?

If you want to just accept defaults you can use:

\n | ./shell_being_run

Create view with primary key?

This worked for me..

select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view

Could not find module FindOpenCV.cmake ( Error in configuration process)

if you are on windows, you can add opencv path to OpenCV_DIR yourself. (OpenCV_DIR is in the red region)

the path is like "D:/opencv244/build".

you can find file "OpenCVConfig.cmake" under the path.

How can I get argv[] as int?

/*

    Input from command line using atoi, and strtol 
*/

#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol 

//strtol - converts a string to a long int 
//atoi - converts string to an int 

int main(int argc, char *argv[]){

    char *p;//used in strtol 
    int i;//used in for loop

    long int longN = strtol( argv[1],&p, 10);
    printf("longN = %ld\n",longN);

    //cast (int) to strtol
    int N = (int) strtol( argv[1],&p, 10);
    printf("N = %d\n",N);

    int atoiN;
    for(i = 0; i < argc; i++)
    {
        //set atoiN equal to the users number in the command line 
        //The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
        atoiN = atoi(argv[i]);
    }

    printf("atoiN = %d\n",atoiN);
    //-----------------------------------------------------//
    //Get string input from command line 
    char * charN;

    for(i = 0; i < argc; i++)
    {
        charN = argv[i];
    }

    printf("charN = %s\n", charN); 

}

Hope this helps. Good luck!

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

removing bold styling from part of a header

<h1 style="font-weight: normal;"></h1>

try this?

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

Ring Buffer in Java

Consider CircularFifoBuffer from Apache Common.Collections. Unlike Queue you don't have to maintain the limited size of underlying collection and wrap it once you hit the limit.

Buffer buf = new CircularFifoBuffer(4);
buf.add("A");
buf.add("B");
buf.add("C");
buf.add("D"); //ABCD
buf.add("E"); //BCDE

CircularFifoBuffer will do this for you because of the following properties:

  • CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.
  • The removal order of a CircularFifoBuffer is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.
  • The add(Object), BoundedFifoBuffer.remove() and BoundedFifoBuffer.get() operations all perform in constant time. All other operations perform in linear time or worse.

However you should consider it's limitations as well - for example, you can't add missing timeseries to this collection because it doens't allow nulls.

NOTE: When using current Common Collections (4.*), you have to use Queue. Like this:

Queue buf = new CircularFifoQueue(4);

How to implement Rate It feature in Android App

My one using DialogFragment:

public class RateItDialogFragment extends DialogFragment {
    private static final int LAUNCHES_UNTIL_PROMPT = 10;
    private static final int DAYS_UNTIL_PROMPT = 3;
    private static final int MILLIS_UNTIL_PROMPT = DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000;
    private static final String PREF_NAME = "APP_RATER";
    private static final String LAST_PROMPT = "LAST_PROMPT";
    private static final String LAUNCHES = "LAUNCHES";
    private static final String DISABLED = "DISABLED";

    public static void show(Context context, FragmentManager fragmentManager) {
        boolean shouldShow = false;
        SharedPreferences sharedPreferences = getSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        long currentTime = System.currentTimeMillis();
        long lastPromptTime = sharedPreferences.getLong(LAST_PROMPT, 0);
        if (lastPromptTime == 0) {
            lastPromptTime = currentTime;
            editor.putLong(LAST_PROMPT, lastPromptTime);
        }

        if (!sharedPreferences.getBoolean(DISABLED, false)) {
            int launches = sharedPreferences.getInt(LAUNCHES, 0) + 1;
            if (launches > LAUNCHES_UNTIL_PROMPT) {
                if (currentTime > lastPromptTime + MILLIS_UNTIL_PROMPT) {
                    shouldShow = true;
                }
            }
            editor.putInt(LAUNCHES, launches);
        }

        if (shouldShow) {
            editor.putInt(LAUNCHES, 0).putLong(LAST_PROMPT, System.currentTimeMillis()).commit();
            new RateItDialogFragment().show(fragmentManager, null);
        } else {
            editor.commit();
        }
    }

    private static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, 0);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                .setTitle(R.string.rate_title)
                .setMessage(R.string.rate_message)
                .setPositiveButton(R.string.rate_positive, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getActivity().getPackageName())));
                        getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
                        dismiss();
                    }
                })
                .setNeutralButton(R.string.rate_remind_later, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss();
                    }
                })
                .setNegativeButton(R.string.rate_never, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
                        dismiss();
                    }
                }).create();
    }
}

Then use it in onCreate() of your main FragmentActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    RateItDialogFragment.show(this, getFragmentManager());

}

H2 in-memory database. Table not found

I had the same problem and changed my configuration in application-test.properties to this:

#Test Properties
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop

And my dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.198</version>
        <scope>test</scope>
    </dependency>

And the annotations used on test class:

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
public class CommentServicesIntegrationTests {
...
}

Skip a submodule during a Maven build

It's possible to decide which reactor projects to build by specifying the -pl command line argument:

$ mvn --help
[...]
 -pl,--projects <arg>                   Build specified reactor projects
                                        instead of all projects
[...]

It accepts a comma separated list of parameters in one of the following forms:

  • relative path of the folder containing the POM
  • [groupId]:artifactId

Thus, given the following structure:

project-root [com.mycorp:parent]
  |
  + --- server [com.mycorp:server]
  |       |
  |       + --- orm [com.mycorp.server:orm]
  |
  + --- client [com.mycorp:client]

You can specify the following command line:

mvn -pl .,server,:client,com.mycorp.server:orm clean install

to build everything. Remove elements in the list to build only the modules you please.


EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el flag that excludes projects from the reactor, similarly to what -pl does:

Matplotlib (pyplot) savefig outputs blank image

plt.show() should come after plt.savefig()

Explanation: plt.show() clears the whole thing, so anything afterwards will happen on a new empty figure

Change CSS class properties with jQuery

You can add a class to the parent of the red div, e.g. green-style

$('.red').parent().addClass('green-style');

then add style to the css

.green-style .red {
     background:green; 
}

so everytime you add red element under green-style, the background will be green

Sending an HTTP POST request on iOS

Sending an HTTP POST request on iOS (Objective c):

-(NSString *)postexample{

// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

//RESPONDE DATA 
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

Read input numbers separated by spaces

int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
    cin >> i;
    sum += i;
    //cout << i << endl;
    if (cin.peek() == '\n') {
        break;
    }
    
}

cout << "result: " << sum << endl;
return 0;
}

I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints

Why and how to fix? IIS Express "The specified port is in use"

In my case there was no application using specified port and elevated running of Visual Studio didn't help either.

What worked for me is to reinstall IIS Express and than restart computer.

client denied by server configuration

For me the following worked which is copied from example in /etc/apache2/apache2.conf:

<Directory /srv/www/default>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Require all granted option is the solution for the first problem example in wiki.apache.org page dedicated for this issue for Apache version 2.4+.

More details about Require option can be found on official apache page for mod_authz module and on this page too. Namely:

Require all granted -> Access is allowed unconditionally.

Simple http post example in Objective-C?

Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )

How to prevent XSS with HTML/PHP?

One of the most important steps is to sanitize any user input before it is processed and/or rendered back to the browser. PHP has some "filter" functions that can be used.

The form that XSS attacks usually have is to insert a link to some off-site javascript that contains malicious intent for the user. Read more about it here.

You'll also want to test your site - I can recommend the Firefox add-on XSS Me.

Passing parameters to addTarget:action:forControlEvents

I subclassed UIButton in CustomButton and I add a property where I store my data. So I call method: (CustomButton*) sender and in the method I only read my data sender.myproperty.

Example CustomButton:

@interface CustomButton : UIButton
@property(nonatomic, retain) NSString *textShare;
@end

Method action:

+ (void) share: (CustomButton*) sender
{
    NSString *text = sender.textShare;
    //your work…
}

Assign action

    CustomButton *btn = [[CustomButton alloc] initWithFrame: CGRectMake(margin, margin, 60, 60)];
    // other setup…

    btnWa.textShare = @"my text";
    [btn addTarget: self action: @selector(shareWhatsapp:)  forControlEvents: UIControlEventTouchUpInside];

How to cast or convert an unsigned int to int in C?

If you have a variable unsigned int x;, you can convert it to an int using (int)x.

Remove duplicates from a list of objects based on property in Java 8

Another solution is to use a Predicate, then you can use this in any filter:

public static <T> Predicate<T> distinctBy(Function<? super T, ?> f) {
  Set<Object> objects = new ConcurrentHashSet<>();
  return t -> objects.add(f.apply(t));
}

Then simply reuse the predicate anywhere:

employees.stream().filter(distinctBy(e -> e.getId));

Note: in the JavaDoc of filter, which says it takes a stateless Predicte. Actually, this works fine even if the stream is parallel.


About other solutions:

1) Using .collect(Collectors.toConcurrentMap(..)).values() is a good solution, but it's annoying if you want to sort and keep the order.

2) stream.removeIf(e->!seen.add(e.getID())); is also another very good solution. But we need to make sure the collection implemented removeIf, for example it will throw exception if we construct the collection use Arrays.asList(..).

AngularJS access parent scope from child controller

When you are using as syntax, like ParentController as parentCtrl, to define a controller then to access parent scope variable in child controller use following :

var id = $scope.parentCtrl.id;

Where parentCtrl is name of parent controller using as syntax and id is a variable defined in same controller.

Javascript to sort contents of select element

From the W3C FAQ:

Although many programming languages have devices like drop-down boxes that have the capability of sorting a list of items before displaying them as part of their functionality, the HTML <select> function has no such capabilities. It lists the <options> in the order received.

You'd have to sort them by hand for a static HTML document, or resort to Javascript or some other programmatic sort for a dynamic document.

'import' and 'export' may only appear at the top level

Maybe you're missing some plugins, try:

npm i --save-dev babel-plugin-transform-vue-jsx

npm i --save-dev babel-plugin-transform-runtime

npm i --save-dev babel-plugin-syntax-dynamic-import
  • If using "Webpack.config.js":

Missing Plugins

  • If using ".babelrc", see answer in this link.

CSS transition fade on hover

This will do the trick

.gallery-item
{
  opacity:1;
}

.gallery-item:hover
{
  opacity:0;
  transition: opacity .2s ease-out;
  -moz-transition: opacity .2s ease-out;
  -webkit-transition: opacity .2s ease-out;
  -o-transition: opacity .2s ease-out;
}

How can you strip non-ASCII characters from a string? (in C#)

no need for regex. just use encoding...

sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

May be You are not registering the Controllers. Try below code:

Step 1. Write your own controller factory class ControllerFactory :DefaultControllerFactory by implementing defaultcontrollerfactory in models folder

  public class ControllerFactory :DefaultControllerFactory
    {
    protected override IController GetControllerInstance(RequestContext         requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                    throw new ArgumentNullException("controllerType");

                if (!typeof(IController).IsAssignableFrom(controllerType))
                    throw new ArgumentException(string.Format(
                        "Type requested is not a controller: {0}",
                        controllerType.Name),
                        "controllerType");

                return MvcUnityContainer.Container.Resolve(controllerType) as IController;
            }
            catch
            {
                return null;
            }

        }
        public static class MvcUnityContainer
        {
            public static UnityContainer Container { get; set; }
        }
    }

Step 2:Regigster it in BootStrap: inBuildUnityContainer method

private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      // register all your components with the container here
      // it is NOT necessary to register your controllers

      // e.g. container.RegisterType<ITestService, TestService>();    
      //RegisterTypes(container);
      container = new UnityContainer();
      container.RegisterType<IProductRepository, ProductRepository>();


      MvcUnityContainer.Container = container;
      return container;
    }

Step 3: In Global Asax.

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            Bootstrapper.Initialise();
            ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));

        }

And you are done

The type or namespace name could not be found

The using statement refers to a namespace, not a project.

Make sure that you have the appropriately named namespace in your referenced project:

namespace PrjTest
{
     public class Foo
     {
          // etc...
     }
}

Read more about namespaces on MSDN:

Printing out a linked list using toString

As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.

LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());

This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:

  1. Add a toString() method to your LinkedListNode class.
  2. Update the toString() method in your LinkedList class to be more concise.
  3. Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.

In LinkedListNode:

public String toString(){
   return "LinkedListNode with data: " + getData();
}

In LinkedList:

public int size(){
    int currentSize = 0;
    LinkedListNode current = head;
    while(current != null){
        currentSize = currentSize + 1;
        current = current.getNext();
    }

    return currentSize;
}

public String toString(){
    return "LinkedList with " + size() + "elements.";
}

public void printList(){
    System.out.println("Contents of " + toString());

    LinkedListNode current = head;
    while(current != null){
        System.out.println(current.toString());
        current = current.getNext();
    }

}

How to link a folder with an existing Heroku app

Heroku links your projects based on the heroku git remote (and a few other options, see the update below). To add your Heroku remote as a remote in your current repository, use the following command:

git remote add heroku [email protected]:project.git

where project is the name of your Heroku project (the same as the project.heroku.com subdomain). Once you've done so, you can use the heroku xxxx commands (assuming you have the Heroku Toolbelt installed), and can push to Heroku as usual via git push heroku master. As a shortcut, if you're using the command line tool, you can type:

heroku git:remote -a project

where, again, project is the name of your Heroku project (thanks, Colonel Panic). You can name the Git remote anything you want by passing -r remote_name.

[Update]

As mentioned by Ben in the comments, the remote doesn't need to be named heroku for the gem commands to work. I checked the source, and it appears it works like this:

  1. If you specify an app name via the --app option (e.g. heroku info --app myapp), it will use that app.
  2. If you specify a Git remote name via the --remote option (e.g. heroku info --remote production), it will use the app associated with that Git remote.
  3. If you specify no option and you have heroku.remote set in your Git config file, it will use the app associated with that remote (for example, to set the default remote to "production" use git config heroku.remote production in your repository, and Heroku will run git config heroku.remote to read the value of this setting)
  4. If you specify no option, the gem finds no configuration in your .git/config file, and the gem only finds one remote in your Git remotes that has "heroku.com" in the URL, it will use that remote.
  5. If none of these work, it raises an error instructing you to pass --app to your command.

Angular JS update input field after change

You just need to correct the format of your html

<form>
    <li>Number 1: <input type="text" ng-model="one"/> </li>
    <li>Number 2: <input type="text" ng-model="two"/> </li>
        <li>Total <input type="text" value="{{total()}}"/>  </li>      
    {{total()}}

</form>

http://jsfiddle.net/YUza7/105/

Is it possible to style a select box?

This seems old but here a very interesting plugin - http://uniformjs.com

How to edit .csproj file

in vs 2019 Version 16.8.2 right click on you project name and click on "Edit Project File" enter image description here

How do I disable and re-enable a button in with javascript?

<script>
function checkusers()
{
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;
}
</script>

Multiple Indexes vs Multi-Column Indexes

If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically.

By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.

Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.

You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Add JSTL library as dependency to your project (javax.servlet.jsp.jstl.core.Config is a part of this package). For example, if you were using Gradle, you could write in a build.gradle:

dependencies {
    compile 'javax.servlet:jstl:1.2'
}

Creating a list of objects in Python

Create a new instance each time, where each new instance has the correct state, rather than continually modifying the state of the same instance.

Alternately, store an explicitly-made copy of the object (using the hint at this page) at each step, rather than the original.

Setting up Gradle for api 26 (Android)

you must add in your MODULE-LEVEL build.gradle file with:

//module-level build.gradle file
repositories {
    maven {
        url 'https://maven.google.com'

    }
}

see: Google's Maven repository

I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

//project-level build.gradle file
allprojects {
 repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
  }
}

UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

How do you select the entire excel sheet with Range using VBA?

Refering to the very first question, I am looking into the same. The result I get, recording a macro, is, starting by selecting cell A76:

Sub find_last_row()
    Range("A76").Select
    Range(Selection, Selection.End(xlDown)).Select
End Sub

installing urllib in Python3.6

The corrected code is

import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand: 
    words = line.decode().split() 
for word in words: 
    counts[word] = counts.get(word, 0) + 1 
print(counts) 

running the code above produces

{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}

Concatenate two slices in Go

append( ) function and spread operator

Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation. So we need to use ...

package main

import (
    "fmt"
)

func main() {
    x := []int{1, 2, 3}
    y := []int{4, 5, 6}
    z := append([]int{}, append(x, y...)...)
    fmt.Println(z)
}

output of the above code is: [1 2 3 4 5 6]

How to Set OnClick attribute with value containing function in ie8?

your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:

if (foo.addEventListener) 
    foo.addEventListener('click',doit,false); //everything else    
else if (foo.attachEvent)
    foo.attachEvent('onclick',doit);  //IE only

edit:

also, your function is a little off. it should be

var doit = function(){
    alert('hello world!');
}

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Sorry for late reply.But this would work properly.

daytext=(textview)findviewById(R.id.day);

Calender c=Calender.getInstance();
SimpleDateFormat sd=new SimpleDateFormat("EEEE");
String dayofweek=sd.format(c.getTime());


daytext.setText(dayofweek);

LINQ equivalent of foreach for IEnumerable<T>

This "functional approach" abstraction leaks big time. Nothing on the language level prevents side effects. As long as you can make it call your lambda/delegate for every element in the container - you will get the "ForEach" behavior.

Here for example one way of merging srcDictionary into destDictionary (if key already exists - overwrites)

this is a hack, and should not be used in any production code.

var b = srcDictionary.Select(
                             x=>
                                {
                                  destDictionary[x.Key] = x.Value;
                                  return true;
                                }
                             ).Count();

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

Upping the directive in the virtualhost for KeepAliveTimeout to 60 solved this for me.

Add a list item through javascript

Try something like this:

var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);

Fiddle: http://jsfiddle.net/FlameTrap/3jDZd/

Adding css class through aspx code behind

If you want to add attributes, including the class, you need to set runat="server" on the tag.

    <div id="classMe" runat="server"></div>

Then in the code-behind:

classMe.Attributes.Add("class", "some-class")

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

How to display a list of images in a ListView in Android?

Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.

In main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

  <TextView
      android:id="@+id/textview"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" />

 <ListView
     android:id="@+id/listview"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

create listview_layout.xml and paste this code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

   <ImageView
      android:id="@+id/flag"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:contentDescription="@string/hello"
      android:paddingTop="10dp"
      android:paddingRight="10dp"
      android:paddingBottom="10dp" />

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

     <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:text="TextView1" />

    <TextView
        android:id="@+id/cur"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10dp"
        android:text="TextView2" />
   </LinearLayout>

In your Activity

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class SimpleListImageActivity extends Activity {

    // Array of strings storing country names
    String[] countries = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan"
    };

    // Array of integers points to images stored in /res/drawable-hdpi/

   //here you have to give image name which you already pasted it in /res/drawable-hdpi/

     int[] flags = new int[]{
        R.drawable.image1,
        R.drawable.image2,   
        R.drawable.image3,
        R.drawable.image4,
        R.drawable.image5,
        R.drawable.image6,
        R.drawable.image7,
        R.drawable.image8,
        R.drawable.image9,
        R.drawable.image10,
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
        "Indian Rupee",
        "Pakistani Rupee",
        "Sri Lankan Rupee",
        "Renminbi",
        "Bangladeshi Taka",
        "Nepalese Rupee",
        "Afghani",
        "North Korean Won",
        "South Korean Won",
        "Japanese Yen"
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Each row in the list stores country name, currency and flag
        List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

        for(int i=0;i<10;i++){
            HashMap<String, String> hm = new HashMap<String,String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur","Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]) );
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = { "flag","txt","cur" };

        // Ids of views in listview_layout
        int[] to = { R.id.flag,R.id.txt,R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = ( ListView ) findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
    }
}

This is the full code.you can make changes to your need... Comments are welcome

Running AngularJS initialization code when view is loaded

Since AngularJS 1.5 we should use $onInit which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preffered way:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {

    //default state
    $scope.name = '';

    //all your init controller goodness in here
    this.$onInit = function () {
      $scope.name = 'Superhero';
    }
});

>> Fiddle Demo


An advanced example of using component lifecycle:

The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope event listener $on. By knowing, that an event $on binded on $rootScope will not be undinded when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on listener manually. A good place to put that stuff is $onDestroy lifecycle function of an component:

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

myApp.controller('MyCtrl', function ($scope, $rootScope) {

  var registerScope = null;

  this.$onInit = function () {
    //register rootScope event
    registerScope = $rootScope.$on('someEvent', function(event) {
        console.log("fired");
    });
  }

  this.$onDestroy = function () {
    //unregister rootScope event by calling the return function
    registerScope();
  }
});

>> Fiddle demo

How can I get System variable value in Java?

To clarify, system variables are the same as environment variables. User environment variables are set per user and are different whenever a different user logs in. System wide environment variables are the same no matter what user logs on.

To access either the current value of a system wide variable or a user variable in Java, see below:

String javaHome = System.getenv("JAVA_HOME");

For more information on environment variables see this wikipedia page.

Also make sure the environment variable you are trying to read is properly set before invoking Java by doing a:

echo %MYENVVAR%

You should see the value of the environment variable. If not, you may need to reopen the shell (DOS) or log off and log back on.

Pandas dataframe get first row of each group

maybe this is what you want

import pandas as pd
idx = pd.MultiIndex.from_product([['state1','state2'],   ['county1','county2','county3','county4']])
df = pd.DataFrame({'pop': [12,15,65,42,78,67,55,31]}, index=idx)
                pop
state1 county1   12
       county2   15
       county3   65
       county4   42
state2 county1   78
       county2   67
       county3   55
       county4   31
df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('pop', ascending=False)).groupby(level=0).head(3)

> Out[29]: 
                pop
state1 county3   65
       county4   42
       county2   15
state2 county1   78
       county2   67
       county3   55

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

Calculating powers of integers

import java.util.*;

public class Power {

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int num = 0;
        int pow = 0;
        int power = 0;

        System.out.print("Enter number: ");
        num = sc.nextInt();

        System.out.print("Enter power: ");
        pow = sc.nextInt();

        System.out.print(power(num,pow));
    }

    public static int power(int a, int b)
    {
        int power = 1;

        for(int c = 0; c < b; c++)
            power *= a;

        return power;
    }

}

What is the difference between the kernel space and the user space?

The kernel space means a memory space can only be touched by kernel. On 32bit linux it is 1G(from 0xC0000000 to 0xffffffff as virtual memory address).Every process created by kernel is also a kernel thread, So for one process, there are two stacks: one stack in user space for this process and another in kernel space for kernel thread.

the kernel stack occupied 2 pages(8k in 32bit linux), include a task_struct(about 1k) and the real stack(about 7k). The latter is used to store some auto variables or function call params or function address in kernel functions. Here is the code(Processor.h (linux\include\asm-i386)):

#define THREAD_SIZE (2*PAGE_SIZE)
#define alloc_task_struct() ((struct task_struct *) __get_free_pages(GFP_KERNEL,1))
#define free_task_struct(p) free_pages((unsigned long) (p), 1)

__get_free_pages(GFP_KERNEL,1)) means alloc memory as 2^1=2 pages.

But the process stack is another thing, its address is just bellow 0xC0000000(32bit linux), the size of it can be quite bigger, used for the user space function calls.

So here is a question come for system call, it is running in kernel space but was called by process in user space, how does it work? Will linux put its params and function address in kernel stack or process stack? Linux's solution: all system call are triggered by software interruption INT 0x80. Defined in entry.S (linux\arch\i386\kernel), here is some lines for example:

ENTRY(sys_call_table)
.long SYMBOL_NAME(sys_ni_syscall)   /* 0  -  old "setup()" system call*/
.long SYMBOL_NAME(sys_exit)
.long SYMBOL_NAME(sys_fork)
.long SYMBOL_NAME(sys_read)
.long SYMBOL_NAME(sys_write)
.long SYMBOL_NAME(sys_open)     /* 5 */
.long SYMBOL_NAME(sys_close)

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

You can use the shorthand flex property and set it to

flex: 0 0 100%;

That's flex-grow, flex-shrink, and flex-basis in one line. Flex shrink was described above, flex grow is the opposite, and flex basis is the size of the container.

Fastest way to convert string to integer in PHP

I've just set up a quick benchmarking exercise:

Function             time to run 1 million iterations
--------------------------------------------
(int) "123":                0.55029
intval("123"):              1.0115  (183%)

(int) "0":                  0.42461
intval("0"):                0.95683 (225%)

(int) int:                  0.1502
intval(int):                0.65716 (438%)

(int) array("a", "b"):      0.91264
intval(array("a", "b")):    1.47681 (162%)

(int) "hello":              0.42208
intval("hello"):            0.93678 (222%)

On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.

I'd be interested to know why though.


Update: I've run the tests again, this time with coercion (0 + $var)

| INPUT ($x)      |  (int) $x  |intval($x) |  0 + $x   |
|-----------------|------------|-----------|-----------|
| "123"           |   0.51541  |  0.96924  |  0.33828  |
| "0"             |   0.42723  |  0.97418  |  0.31353  |
| 123             |   0.15011  |  0.61690  |  0.15452  |
| array("a", "b") |   0.8893   |  1.45109  |  err!     |
| "hello"         |   0.42618  |  0.88803  |  0.1691   |
|-----------------|------------|-----------|-----------|

Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:

$x = "11";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11)

$x = "0x11";
(int) $x;      // int(0)
intval($x);    // int(0)
$x + 0;        // int(17) !

$x = "011";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11) (not 9)

Tested using PHP 5.3.1

@Resource vs @Autowired

As a note here: SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext and SpringBeanAutowiringSupport.processInjectionBasedOnServletContext DOES NOT work with @Resource annotation. So, there are difference.

How to reference static assets within vue javascript

Having a default structure of folders generated by Vue CLI such as src/assets you can place your image there and refer this from HTML as follows <img src="../src/assets/img/logo.png"> as well (works automatically without any changes on deployment too).

What's the best way to iterate an Android Cursor?

The simplest way is this:

while (cursor.moveToNext()) {
    ...
}

The cursor starts before the first result row, so on the first iteration this moves to the first result if it exists. If the cursor is empty, or the last row has already been processed, then the loop exits neatly.

Of course, don't forget to close the cursor once you're done with it, preferably in a finally clause.

Cursor cursor = db.rawQuery(...);
try {
    while (cursor.moveToNext()) {
        ...
    }
} finally {
    cursor.close();
}

If you target API 19+, you can use try-with-resources.

try (Cursor cursor = db.rawQuery(...)) {
    while (cursor.moveToNext()) {
        ...
    }
}

Javascript equivalent of php's strtotime()?

Check out this implementation of PHP's strtotime() in JavaScript!

I found that it works identically to PHP for everything that I threw at it.

Update: this function as per version 1.0.2 can't handle this case: '2007:07:20 20:52:45' (Note the : separator for year and month)

Update 2018:

This is now available as an npm module! Simply npm install locutus and then in your source:

var strtotime = require('locutus/php/datetime/strtotime');

Center text in div?

Will this work for you?

div { text-align: center; }

How to download and save a file from Internet using Java?

Personally, I've found Apache's HttpClient to be more than capable of everything I've needed to do with regards to this. Here is a great tutorial on using HttpClient

Value of type 'T' cannot be converted to

Even though it's inside of an if block, the compiler doesn't know that T is string.
Therefore, it doesn't let you cast. (For the same reason that you cannot cast DateTime to string)

You need to cast to object, (which any T can cast to), and from there to string (since object can be cast to string).
For example:

T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

How to write a UTF-8 file with Java?

Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:

try (OutputStreamWriter writer =
             new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
    // do stuff
}

How do I check if a Socket is currently connected in Java?

Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.

TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.

See Do I need to heartbeat to keep a TCP connection open? for more discussion.

C compile : collect2: error: ld returned 1 exit status

This issue appears when you have a running console at the time you try to run other (or the same) program.

I had this problem during executing a program on Sublime Text while I had another one running on DevC++ already.

How to run only one unit test class using Gradle

After much figuring out, the following worked for me:

gradle test --tests "a.b.c.MyTestFile.mySingleTest"

Removing unwanted table cell borders with CSS

After trying the above suggestions, the only thing that worked for me was changing the border attribute to "0" in the following sections of a child theme's style.css (do a "Find" operation to locate each one -- the following are just snippets):

.comment-content table {
    border-bottom: 1px solid #ddd;

.comment-content td {
    border-top: 1px solid #ddd;
    padding: 6px 10px 6px 0;
}

Thus looking like this afterwards:

.comment-content table {
    border-bottom: 0;

.comment-content td {
    border-top: 0;
    padding: 6px 10px 6px 0;
}

Add error bars to show standard deviation on a plot in R

You can use segments to add the bars in base graphics. Here epsilon controls the line across the top and bottom of the line.

plot (x, y, ylim=c(0, 6))
epsilon = 0.02
for(i in 1:5) {
    up = y[i] + sd[i]
    low = y[i] - sd[i]
    segments(x[i],low , x[i], up)
    segments(x[i]-epsilon, up , x[i]+epsilon, up)
    segments(x[i]-epsilon, low , x[i]+epsilon, low)
}

As @thelatemail points out, I should really have used vectorised function calls:

segments(x, y-sd,x, y+sd)
epsilon = 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

Responsive css background images

background: url(/static/media/group3x.6bb50026.jpg);
background-size: contain;
background-repeat: no-repeat;
background-position: top;

the position property can be used to align top bottom and center as per your need and background-size can be used for center crop(cover) or full image(contain or 100%)

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

INSERTING

enter image description here

REFRESHING THE TABLE

enter image description here

PHP ini file_get_contents external url

Add:

allow_url_fopen=1

in your php.ini file. If you are using shared hosting, create one first.

Trim spaces from end of a NSString

The solution is described here: How to remove whitespace from right end of NSString?

Add the following categories to NSString:

- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
    NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
                                                               options:NSBackwardsSearch];
    if (rangeOfLastWantedCharacter.location == NSNotFound) {
        return @"";
    }
    return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}

- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
    return [self stringByTrimmingTrailingCharactersInSet:
            [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

And you use it as such:

[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

convert json ipython notebook(.ipynb) to .py file

  1. Go to https://jupyter.org/
  2. click on nbviewer
  3. Enter the location of your file and render it.
  4. Click on view as code (shown as < />)

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

time data does not match format

No need to use datetime library. Using the dateutil library there is no need of any format:

>>> from dateutil import parser
>>> s= '25 April, 2020, 2:50, pm, IST'
>>> parser.parse(s)
datetime.datetime(2020, 4, 25, 14, 50)

Efficient way to update all rows in a table

As Marcelo suggests:

UPDATE mytable
SET new_column = <expr containing old_column>;

If this takes too long and fails due to "snapshot too old" errors (e.g. if the expression queries another highly-active table), and if the new value for the column is always NOT NULL, you could update the table in batches:

UPDATE mytable
SET new_column = <expr containing old_column>
WHERE new_column IS NULL
AND ROWNUM <= 100000;

Just run this statement, COMMIT, then run it again; rinse, repeat until it reports "0 rows updated". It'll take longer but each update is less likely to fail.

EDIT:

A better alternative that should be more efficient is to use the DBMS_PARALLEL_EXECUTE API.

Sample code (from Oracle docs):

DECLARE
  l_sql_stmt VARCHAR2(1000);
  l_try NUMBER;
  l_status NUMBER;
BEGIN

  -- Create the TASK
  DBMS_PARALLEL_EXECUTE.CREATE_TASK ('mytask');

  -- Chunk the table by ROWID
  DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_ROWID('mytask', 'HR', 'EMPLOYEES', true, 100);

  -- Execute the DML in parallel
  l_sql_stmt := 'update EMPLOYEES e 
      SET e.salary = e.salary + 10
      WHERE rowid BETWEEN :start_id AND :end_id';
  DBMS_PARALLEL_EXECUTE.RUN_TASK('mytask', l_sql_stmt, DBMS_SQL.NATIVE,
                                 parallel_level => 10);

  -- If there is an error, RESUME it for at most 2 times.
  l_try := 0;
  l_status := DBMS_PARALLEL_EXECUTE.TASK_STATUS('mytask');
  WHILE(l_try < 2 and l_status != DBMS_PARALLEL_EXECUTE.FINISHED) 
  LOOP
    l_try := l_try + 1;
    DBMS_PARALLEL_EXECUTE.RESUME_TASK('mytask');
    l_status := DBMS_PARALLEL_EXECUTE.TASK_STATUS('mytask');
  END LOOP;

  -- Done with processing; drop the task
  DBMS_PARALLEL_EXECUTE.DROP_TASK('mytask');

END;
/

Oracle Docs: https://docs.oracle.com/database/121/ARPLS/d_parallel_ex.htm#ARPLS67333

How do I import CSV file into a MySQL table?

Yet another solution is to use csvsql tool from amazing csvkit suite.

Usage example:

csvsql --db mysql://$user:$password@localhost/$database --insert --tables $tablename  $file

This tool can automatically infer the data types (default behavior), create table and insert the data into the created table. --overwrite option can be used to drop table if it already exists. --insert option — to populate the table from the file.

To install the suite

pip install csvkit

Prerequisites: python-dev, libmysqlclient-dev, MySQL-python

apt-get install python-dev libmysqlclient-dev
pip install MySQL-python

How to write a switch statement in Ruby

It's critical to emphasize the comma (,) in a when clause. It acts as an || of an if statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when clause. See the following case statement:

x = 3
case x
  when 3, x < 2 then 'apple'
  when 3, x > 2 then 'orange'
end
 => "apple"

x is not less than 2, yet the return value is "apple". Why? Because x was 3 and since ',`` acts as an||, it did not bother to evaluate the expressionx < 2'.

You might think that to perform an AND, you can do something like this below, but it doesn't work:

case x
  when (3 && x < 2) then 'apple'
  when (3 && x > 2) then 'orange'
end
 => nil 

It doesn't work because (3 && x > 2) evaluates to true, and Ruby takes the True value and compares it to x with ===, which is not true, since x is 3.

To do an && comparison, you will have to treat case like an if/else block:

case
  when x == 3 && x < 2 then 'apple'
  when x == 3 && x > 2 then 'orange'
end

In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if/elsif/else. However, whether it is infrequently used or not, I do not see any other way to attach multiple && expressions for a given when clause.

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).

Benefits

  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

Real time data graphing on a line chart with html5

There are several charting libraries that can be used : gRaphael, Highcharts and the one mentioned by others. These libraries are quite easy to use and well-documented (lets say 1 on the difficulty scale).

AFAIK, these libs are not "real-time" because they don't give the possibility to add new points on the fly. To add new point, you need to redraw the full chart. But I think this is not a problem because redrawing the chart is fast. I've made some tries with gRaphael and I didn't notice any problem with this approach. If you update rate is 10s that should work ok (but it may depends on the complexity of your charts).

If redrawing the full chart is a problem, you may have to develop a chart by yourself with a vector graphics lib like Raphael or paper.js. That will be a bit harder than using a charting lib but should be feasible. (Let say 5 on the difficulty scale).

As you are getting the data on a fixed intervall, you can use a regular ajax lib. jQuery is ok for me but there are some other choices. That may not be the best choice for a non-fixed interval and in this case you may have to look at something like socket.io but it would have consequences on the server side too.

Note1: Raphael, gRaphael and Highcharts are not purely HTML5 but SVG/VML but I guess this is an acceptable choice too.

Note2: it seems that Highchart doesn't require to redraw the chart when inserting new points. See http://www.highcharts.com/documentation/how-to-use#live-charts

How can I scale an image in a CSS sprite

When you use sprites, you are limited to the dimensions of the image in the sprite. The background-size CSS property, mentioned by Stephen, isn't widely supported yet and might cause problems with browsers like IE8 and below - and given their market share, this isn't a viable option.

Another way to solve the problem is to use two elements and scale the sprite by using it with an img tag, like this:

<div class="sprite-image"
     style="width:20px; height:20px; overflow:hidden; position:relative">
    <!-- set width/height proportionally, to scale the sprite image -->
    <img src="sprite.png" alt="icon"
         width="20" height="80"
         style="position:absolute; top: -20px; left: 0;" />
</div>

This way, the outer element (div.sprite-image) is cropping a 20x20px image from the img tag, which acts like a scaled background-image.

How to drop a database with Mongoose?

To drop all documents in a collection:

await mongoose.connection.db.dropDatabase();

This answer is based off the mongoose index.d.ts file:

dropDatabase(): Promise<any>;

Git resolve conflict using --ours/--theirs for all files

Just grep through the working directory and send the output through the xargs command:

grep -lr '<<<<<<<' . | xargs git checkout --ours

or

grep -lr '<<<<<<<' . | xargs git checkout --theirs

How this works: grep will search through every file in the current directory (the .) and subdirectories recursively (the -r flag) looking for conflict markers (the string '<<<<<<<')

the -l or --files-with-matches flag causes grep to output only the filename where the string was found. Scanning stops after first match, so each matched file is only output once.

The matched file names are then piped to xargs, a utility that breaks up the piped input stream into individual arguments for git checkout --ours or --theirs

More at this link.

Since it would be very inconvenient to have to type this every time at the command line, if you do find yourself using it a lot, it might not be a bad idea to create an alias for your shell of choice: Bash is the usual one.

This method should work through at least Git versions 2.4.x

Add onclick event to newly added element in JavaScript

Short answer: you want to set the handler to a function:

elemm.onclick = function() { alert('blah'); };

Slightly longer answer: you'll have to write a few more lines of code to get that to work consistently across browsers.

The fact is that even the sligthly-longer-code that might solve that particular problem across a set of common browsers will still come with problems of its own. So if you don't care about cross-browser support, go with the totally short one. If you care about it and absolutely only want to get this one single thing working, go with a combination of addEventListener and attachEvent. If you want to be able to extensively create objects and add and remove event listeners throughout your code, and want that to work across browsers, you definitely want to delegate that responsibility to a library such as jQuery.

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

jQuery UI: Datepicker set year range dropdown to 100 years

I wanted to implement the datepicker to select the birthdate and I had troubles changing the yearRange as it doesn't seemed to work with my version (1.5). I updated to the newest jquery-ui datepicker version here: https://github.com/uxsolutions/bootstrap-datepicker.

Then I found out they provide this very helpful on-the-fly tool, so you can config your whole datepicker and see what settings you have to use.

That's how I found out that the option

defaultViewDate

is the option I was looking for and I didn't find any results searching the web.

So for other users: If you also want to provide the datepicker to change the birthdate, I suggest to use this code options:

$('#birthdate').datepicker({
    startView: 2,
    maxViewMode: 2,
    daysOfWeekHighlighted: "1,2",
    defaultViewDate: { year: new Date().getFullYear()-20, month: 01, day: 01 }
});

When opening the datepicker you will start with the view to select the years, 20 years ago relative to the current year.

Detecting input change in jQuery?

This covers every change to an input using jQuery 1.7 and above:

$(".inputElement").on("input", null, null, callbackFunction);

An array of List in c#

List<int>[]  a = new List<int>[100];

You still would have to allocate each individual list in the array before you can use it though:

for (int i = 0; i < a.Length; i++)
    a[i] = new List<int>();

convert string into array of integers

An alternative to Tushar Gupta answer would be :

'14 2'.split(' ').map(x=>+x);

// [14, 2]`

In code golf you save 1 character. Here the "+" is "unary plus" operator, works like parseInt.

How can I make content appear beneath a fixed DIV element?

I liked grdevphl's Javascript answer best, but in my own use case, I found that using height() in the calculation still left a little overlap since it didn't take padding into account. If you run into the same issue, try outerHeight() instead to compensate for padding and border.

$(document).ready(function() {
    var contentPlacement = $('#header').position().top + $('#header').outerHeight();
    $('#content').css('margin-top',contentPlacement);
});

Unsigned keyword in C++

Integer Types:

short            -> signed short
signed short
unsigned short
int              -> signed int
signed int
unsigned int
signed           -> signed int
unsigned         -> unsigned int
long             -> signed long
signed long
unsigned long

Be careful of char:

char  (is signed or unsigned depending on the implmentation)
signed char
unsigned char

-bash: export: `=': not a valid identifier

I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.

Scenario 1: There cannot be spaces beside the = (equals) sign

$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question

$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier

$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier

Scenario 2: Object value assignment should not have spaces besides quotes

$ export TEMP_ENV={ "key" : "json example" } 
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier

Scenario 3: List value assignment should not have spaces between values

$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier

I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.

How to find the width of a div using vanilla JavaScript?

Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:

var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.

Where is Xcode's build folder?

enter image description here

enter image description here

Configure XCode project settings, it can solve your problem.

How do I print out the contents of a vector?

In C++11 you can now use a range-based for loop:

for (auto const& c : path)
    std::cout << c << ' ';

VBA Subscript out of range - error 9

Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.

Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.

As a guess, I would try using this:

Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate

How to convert a char array back to a string?

You can also use StringBuilder class

String b = new StringBuilder(a).toString();

Use of String or StringBuilder varies with your method requirements.

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

How do I specify new lines on Python, when writing on files?

\n separates the lines of a string. In the following example, I keep writing the records in a loop. Each record is separated by \n.

f = open("jsonFile.txt", "w")

for row_index in range(2, sheet.nrows):

  mydict1 = {
    "PowerMeterId" : row_index + 1,
    "Service": "Electricity",
    "Building": "JTC FoodHub",
    "Floor": str(Floor),
    "Location": Location,
    "ReportType": "Electricity",
    "System": System,
    "SubSystem": "",
    "Incomer": "",
    "Category": "",
    "DisplayName": DisplayName,
    "Description": Description,
    "Tag": tag,
    "IsActive": 1,
    "DataProviderType": int(0),
    "DataTable": ""
  }
  mydict1.pop("_id", None)
  f.write(str(mydict1) + '\n')

f.close()

Room persistance library. Delete all

To make use of the Room without abuse of the @Query annotation first use @Query to select all rows and put them in a list, for example:

@Query("SELECT * FROM your_class_table")

List`<`your_class`>` load_all_your_class();

Put his list into the delete annotation, for example:

@Delete

void deleteAllOfYourTable(List`<`your_class`>` your_class_list);

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

XAMPP installation on Win 8.1 with UAC Warning

As ivan.sim writes in his answer

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC(User Account Control) as it restricts certain administrative function needed to run a web server.
  3. Install in C://xampp.

Problem with the correct answer is in the explanation of point 2., and magicandre1981 writes more about it

Moving the slider down doesn't completely disable UAC since Windows 8. This is changed compared to Windows 7, because the new Store apps require an active UAC. With UAC off, they no longer run.


How can we then disable UAC and install XAMPP?

Easy. Go to Registry Editor and navigate to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

Registry Editor

Right click EnableLUA and modify the Value data to 0.

EnableLUA

Then restart your computer and you're ready to install XAMPP.

Installing XAMPP

XAMPP installed

XAMPP Control Panel

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

What are the differences between .so and .dylib on osx?

Just an observation I just made while building naive code on OSX with cmake:

cmake ... -DBUILD_SHARED_LIBS=OFF ...

creates .so files

while

cmake ... -DBUILD_SHARED_LIBS=ON ...

creates .dynlib files.

Perhaps this helps anyone.

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

HTTP test server accepting GET/POST requests

You can run the actual Ken Reitz's httpbin server locally (under docker or on bare metal):

https://github.com/postmanlabs/httpbin

Run dockerized

docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin

Run directly on your machine

## install dependencies
pip3 install gunicorn decorator httpbin werkzeug Flask flasgger brotlipy gevent meinheld six pyyaml

## start the server
gunicorn -b 0.0.0.0:8000 httpbin:app -k gevent

Now you have your personal httpbin instance running on http://0.0.0.0:8000 (visible to all of your LAN)

Ascii/Hex convert in bash

Finally got the correct thing

echo "Hello, world!" | tr -d '\n' | xxd -ps -c 200

How do I center align horizontal <UL> menu?

I used the display:inline-block property: the solution consist in use a wrapper with fixed width. Inside, the ul block with the inline-block for display. Using this, the ul just take the width for the real content! and finally margin: 0 auto, to center this inline-block =)

/*ul wrapper*/
.gallery_wrapper{
        width:          958px;
        margin:         0 auto;
  }
/*ul list*/
ul.gallery_carrousel{
        display:        inline-block;
        margin:         0 auto;
}
.contenido_secundario li{
        float:          left;
}

What's the purpose of the LEA instruction?

LEA : just an "arithmetic" instruction..

MOV transfers data between operands but lea is just calculating

What does LINQ return when the results are empty

.ToList returns an empty list. (same as new List() );

Forward X11 failed: Network error: Connection refused

I had the same problem, but it's solved now. Finally, Putty does work with Cigwin-X, and Xming is not an obligatory app for MS-Windows X-server.

Nowadays it's xlaunch, who controls the run of X-window. Certainly, xlaunch.exe must be installed in Cigwin. When run in interactive mode it asks for "extra settings". You should add "-listen tcp" to additional param field, since Cigwin-X does not listen TCP by default.

In order to not repeat these steps, you may save settings to the file. And run xlaunch.exe via its shortcut with modified CLI inside. Something like

C:\cygwin64\bin\xlaunch.exe -run C:\cygwin64\config.xlaunch

HTML checkbox - allow to check only one checkbox

$('#OvernightOnshore').click(function () {
    if ($('#OvernightOnshore').prop("checked") == true) {
        if ($('#OvernightOffshore').prop("checked") == true) {
            $('#OvernightOffshore').attr('checked', false)
        }
    }
})

$('#OvernightOffshore').click(function () {
    if ($('#OvernightOffshore').prop("checked") == true) {
        if ($('#OvernightOnshore').prop("checked") == true) {
            $('#OvernightOnshore').attr('checked', false);
        }
    }
})

This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.

How can I tell gcc not to inline a function?

You want the gcc-specific noinline attribute.

This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put asm ("");

Use it like this:

void __attribute__ ((noinline)) foo() 
{
  ...
}

Ineligible Devices section appeared in Xcode 6.x.x

I can confirm that the answer it to upgrade Xcode to 6.1. If you are using Xcode 6.0.x you will not be able to select a device running 8.1. Your deployment targets and OS version should have nothing to do with this.

If your OS version is greater than 10.9.4 I would recommend this. First, un-attaching all devices. Download Xcode 6.1. After opening the new version of Xcode attach your device. You should be good to go.

Another good thing would be to look at the release notes. It's and easy read and gives you a general idea of what still needs to be fixed.

Named colors in matplotlib

Matplotlib uses a dictionary from its colors.py module.

To print the names use:

# python2:

import matplotlib
for name, hex in matplotlib.colors.cnames.iteritems():
    print(name, hex)

# python3:

import matplotlib
for name, hex in matplotlib.colors.cnames.items():
    print(name, hex)

This is the complete dictionary:

cnames = {
'aliceblue':            '#F0F8FF',
'antiquewhite':         '#FAEBD7',
'aqua':                 '#00FFFF',
'aquamarine':           '#7FFFD4',
'azure':                '#F0FFFF',
'beige':                '#F5F5DC',
'bisque':               '#FFE4C4',
'black':                '#000000',
'blanchedalmond':       '#FFEBCD',
'blue':                 '#0000FF',
'blueviolet':           '#8A2BE2',
'brown':                '#A52A2A',
'burlywood':            '#DEB887',
'cadetblue':            '#5F9EA0',
'chartreuse':           '#7FFF00',
'chocolate':            '#D2691E',
'coral':                '#FF7F50',
'cornflowerblue':       '#6495ED',
'cornsilk':             '#FFF8DC',
'crimson':              '#DC143C',
'cyan':                 '#00FFFF',
'darkblue':             '#00008B',
'darkcyan':             '#008B8B',
'darkgoldenrod':        '#B8860B',
'darkgray':             '#A9A9A9',
'darkgreen':            '#006400',
'darkkhaki':            '#BDB76B',
'darkmagenta':          '#8B008B',
'darkolivegreen':       '#556B2F',
'darkorange':           '#FF8C00',
'darkorchid':           '#9932CC',
'darkred':              '#8B0000',
'darksalmon':           '#E9967A',
'darkseagreen':         '#8FBC8F',
'darkslateblue':        '#483D8B',
'darkslategray':        '#2F4F4F',
'darkturquoise':        '#00CED1',
'darkviolet':           '#9400D3',
'deeppink':             '#FF1493',
'deepskyblue':          '#00BFFF',
'dimgray':              '#696969',
'dodgerblue':           '#1E90FF',
'firebrick':            '#B22222',
'floralwhite':          '#FFFAF0',
'forestgreen':          '#228B22',
'fuchsia':              '#FF00FF',
'gainsboro':            '#DCDCDC',
'ghostwhite':           '#F8F8FF',
'gold':                 '#FFD700',
'goldenrod':            '#DAA520',
'gray':                 '#808080',
'green':                '#008000',
'greenyellow':          '#ADFF2F',
'honeydew':             '#F0FFF0',
'hotpink':              '#FF69B4',
'indianred':            '#CD5C5C',
'indigo':               '#4B0082',
'ivory':                '#FFFFF0',
'khaki':                '#F0E68C',
'lavender':             '#E6E6FA',
'lavenderblush':        '#FFF0F5',
'lawngreen':            '#7CFC00',
'lemonchiffon':         '#FFFACD',
'lightblue':            '#ADD8E6',
'lightcoral':           '#F08080',
'lightcyan':            '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgreen':           '#90EE90',
'lightgray':            '#D3D3D3',
'lightpink':            '#FFB6C1',
'lightsalmon':          '#FFA07A',
'lightseagreen':        '#20B2AA',
'lightskyblue':         '#87CEFA',
'lightslategray':       '#778899',
'lightsteelblue':       '#B0C4DE',
'lightyellow':          '#FFFFE0',
'lime':                 '#00FF00',
'limegreen':            '#32CD32',
'linen':                '#FAF0E6',
'magenta':              '#FF00FF',
'maroon':               '#800000',
'mediumaquamarine':     '#66CDAA',
'mediumblue':           '#0000CD',
'mediumorchid':         '#BA55D3',
'mediumpurple':         '#9370DB',
'mediumseagreen':       '#3CB371',
'mediumslateblue':      '#7B68EE',
'mediumspringgreen':    '#00FA9A',
'mediumturquoise':      '#48D1CC',
'mediumvioletred':      '#C71585',
'midnightblue':         '#191970',
'mintcream':            '#F5FFFA',
'mistyrose':            '#FFE4E1',
'moccasin':             '#FFE4B5',
'navajowhite':          '#FFDEAD',
'navy':                 '#000080',
'oldlace':              '#FDF5E6',
'olive':                '#808000',
'olivedrab':            '#6B8E23',
'orange':               '#FFA500',
'orangered':            '#FF4500',
'orchid':               '#DA70D6',
'palegoldenrod':        '#EEE8AA',
'palegreen':            '#98FB98',
'paleturquoise':        '#AFEEEE',
'palevioletred':        '#DB7093',
'papayawhip':           '#FFEFD5',
'peachpuff':            '#FFDAB9',
'peru':                 '#CD853F',
'pink':                 '#FFC0CB',
'plum':                 '#DDA0DD',
'powderblue':           '#B0E0E6',
'purple':               '#800080',
'red':                  '#FF0000',
'rosybrown':            '#BC8F8F',
'royalblue':            '#4169E1',
'saddlebrown':          '#8B4513',
'salmon':               '#FA8072',
'sandybrown':           '#FAA460',
'seagreen':             '#2E8B57',
'seashell':             '#FFF5EE',
'sienna':               '#A0522D',
'silver':               '#C0C0C0',
'skyblue':              '#87CEEB',
'slateblue':            '#6A5ACD',
'slategray':            '#708090',
'snow':                 '#FFFAFA',
'springgreen':          '#00FF7F',
'steelblue':            '#4682B4',
'tan':                  '#D2B48C',
'teal':                 '#008080',
'thistle':              '#D8BFD8',
'tomato':               '#FF6347',
'turquoise':            '#40E0D0',
'violet':               '#EE82EE',
'wheat':                '#F5DEB3',
'white':                '#FFFFFF',
'whitesmoke':           '#F5F5F5',
'yellow':               '#FFFF00',
'yellowgreen':          '#9ACD32'}

You could plot them like this:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.colors as colors
import math


fig = plt.figure()
ax = fig.add_subplot(111)

ratio = 1.0 / 3.0
count = math.ceil(math.sqrt(len(colors.cnames)))
x_count = count * ratio
y_count = count / ratio
x = 0
y = 0
w = 1 / x_count
h = 1 / y_count

for c in colors.cnames:
    pos = (x / x_count, y / y_count)
    ax.add_patch(patches.Rectangle(pos, w, h, color=c))
    ax.annotate(c, xy=pos)
    if y >= y_count-1:
        x += 1
        y = 0
    else:
        y += 1

plt.show()

Run two async tasks in parallel and collect results in .NET 4.5

You should use Task.Delay instead of Sleep for async programming and then use Task.WhenAll to combine the task results. The tasks would run in parallel.

public class Program
    {
        static void Main(string[] args)
        {
            Go();
        }
        public static void Go()
        {
            GoAsync();
            Console.ReadLine();
        }
        public static async void GoAsync()
        {

            Console.WriteLine("Starting");

            var task1 = Sleep(5000);
            var task2 = Sleep(3000);

            int[] result = await Task.WhenAll(task1, task2);

            Console.WriteLine("Slept for a total of " + result.Sum() + " ms");

        }

        private async static Task<int> Sleep(int ms)
        {
            Console.WriteLine("Sleeping for {0} at {1}", ms, Environment.TickCount);
            await Task.Delay(ms);
            Console.WriteLine("Sleeping for {0} finished at {1}", ms, Environment.TickCount);
            return ms;
        }
    }

html text input onchange event

Use the oninput event

<input type="text" oninput="myFunction();" />

Browse files and subfolders in Python

In python 3 you can use os.scandir():

for i in os.scandir(path):
    if i.is_file():
        print('File: ' + i.path)
    elif i.is_dir():
        print('Folder: ' + i.path)

jQuery move to anchor location on page load

Put this right before the closing Body tag at the bottom of the page.

<script>
    if (location.hash) {
        location.href = location.hash;
    }
</script>

jQuery is actually not required.

SQL RANK() versus ROW_NUMBER()

Look this example.

CREATE TABLE [dbo].#TestTable(
    [id] [int] NOT NULL,
    [create_date] [date] NOT NULL,
    [info1] [varchar](50) NOT NULL,
    [info2] [varchar](50) NOT NULL,
)

Insert some data

INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/1/09', 'Blue', 'Green')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/2/09', 'Red', 'Yellow')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/3/09', 'Orange', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/1/09', 'Yellow', 'Blue')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/5/09', 'Blue', 'Orange')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/2/09', 'Green', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/8/09', 'Red', 'Blue')

Repeat same Values for 1

INSERT INTO dbo.#TestTable (id, create_date, info1, info2) VALUES (1, '1/1/09', 'Blue', 'Green')

Look All

SELECT * FROM #TestTable

Look your results

SELECT Id,
    create_date,
    info1,
    info2,
    ROW_NUMBER() OVER (PARTITION BY Id ORDER BY create_date DESC) AS RowId,
    RANK() OVER(PARTITION BY Id ORDER BY create_date DESC)    AS [RANK]
FROM #TestTable

Need to understand the different

ImportError: No module named _ssl

Either install the supplementary packages for python-ssl using your package manager or recompile Python using -with-ssl (requires OpenSSL headers/libs installed).

Support for the experimental syntax 'classProperties' isn't currently enabled

I created a symlink for src/components -> ../../components that caused npm start to go nuts and stop interpreting src/components/*.js as jsx, thus giving that same error. All instructions to fix it from official babel were useless. When I copied back the components directory everything was BACK TO NORMAL!

Error: vector does not name a type

You forgot to add std:: namespace prefix to vector class name.

Create a new line in Java's FileWriter

If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.

try {
    BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
        writer.write(jTextField1.getText());
        writer.write(jTextField2.getText());
        writer.newLine();
        writer.flush();
        writer.close();
} catch (IOException ex) {
    System.out.println("File could not be created");
}

pandas GroupBy columns with NaN (missing) values

pandas >= 1.1

From pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False:

pd.__version__
# '1.1.0.dev0+2004.g8d10bfb6f'

# Example from the docs
df

   a    b  c
0  1  2.0  3
1  1  NaN  4
2  2  1.0  3
3  1  2.0  2

# without NA (the default)
df.groupby('b').sum()

     a  c
b        
1.0  2  3
2.0  2  5
# with NA
df.groupby('b', dropna=False).sum()

     a  c
b        
1.0  2  3
2.0  2  5
NaN  1  4

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

Laravel 4: how to run a raw SQL?

You can also use DB::unprepared for ALTER TABLE queries.

DB::unprepared is meant to be used for queries like CREATE TRIGGER. But essentially it executes raw sql queries directly. (without using PDO prepared statements)

https://github.com/laravel/framework/pull/54

Java: How to Indent XML Generated by Transformer

For me adding DOCTYPE_PUBLIC worked:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "10");

How do I install Maven with Yum?

For those of you that are looking for a way to install Maven in 2018:

$ sudo yum install maven

is supported these days.

"git pull" or "git merge" between master and development branches

my rule of thumb is:

rebase for branches with the same name, merge otherwise.

examples for same names would be master, origin/master and otherRemote/master.

if develop exists only in the local repository, and it is always based on a recent origin/master commit, you should call it master, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master branch.

if develop is shared, it should not be rebased on master, just merged back into it with --no-ff. you are developing on develop. master and develop have different names, because we want them to be different things, and stay separate. do not make them same with rebase.

Git refusing to merge unrelated histories on rebase

In my case, the error was just fatal: refusing to merge unrelated histories on every try, especially the first pull request after remotely adding a Git repository.

Using the --allow-unrelated-histories flag worked with a pull request in this way:

git pull origin branchname --allow-unrelated-histories

How can I find a specific element in a List<T>?

You can also use LINQ extensions:

string id = "hello";
MyClass result = list.Where(m => m.GetId() == id).First();

How to force a hover state with jQuery?

You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover rules to not only apply to physically-hovered links, but also to links that have the classname hovered.

a:hover, a.hovered { color: #ccff00; }

Next, when you click #btn, we'll toggle the .hovered class on the #link.

$("#btn").click(function() {
   $("#link").toggleClass("hovered");
});

If the link has the class already, it will be removed. If it doesn't have the class, it will be added.

Viewing root access files/folders of android on windows

You can use Eclipse DDMS perspective to see connected devices and browse through files, you can also pull and push files to the device. You can also do a bunch of stuff using DDMS, this link explains a little bit more of DDMS uses.

EDIT:

If you just want to copy a database you can locate the database on eclipse DDMS file explorer, select it and then pull the database from the device to your computer.

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

On a POSIX system, you probably should use getline if it's available.

You also can use Chuck Falconer's public domain ggets function which provides syntax closer to gets but without the problems. (Chuck Falconer's website is no longer available, although archive.org has a copy, and I've made my own page for ggets.)

Cleanest Way to Invoke Cross-Thread Events

A couple of observations:

  • Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use:
   BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent), 
               sender, 
               args);
  • Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list.

  • I would probably favor Invoke over BeginInvoke as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to EndInvoke. What would happen is that your app will end up getting a TargetInvocationException instead.

React Hooks useState() with Object

function App() {

  const [todos, setTodos] = useState([
    { id: 1, title: "Selectus aut autem", completed: false },
    { id: 2, title: "Luis ut nam facilis et officia qui", completed: false },
    { id: 3, title: "Fugiat veniam minus", completed: false },
    { id: 4, title: "Aet porro tempora", completed: true },
    { id: 5, title: "Laboriosam mollitia et enim quasi", completed: false }
  ]);

  const changeInput = (e) => {todos.map(items => items.id === parseInt(e.target.value) && (items.completed = e.target.checked));
 setTodos([...todos], todos);}
  return (
    <div className="container">
      {todos.map(items => {
        return (
          <div key={items.id}>
            <label>
<input type="checkbox" 
onChange={changeInput} 
value={items.id} 
checked={items.completed} />&nbsp; {items.title}</label>
          </div>
        )
      })}
    </div>
  );
}

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

Here´s how I do it:

    <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <appendAssemblyId>false</appendAssemblyId>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <archive>
                    <manifest>
                        <mainClass>com.project.MainClass</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

And then I just run:

mvn assembly:assembly

Watermark / hint text / placeholder TextBox

<TextBox Controls:TextBoxHelper.Watermark="Watermark"/>

Add mahapps.metro to your project. Add textbox with the above code to the window.

Why in C++ do we use DWORD rather than unsigned int?

SDK developers prefer to define their own types using typedef. This allows changing underlying types only in one place, without changing all client code. It is important to follow this convention. DWORD is unlikely to be changed, but types like DWORD_PTR are different on different platforms, like Win32 and x64. So, if some function has DWORD parameter, use DWORD and not unsigned int, and your code will be compiled in all future windows headers versions.

jQuery hasAttr checking to see if there is an attribute on an element

Late to the party, but... why not just this.hasAttribute("name")?

Refer This

iFrame onload JavaScript event

_x000D_
_x000D_
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
    this.style.backgroundColor = "red";_x000D_
    alert(this.nodeName);_x000D_
_x000D_
    console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
_x000D_
_x000D_

How to unescape a Java string literal in Java?

For the record, if you use Scala, you can do:

StringContext.treatEscapes(escaped)

Escaping special characters in Java Regular Expressions

The only way the regex matcher knows you are looking for a digit and not the letter d is to escape the letter (\d). To type the regex escape character in java, you need to escape it (so \ becomes \\). So, there's no way around typing double backslashes for special regex chars.

How can I change the user on Git Bash?

For Mac Users

I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.

You need to remove those credentials from Keychain Access and then try to push.

Hope it help to Mac users.

Can a table have two foreign keys?

Yes, MySQL allows this. You can have multiple foreign keys on the same table.

Get more details here FOREIGN KEY Constraints

How to customize Bootstrap 3 tab color

On the selector .nav-tabs > li > a:hover add !important to the background-color.

_x000D_
_x000D_
.nav-tabs{_x000D_
  background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
    background-color:#303136;_x000D_
    color:#fff;_x000D_
    padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
  border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
  background-color: #303136 !important;_x000D_
    border: medium none;_x000D_
    border-radius: 0;_x000D_
    color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
    <li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
    <li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
    <div id="search" class="tab-pane fade in active">_x000D_
        Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
        butcher voluptate nisi qui._x000D_
    </div>_x000D_
    <div id="advanced" class="tab-pane fade">_x000D_
        Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I make a newline after a twitter bootstrap element?

May be the solution could be use a padding property.

<div class="well span6" style="padding-top: 50px">
    <h3>I wish this appeared on the next line without having to 
        gratuitously use BR!
    </h3>
</div>

Redirect to external URI from ASP.NET MVC controller

Using JavaScript

 public ActionResult Index()
 {
    return Content("<script>window.location = 'http://www.example.com';</script>");
 }

Note: As @Jeremy Ray Brown said , This is not the best option but you might find useful in some situations.

Hope this helps.

How to set HttpResponse timeout for Android in Java

you can creat HttpClient instance by the way with Httpclient-android-4.3.5,it can work well.

 SSLContext sslContext = SSLContexts.createSystemDefault();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
                RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCircularRedirectsAllowed(false).setConnectionRequestTimeout(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000);
        CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfigBuilder.build()).build();

In c# is there a method to find the max of 3 numbers?

As generic

public static T Min<T>(params T[] values) {
    return values.Min();
}

public static T Max<T>(params T[] values) {
    return values.Max();
}

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

How to change the height of a div dynamically based on another div using css?

In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...

function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}

You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/

Creating a range of dates in Python

If there are two dates and you need the range try

from dateutil import rrule, parser
date1 = '1995-01-01'
date2 = '1995-02-28'
datesx = list(rrule.rrule(rrule.DAILY, dtstart=parser.parse(date1), until=parser.parse(date2)))

How to create a TextArea in Android

If you do not want to allow user to enter text TextView is the best option here. Any how you can also add EditText for this purpose. here is a sample code for that.

This would automatically show scrollbar if there is more text than the specified lines.

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:lines="8"
    android:maxLines="10"
    android:minLines="6"
    android:scrollbars="vertical" />

Edit: Adding attributes below to textView would make it a textArea that would not be editable.

android:lines="8"
android:maxLines="10"
android:minLines="6" // optional

Transpose list of lists

    #Import functions from library
    from numpy import size, array
    #Transpose a 2D list
    def transpose_list_2d(list_in_mat):
        list_out_mat = []
        array_in_mat = array(list_in_mat)
        array_out_mat = array_in_mat.T
        nb_lines = size(array_out_mat, 0)
        for i_line_out in range(0, nb_lines):
            array_out_line = array_out_mat[i_line_out]
            list_out_line = list(array_out_line)
            list_out_mat.append(list_out_line)
        return list_out_mat

Check that a input to UITextField is numeric only

You can do it in a few lines like this:

BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [alphaNums isSupersetOfSet:inStringSet];    
if (!valid) // Not numeric

-- this is for validating input is numeric chars only. Look at the documentation for NSCharacterSet for the other options. You can use characterSetWithCharactersInString to specify any set of valid input characters.

Construct pandas DataFrame from items in nested dictionary

In case someone wants to get the data frame in a "long format" (leaf values have the same type) without multiindex, you can do this:

pd.DataFrame.from_records(
    [
        (level1, level2, level3, leaf)
        for level1, level2_dict in user_dict.items()
        for level2, level3_dict in level2_dict.items()
        for level3, leaf in level3_dict.items()
    ],
    columns=['UserId', 'Category', 'Attribute', 'value']
)

    UserId    Category Attribute     value
0       12  Category 1     att_1         1
1       12  Category 1     att_2  whatever
2       12  Category 2     att_1        23
3       12  Category 2     att_2   another
4       15  Category 1     att_1        10
5       15  Category 1     att_2       foo
6       15  Category 2     att_1        30
7       15  Category 2     att_2       bar

(I know the original question probably wants (I.) to have Levels 1 and 2 as multiindex and Level 3 as columns and (II.) asks about other ways than iteration over values in the dict. But I hope this answer is still relevant and useful (I.): to people like me who have tried to find a way to get the nested dict into this shape and google only returns this question and (II.): because other answers involve some iteration as well and I find this approach flexible and easy to read; not sure about performance, though.)

Why can't I inherit static classes?

What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces

How to create an Excel File with Nodejs?

install exceljs

npm i exceljs --save

import exceljs

var Excel = require('exceljs');
var workbook = new Excel.Workbook();

create workbook

var options = {
                filename: __dirname+'/Reports/'+reportName,
                useStyles: true,
                useSharedStrings: true
            };

            var workbook = new Excel.stream.xlsx.WorkbookWriter(options);

after create worksheet

var worksheet = workbook.addWorksheet('Rate Sheet',{properties:{tabColor:{argb:'FFC0000'}}});

in worksheet.column array you pass column name in header and array key pass in key

worksheet.columns = [
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 20},

            ];

after using forEach loop append row one by one in exel file

array.forEach(function(row){ worksheet.addRow(row); })

you can also perfome loop on each exel row and cell

worksheet.eachRow(function(row, rowNumber) {
    console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});
row.eachCell(function(cell, colNumber) {
    console.log('Cell ' + colNumber + ' = ' + cell.value);
});

Download a single folder or directory from a GitHub repo

Two options for this feature:

Option 1: GitZip Browser Extension

Chrome Extension, Firefox Addon

Usage:

  1. In any GitHub repos page.
  2. Just double click on the blank part of the items you need.
  3. Click download button at bottom-right.
  4. See the progress dashboard and wait for browser trigger download.
  5. Get the ZIP file.

Get Token:

  1. Click GitZip Extension icon on your browser.
  2. Click "Normal" or "Private" link besides "Get Token".
  3. Authorize GitZip permission on Github auth page.
  4. Back to repo page of the beginning.
  5. Continue to use.

Option 2: Github gh-page

http://kinolien.github.io/gitzip by using GitHub API, and JSZip, FileSaver.js libraries.

Step1: Input github url to the field at the top-right.
Step2: Press enter or click download for download zip directly or click search for view the list of sub-folders and files.
Step3: Click "Download Zip File" or "Get File" button to get files.

In most cases, it works fine, except that the folder contains more than 1,000 files, because of the Github Trees API limitation. (refers to Github API#Contents)

And it also can support private/public repos and upgrade the rate limit, if you have GitHub account and use "get token" link in this site.

Replace last occurrence of a string in a string

You could do this:

$str = 'Hello world';
$str = rtrim($str, 'world') . 'John';

Result is 'Hello John';

Regards

How can I split a string into segments of n characters?

Here we intersperse a string with another string every n characters:

export const intersperseString = (n: number, intersperseWith: string, str: string): string => {

  let ret = str.slice(0,n), remaining = str;

  while (remaining) {
    let v = remaining.slice(0, n);
    remaining = remaining.slice(v.length);
    ret += intersperseWith + v;
  }

  return ret;

};

if we use the above like so:

console.log(splitString(3,'|', 'aagaegeage'));

we get:

aag|aag|aeg|eag|e

and here we do the same, but push to an array:

export const sperseString = (n: number, str: string): Array<string> => {

  let ret = [], remaining = str;

  while (remaining) {
    let v = remaining.slice(0, n);
    remaining = remaining.slice(v.length);
    ret.push(v);
  }

  return ret;

};

and then run it:

console.log(sperseString(5, 'foobarbaztruck'));

we get:

[ 'fooba', 'rbazt', 'ruck' ]

if someone knows of a way to simplify the above code, lmk, but it should work fine for strings.

How to reset a select element with jQuery

This does the trick, and works for any select.

$('#baba').val($(this).find('option:first').val());

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

For all those who are reading this but do not have problem with application.css and instead with their custom CSS classes e.g. admin.css, base.css etc.

Solution is to use as mentioned

bundle exec rake assets:precompile

And in stylesheets references just reference application.css

<%= stylesheet_link_tag    "application", :media => "all" %>

Since assets pipeline will precompile all of your stylesheets in application.css. This also happens in development so using any other references is wrong when using assets pipeline.

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

DOS: find a string, if found then run another script

@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls

:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit

:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

How to make tesseract to recognize only numbers, when they are mixed with letters?

Recognizing only numbers is actually answered on the tesseract FAQ page. See that page for more info, but if you have the version 3 package, the config files are already set up. You just specify on the commandline:

tesseract image.tif outputbase nobatch digits

As for the threshold value, I'm not sure which you mean. If your input is an unusual font, perhaps you might retrain with a sample of your input. An alternative is to change tesseract's pruning threshold. Both options are also mentioned in the FAQ.

Is key-value pair available in Typescript?

TypeScript has Map. You can use like:

public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);

myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I've seen it suggested docker may be at its maximum of created networks. The command docker network prune can be used to remove all networks not used by at least one container.

My issue ended up being, as Robert commented about: an issue with openvpn service openvpn stop 'solved' the problem.

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

How to specify legend position in matplotlib in graph coordinates

According to the matplotlib legend documentation:

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

Thus, one could use:

plt.legend(loc=(x, y))

to set the legend's lower left corner to the specified (x, y) position.

VB.NET Switch Statement GoTo Case

Why not just do it like this:

Select Case parameter     
   Case "userID"                
      ' does something here.        
   Case "packageID"                
      ' does something here.        
   Case "mvrType"                 
      If otherFactor Then                         
         ' does something here.                 
      Else                         
         ' do processing originally part of GoTo here
         Exit Select  
      End If      
End Select

I'm not sure if not having a case else at the end is a big deal or not, but it seems like you don't really need the go to if you just put it in the else statement of your if.