Programs & Examples On #Back

Method or control to return user to previous state, page or screen.

How to go back (ctrl+z) in vi/vim

I had the same problem right now and i solved it. You must not need it anymore so I write for others:

if you use gvim on windows, you just add this in your _vimrc: $VIMRUNTIME/mswin.vim behave mswin

else just use imap...

Fragment pressing back button

Solution for Pressing or handling back button in Fragment.

The way I solved my issue I am sure it will helps you too:

1.If you don't have any Edit Text-box in your fragment you can use below code

Here MainHomeFragment is main Fragment (When I press back button from second fragment it will take me too MainHomeFragment)

    @Override
    public void onResume() {

    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;    
            }    
            return false;
        }
    }); }

2.If you have another fragment named as Somefragment and it has Edit text-box then you can do it by this way.

private EditText editText;

Then In,

onCreateView():    
editText = (EditText) view.findViewById(R.id.editText);

Then Override OnResume,

@Override
public void onResume() {
    super.onResume();

    editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                editTextOFS.clearFocus();
                getView().requestFocus();
            }
            return false;
        }
    });

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;

            }

            return false;
        }
    });

}

That's all folks (amitamie.com) :-) ;-)

How to Detect Browser Back Button event - Cross Browser

 <input style="display:none" id="__pageLoaded" value=""/>


 $(document).ready(function () {
        if ($("#__pageLoaded").val() != 1) {

            $("#__pageLoaded").val(1);


        } else {
            shared.isBackLoad = true;
            $("#__pageLoaded").val(1);  

            // Call any function that handles your back event

        }
    });

The above code worked for me. On mobile browsers, when the user clicked on the back button, we wanted to restore the page state as per his previous visit.

How to prevent going back to the previous activity?

Put

finish();

immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add

onCreate(){
    getActionBar().setDisplayHomeAsUpEnabled(false);
    ...
}

to the activity you are starting.

Android: Cancel Async Task

I spent a while figuring this out, all I wanted was a simple example of how to do it, so I thought I'd post how I did it. This is some code that updates a library and has a progress dialog showing how many books have been updated and cancels when a user dismisses the dialog:

private class UpdateLibrary extends AsyncTask<Void, Integer, Boolean>{
    private ProgressDialog dialog = new ProgressDialog(Library.this);
    private int total = Library.instance.appState.getAvailableText().length;
    private int count = 0;

    //Used as handler to cancel task if back button is pressed
    private AsyncTask<Void, Integer, Boolean> updateTask = null;

    @Override
    protected void onPreExecute(){
        updateTask = this;
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setOnDismissListener(new OnDismissListener() {               
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTask.cancel(true);
            }
        });
        dialog.setMessage("Updating Library...");
        dialog.setMax(total);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
            for (int i = 0; i < appState.getAvailableText().length;i++){
                if(isCancelled()){
                    break;
                }
                //Do your updating stuff here
            }
        }

    @Override
    protected void onProgressUpdate(Integer... progress){
        count += progress[0];
        dialog.setProgress(count);
    }

    @Override
    protected void onPostExecute(Boolean finished){
        dialog.dismiss();
        if (finished)
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY, Str.TEXT_UPDATECOMPLETED, Library.instance);
        else 
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY,Str.TEXT_NOUPDATE , Library.instance);
    }
}

Override back button to act like home button

Even better, how about OnPause():

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().

When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure toenter code here not do anything lengthy here.

This callback is mostly used for saving any persistent state the activity is editing and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one.

This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.

back button callback in navigationController in iOS

Here's another way I implemented (didn't test it with an unwind segue but it probably wouldn't differentiate, as others have stated in regards to other solutions on this page) to have the parent view controller perform actions before the child VC it pushed gets popped off the view stack (I used this a couple levels down from the original UINavigationController). This could also be used to perform actions before the childVC gets pushed, too. This has the added advantage of working with the iOS system back button, instead of having to create a custom UIBarButtonItem or UIButton.

  1. Have your parent VC adopt the UINavigationControllerDelegate protocol and register for delegate messages:

    MyParentViewController : UIViewController <UINavigationControllerDelegate>
    
    -(void)viewDidLoad {
        self.navigationcontroller.delegate = self;
    }
    
  2. Implement this UINavigationControllerDelegate instance method in MyParentViewController:

    - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
        // Test if operation is a pop; can also test for a push (i.e., do something before the ChildVC is pushed
        if (operation == UINavigationControllerOperationPop) {
            // Make sure it's the child class you're looking for
            if ([fromVC isKindOfClass:[ChildViewController class]]) {
                // Can handle logic here or send to another method; can also access all properties of child VC at this time
                return [self didPressBackButtonOnChildViewControllerVC:fromVC];
            }
        }
        // If you don't want to specify a nav controller transition
        return nil;
    }
    
  3. If you specify a specific callback function in the above UINavigationControllerDelegate instance method

    -(id <UIViewControllerAnimatedTransitioning>)didPressBackButtonOnAddSearchRegionsVC:(UIViewController *)fromVC {
        ChildViewController *childVC = ChildViewController.new;
        childVC = (ChildViewController *)fromVC;
    
        // childVC.propertiesIWantToAccess go here
    
        // If you don't want to specify a nav controller transition
        return nil;
    

    }

How do I kill an Activity when the Back button is pressed?

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}

My app closed with above code.

Back to previous page with header( "Location: " ); in PHP

Storing previous url in a session variable is bad, because the user might right click on multiple pages and then come back and save.

unless you save the previous url in the session variable to a hidden field in the form and after save header( "Location: save URL of calling page" );

How to run html file on localhost?

You can install Xampp and run apache serve and place your file to www folder and access your file at localhost/{file name} or simply at localhost if your file is named index.html

How to provide animation when calling another activity in Android?

Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.

How to rename a class and its corresponding file in Eclipse?

Shift + Alt + r (Right click file -> Refactor -> Rename) when cursor is on class name. The file and constructors will be also changed.

How to set placeholder value using CSS?

AFAIK, you can't do it with CSS alone. CSS has content rule but even that can be used to insert content before or after an element using pseudo selectors. You need to resort to javascript for that OR use placeholder attribute if you are using HTML5 as pointed out by @Blender.

how can I display tooltip or item information on mouse over?

Use the title attribute while alt is important for SEO stuff.

How can I compare strings in C using a `switch` statement?

Assuming little endianness and sizeof(char) == 1, you could do that (something like this was suggested by MikeBrom).

char* txt = "B1";
int tst = *(int*)txt;
if ((tst & 0x00FFFFFF) == '1B')
    printf("B1!\n");

It could be generalized for BE case.

How To Check If A Key in **kwargs Exists?

One way is to add it by yourself! How? By merging kwargs with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:

import sys

def myfunc(**kwargs):
    args = {'country':'England','town':'London',
            'currency':'Pound', 'language':'English'}

    diff = set(kwargs.keys()) - set(args.keys())
    if diff:
        print("Invalid args:",tuple(diff),file=sys.stderr)
        return

    args.update(kwargs)            
    print(args)

The defaults are set in the dictionary args, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args as our argument dictionary and have no further need of kwargs.

jquery fill dropdown with json data

Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/ URL. Upon success, it removes all items from dropdown list with id = OfferTransModel_ItemID and then it fills it with new items based on AJAX call's result:

if (productgrpid != 0) {    
    $.ajax({
        type: "POST",
        url: "/Ajax/_AjaxGetItemListHelp/",
        data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
        contentType: "application/json",              
        dataType: "json",
        success: function (data) {
            $("#OfferTransModel_ItemID").empty();

            $.each(data, function () {
                $("#OfferTransModel_ItemID").append($("<option>                                                      
                </option>").val(this['ITEMID']).html(this['ITEMDESC']));
            });
        }
    });
}

Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID and ITEMDESC elements. For example:

{
    {
        "ITEMID":"13",
        "ITEMDESC":"About"
    },
    {
        "ITEMID":"21",
        "ITEMDESC":"Contact"
    }
}

The OfferTransModel_ItemID listbox is populated with above data and its code should look like:

<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
    <option value="13">About</option>
    <option value="21">Contact</option>
</select>

When user selects About, form submits 13 as value for this field and 21 when user selects Contact and so on.

Fell free to modify above code if your server returns URL in a different format.

stringstream, string, and char* conversion confusion

What you're doing is creating a temporary. That temporary exists in a scope determined by the compiler, such that it's long enough to satisfy the requirements of where it's going.

As soon as the statement const char* cstr2 = ss.str().c_str(); is complete, the compiler sees no reason to keep the temporary string around, and it's destroyed, and thus your const char * is pointing to free'd memory.

Your statement string str(ss.str()); means that the temporary is used in the constructor for the string variable str that you've put on the local stack, and that stays around as long as you'd expect: until the end of the block, or function you've written. Therefore the const char * within is still good memory when you try the cout.

Find unused npm packages in package.json

You can use an npm module called depcheck (requires at least version 10 of Node).

  1. Install the module:

     npm install depcheck -g
    
     or
    
     yarn global add depcheck
    
  2. Run it and find the unused dependencies:

     depcheck
    

The good thing about this approach is that you don't have to remember the find or grep command.

To run without installing use npx:

npx depcheck 

How to check if any Checkbox is checked in Angular

Try to think in terms of a model and what happens to that model when a checkbox is checked.

Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:

<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />

and in the controller:

$scope.fooSelected = false;
$scope.baaSelected = false;

The next button should only be available under certain circumstances so add the ng-disabled directive to the button:

<button type='button' ng-disabled='nextButtonDisabled'></button>

Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:

$scope.$watch('[fooSelected,baaSelected]', function(){
    $scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );

The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.

Print all key/value pairs in a Java ConcurrentHashMap

  //best and simple way to show keys and values

    //initialize map
    Map<Integer, String> map = new HashMap<Integer, String>();

   //Add some values
    map.put(1, "Hi");
    map.put(2, "Hello");

    // iterate map using entryset in for loop
    for(Entry<Integer, String> entry : map.entrySet())
    {   //print keys and values
         System.out.println(entry.getKey() + " : " +entry.getValue());
    }

   //Result : 
    1 : Hi
    2 : Hello

How to sort alphabetically while ignoring case sensitive?

Since Java 8 you can sort using the Streams API:

List<String> fruits = Arrays.asList("apple", "Apricot", "banana");

List<String> sortedFruit = fruits.stream()
      .sorted(String.CASE_INSENSITIVE_ORDER)
      .collect(Collectors.toList())

The difference with Collections.sort is that this will return a new list and will not modify the existing one.

How do I set specific environment variables when debugging in Visual Studio?

Set up a batch file which you can invoke. Pass the path the batch file, and have the batch file set the environment variable and then invoke NUnit.

How do I specify local .gem files in my Gemfile?

I found it easiest to run my own gem server using geminabox

See these simple instructions.

Preventing form resubmission

Try tris:

function prevent_multi_submit($excl = "validator") {
    $string = "";
    foreach ($_POST as $key => $val) {
    // this test is to exclude a single variable, f.e. a captcha value
    if ($key != $excl) {
        $string .= $key . $val;
    }
    }
    if (isset($_SESSION['last'])) {
    if ($_SESSION['last'] === md5($string)) {
        return false;
    } else {
        $_SESSION['last'] = md5($string);
        return true;
    }
    } else {
    $_SESSION['last'] = md5($string);
    return true;
    }
}

How to use / example:

if (isset($_POST)) {
    if ($_POST['field'] != "") { // place here the form validation and other controls
    if (prevent_multi_submit()) { // use the function before you call the database or etc
        mysql_query("INSERT INTO table..."); // or send a mail like...
        mail($mailto, $sub, $body); // etc
    } else {
        echo "The form is already processed";
    }
    } else {
    // your error about invalid fields
    }
}

Font: https://www.tutdepot.com/prevent-multiple-form-submission/

Is there a php echo/print equivalent in javascript

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

How to get a pixel's x,y coordinate color from an image?

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

How to use onBlur event on Angular2?

This is the proposed answer on the Github repo:

// example without validators
const c = new FormControl('', { updateOn: 'blur' });

// example with validators
const c= new FormControl('', {
   validators: Validators.required,
   updateOn: 'blur'
});

Github : feat(forms): add updateOn blur option to FormControls

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

You need either

  • A unique index on Title in BookTitle
  • An ISBN column in BookCopy and the FK is on both columns

A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.

How do I redirect in expressjs while passing some context?

The easiest way I have found to pass data between routeHandlers to use next() no need to mess with redirect or sessions. Optionally you could just call your homeCtrl(req,res) instead of next() and just pass the req and res

var express  = require('express');
var jade     = require('jade');
var http     = require("http");


var app    = express();
var server = http.createServer(app);

/////////////
// Routing //
/////////////

// Move route middleware into named
// functions
function homeCtrl(req, res) {

    // Prepare the context
    var context = req.dataProcessed;
    res.render('home.jade', context);
}

function categoryCtrl(req, res, next) {

    // Process the data received in req.body
    // instead of res.redirect('/');
    req.dataProcessed = somethingYouDid;
    return next();
    // optionally - Same effect
    // accept no need to define homeCtrl
    // as the last piece of middleware
    // return homeCtrl(req, res, next);
}

app.get('/', homeCtrl);

app.post('/category', categoryCtrl, homeCtrl);

Using BeautifulSoup to search HTML for string

The following line is looking for the exact NavigableString 'Python':

>>> soup.body.findAll(text='Python')
[]

Note that the following NavigableString is found:

>>> soup.body.findAll(text='Python Jobs') 
[u'Python Jobs']

Note this behaviour:

>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]

So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.

How can I know if Object is String type object?

From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof

Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.

Before Java 14

if (obj instanceof String) {
    String str = (String) obj; // need to declare and cast again the object
    .. str.contains(..) ..
}else{
     str = ....
}

Java 14 enhancements

if (!(obj instanceof String str)) {
    .. str.contains(..) .. // no need to declare str object again with casting
} else {
    .. str....
}

We can also combine the type check and other conditions together

if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}

The use of pattern matching in instanceof should reduce the overall number of explicit casts in Java programs.

PS: instanceOf will only match when the object is not null, then only it can be assigned to str.

Get first key in a (possibly) associative array?

To enhance on the solution of Webmut, I've added the following solution:

$firstKey = array_keys(array_slice($array, 0, 1, TRUE))[0];

The output for me on PHP 7.1 is:

foreach to get first key and value: 0.048566102981567 seconds 
reset+key to get first key and value: 0.11727809906006 seconds 
reset+key to get first key: 0.11707186698914 seconds 
array_keys to get first key: 0.53917098045349 seconds 
array_slice to get first key: 0.2494580745697 seconds 

If I do this for an array of size 10000, then the results become

foreach to get first key and value: 0.048488140106201 seconds 
reset+key to get first key and value: 0.12659382820129 seconds 
reset+key to get first key: 0.12248802185059 seconds 
array_slice to get first key: 0.25442600250244 seconds 

The array_keys method times out at 30 seconds (with only 1000 elements, the timing for the rest was about the same, but the array_keys method had about 7.5 seconds).

Can promises have multiple arguments to onFulfilled?

You can use E6 destructuring:

Object destructuring:

promise = new Promise(function(onFulfilled, onRejected){
    onFulfilled({arg1: value1, arg2: value2});
})

promise.then(({arg1, arg2}) => {
    // ....
});

Array destructuring:

promise = new Promise(function(onFulfilled, onRejected){
    onFulfilled([value1, value2]);
})

promise.then(([arg1, arg2]) => {
    // ....
});

How to change a package name in Eclipse?

Create your directory structure in src folder like

.

means to create subpkg1 folder under pkg1 folder (source folder in eclipse) then place your source code inside and then modify its package declaration.

Mocking static methods with Mockito

For those who use JUnit 5, Powermock is not an option. You'll require the following dependencies to successfully mock a static method with just Mockito.

testCompile    group: 'org.mockito', name: 'mockito-core',           version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-junit-jupiter',  version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-inline',         version: '3.6.0'

mockito-junit-jupiter add supports for JUnit 5.

And support for mocking static methods is provided by mockito-inline dependency.

Example:

@Test
void returnUtilTest() {
    assertEquals("foo", UtilClass.staticMethod("foo"));

    try (MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)) {

        classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");

        assertEquals("bar", UtilClass.staticMethod("foo"));
     }

     assertEquals("foo", UtilClass.staticMethod("foo"));
}

The try-with-resource block is used to make the static mock remains temporary, so it's mocked only within that scope.

When not using a try block, make sure to close the scoped mock, once you are done with the assertions.

MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)
classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");
assertEquals("bar", UtilClass.staticMethod("foo"));
classMock.close();

Mocking void methods:

When mockStatic is called on a class, all the static void methods in that class automatically get mocked to doNothing().

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

Table Naming Dilemma: Singular vs. Plural Names

I stick with singular for table names and any programming entity.

The reason? The fact that there are irregular plurals in English like mouse ? mice and sheep ? sheep. Then, if I need a collection, i just use mouses or sheeps, and move on.

It really helps the plurality stand out, and I can easily and programatically determine what the collection of things would look like.

So, my rule is: everything is singular, every collection of things is singular with an s appended. Helps with ORMs too.

How do I limit the number of returned items?

models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
 // `posts` with sorted length of 20
});

How can I disable notices and warnings in PHP within the .htaccess file?

Fortes is right, thank you.

When you have a shared hosting it is usual to obtain an 500 server error.

I have a website with Joomla and I added to the index.php:

ini_set('display_errors','off');

The error line showed in my website disappeared.

cleanest way to skip a foreach if array is empty

I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.

All other solutions are quite dirty hacks to me.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

I was facing the same issue and with some hint from @tadtab 's answer, I was able to figure out a solution for the same problem in my project.

Steps:

1->Follow the steps mentioned in @tadtab's answers.

2->Right Click on the project->Click on Properties->Search for Deployment Assembly.

3->Search whether your folder exists on the screen. (If not, add it).

4->On the screen you will find a 'Deploy Path' column corresponding to your source folder. Copy that path. In my case, it was /views.

enter image description here 5->So basically, in the setPrefix() method, we should have the path at the time of deployment. Earlier I was just using /views in the setPrefix() method, so I was getting the same error. But after, it worked well.

@Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/classes/");
        resolver.setSuffix(".jsp");

        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;

    }

The same should be applicable to XML configuration also.

How to make the HTML link activated by clicking on the <li>?

Or you can create an empty link at the end of your <li>:

<a href="link"></a>

.menu li{position:relative;padding:0;}
.link{
     bottom: 0;
     left: 0;
     position: absolute;
     right: 0;
     top: 0;
}

This will create a full clickable <li> and keep your formatting on your real link. It could be useful for <div> tag as well

Getting the IP Address of a Remote Socket Endpoint

RemoteEndPoint is a property, its type is System.Net.EndPoint which inherits from System.Net.IPEndPoint.

If you take a look at IPEndPoint's members, you'll see that there's an Address property.

Why can't variables be declared in a switch statement?

The whole switch statement is in the same scope. To get around it, do this:

switch (val)
{
    case VAL:
    {
        // This **will** work
        int newVal = 42;
    }
    break;

    case ANOTHER_VAL:
      ...
    break;
}

Note the brackets.

How to test if string exists in file with Bash?

The @Thomas's solution didn't work for me for some reason but I had longer string with special characters and whitespaces so I just changed the parameters like this:

if grep -Fxq 'string you want to find' "/path/to/file"; then
    echo "Found"
else
    echo "Not found"
fi

Hope it helps someone

see if two files have the same content in python

I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

  • Compare file sizes first, discarding all which doesn't match
  • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

No mapping found for HTTP request with URI.... in DispatcherServlet with name

If you are using Java code based on Spring MVC configuration then enable the DefaultServletHandlerConfigurer in the WebMvcConfigurerAdapter object.

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
        configurer.enable();
}

How to put a jar in classpath in Eclipse?

As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs on the same level as your src and assets directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.

How to create a release signed apk file using Gradle?

I had several issues that I put the following line in a wrong place:

signingConfigs {
    release {
        // We can leave these in environment variables
        storeFile file("d:\\Fejlesztés\\******.keystore")
        keyAlias "mykey"

        // These two lines make gradle believe that the signingConfigs
        // section is complete. Without them, tasks like installRelease
        // will not be available!
        storePassword "*****"
        keyPassword "******"
    }
}

Make sure that you put the signingConfigs parts inside the android section:

android
{
    ....
    signingConfigs {
        release {
          ...
        }
    }
}

instead of

android
{
    ....
}

signingConfigs {
   release {
        ...
   }
}

It is easy to make this mistake.

How to add number of days to today's date?

The prototype-solution from Krishna Chytanya is very nice, but needs a minor but important improvement. The days param must be parsed as Integer to avoid weird calculations when days is a String like "1". (I needed several hours to find out, what went wrong in my application.)

Date.prototype.addDays = function(days) {
    this.setDate(this.getDate() + parseInt(days));
    return this;
};

Even if you do not use this prototype function: Always be sure to have an Integer when using setDate().

How to enable bulk permission in SQL Server

Note that the accepted answer or either of these two solutions work for Windows only.

GRANT ADMINISTER BULK OPERATIONS TO [login_name];
-- OR
ALTER SERVER ROLE [bulkadmin] ADD MEMBER [login_name];

If you run any of them on SQL Server based on a linux machine, you will get these errors:

Msg 16202, Level 15, State 1, Line 1
Keyword or statement option 'bulkadmin' is not supported on the 'Linux' platform.
Msg 16202, Level 15, State 3, Line 1
Keyword or statement option 'ADMINISTER BULK OPERATIONS' is not supported on the 'Linux' platform.

Check the docs.

Requires INSERT and ADMINISTER BULK OPERATIONS permissions. In Azure SQL Database, INSERT and ADMINISTER DATABASE BULK OPERATIONS permissions are required. ADMINISTER BULK OPERATIONS permissions or the bulkadmin role is not supported for SQL Server on Linux. Only the sysadmin can perform bulk inserts for SQL Server on Linux.

Solution for Linux

ALTER SERVER ROLE [sysadmin] ADD MEMBER [login_name];

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

My app was an ASP.Net3.5 app (using version 2 of the framework). When ASP.Net3.5 apps got created Visual Studio automatically added scriptResourceHandler to the web.config. Later versions of .Net put this into the machine.config. If you run your ASP.Net 3.5 app using the version 4 app pool (depending on install order this is the default app pool), you will get this error.

When I moved to using the version 2.0 app pool. The error went away. I then had to deal with the error when serving WCF .svc :

HTTP Error 404.17 - Not Found The requested content appears to be script and will not be served by the static file handler

After some investigation, it seems that I needed to register the WCF handler. using the following steps:

  1. open Visual Studio Command Prompt (as administrator)
  2. navigate to "C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation"
  3. Run servicemodelreg -i

Which JRE am I using?

Git Bash + Windows 10 + Software that came bundled with its own JRE copy:

Do a "Git Bash Here" in the jre/bin folder of the software you installed.

Then use "./java.exe -version" instead of "java -version" to get the information on the software's copy rather than the copy referenced by your PATH environment variable.

Get the version of the software installation: ./java.exe -version

JMIM@DESKTOP-JUDCNDL MINGW64 /c/DEV/PROG/EYE_DB/INST/jre/bin
$ ./java.exe -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Get the version in your PATH variable: java -version

JMIM@DESKTOP-JUDCNDL MINGW64 /c/DEV/PROG/EYE_DB/INST/jre/bin
$ java -version
java version "10" 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)

As for addressing the original question and getting vendor information:

./java.exe -XshowSettings:properties -version ## Software's copy
java       -XshowSettings:properties -version ## Copy in PATH

Pass data from Activity to Service using an Intent

First Context (can be Activity/Service etc)

For Service, you need to override onStartCommand there you have direct access to intent:

Override
public int onStartCommand(Intent intent, int flags, int startId) {

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

New Context (can be Activity/Service etc)

Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
     String value = myIntent.getExtras().getString(key);
}

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

My solution will work if you apply the ActionFilter to the Subcategory action method, as long as you always want to redirect the user to the same bookmark:

http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html

It modifies the HTML buffer and outputs a small piece of javascript to instruct the browser to append the bookmark.

You could modify the javascript to manually scroll, instead of using a bookmark in the URL, of course!

Hope it helps :)

Git merge master into feature branch

You should be able to rebase your branch on master:

git checkout feature1
git rebase master

Manage all conflicts that arise. When you get to the commits with the bugfixes (already in master), Git will say that there were no changes and that maybe they were already applied. You then continue the rebase (while skipping the commits already in master) with

git rebase --skip

If you perform a git log on your feature branch, you'll see the bugfix commit appear only once, and in the master portion.

For a more detailed discussion, take a look at the Git book documentation on git rebase (https://git-scm.com/docs/git-rebase) which cover this exact use case.

================ Edit for additional context ====================

This answer was provided specifically for the question asked by @theomega, taking his particular situation into account. Note this part:

I want to prevent [...] commits on my feature branch which have no relation to the feature implementation.

Rebasing his private branch on master is exactly what will yield that result. In contrast, merging master into his branch would precisely do what he specifically does not want to happen: adding a commit that is not related to the feature implementation he is working on via his branch.

To address the users that read the question title, skip over the actual content and context of the question, and then only read the top answer blindly assuming it will always apply to their (different) use case, allow me to elaborate:

  • only rebase private branches (i.e. that only exist in your local repository and haven't been shared with others). Rebasing shared branches would "break" the copies other people may have.
  • if you want to integrate changes from a branch (whether it's master or another branch) into a branch that is public (e.g. you've pushed the branch to open a pull request, but there are now conflicts with master, and you need to update your branch to resolve those conflicts) you'll need to merge them in (e.g. with git merge master as in @Sven's answer).
  • you can also merge branches into your local private branches if that's your preference, but be aware that it will result in "foreign" commits in your branch.

Finally, if you're unhappy with the fact that this answer is not the best fit for your situation even though it was for @theomega, adding a comment below won't be particularly helpful: I don't control which answer is selected, only @theomega does.

SQL split values to multiple rows

If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  numbers inner join tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

Please see fiddle here.

If you cannot create a table, then a solution can be this:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

an example fiddle is here.

Maximum filename length in NTFS (Windows XP and Windows Vista)?

Actually it is 256, see File System Functionality Comparison, Limits.

To repeat a post on http://fixunix.com/microsoft-windows/30758-windows-xp-file-name-length-limit.html

"Assuming we're talking about NTFS and not FAT32, the "255 characters for path+file" is a limitation of Explorer, not the filesystem itself. NTFS supports paths up to 32,000 Unicode characters long, with each component up to 255 characters.

Explorer -and the Windows API- limits you to 260 characters for the path, which include drive letter, colon, separating slashes and a terminating null character. It's possible to read a longer path in Windows if you start it with a \\"

If you read the above posts you'll see there is a 5th thing you can be certain of: Finding at least one obstinate computer user!

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

How do I read from parameters.yml in a controller in symfony2?

You can use:

public function indexAction()
{
   dump( $this->getParameter('api_user'));
}

For more information I recommend you read the doc :

http://symfony.com/doc/2.8/service_container/parameters.html

jQuery checkbox event handling

$('#myform :checkbox').change(function() {
    // this will contain a reference to the checkbox   
    if (this.checked) {
        // the checkbox is now checked 
    } else {
        // the checkbox is now no longer checked
    }
});

Is there an equivalent method to C's scanf in Java?

If one really wanted to they could make there own version of scanf() like so:

    import java.util.ArrayList;
    import java.util.Scanner;

public class Testies {

public static void main(String[] args) {
    ArrayList<Integer> nums = new ArrayList<Integer>();
    ArrayList<String> strings = new ArrayList<String>();

    // get input
    System.out.println("Give me input:");
    scanf(strings, nums);

    System.out.println("Ints gathered:");
    // print numbers scanned in
    for(Integer num : nums){
        System.out.print(num + " ");
    }
    System.out.println("\nStrings gathered:");
    // print strings scanned in
    for(String str : strings){
        System.out.print(str + " ");
    }

    System.out.println("\nData:");
    for(int i=0; i<strings.size(); i++){
        System.out.println(nums.get(i) + " " + strings.get(i));
    }
}

// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner getLine = new Scanner(System.in);
    Scanner input = new Scanner(getLine.nextLine());

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner input = (new Scanner(in));

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}


}

Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.

Output:

Give me input: apples 8 9 pears oranges 5 Ints gathered: 8 9 5 Strings gathered: apples pears oranges Data: 8 apples 9 pears 5 oranges

Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.

Keras model.summary() result - Understanding the # of Parameters

The "none" in the shape means it does not have a pre-defined number. For example, it can be the batch size you use during training, and you want to make it flexible by not assigning any value to it so that you can change your batch size. The model will infer the shape from the context of the layers.

To get nodes connected to each layer, you can do the following:

for layer in model.layers:
    print(layer.name, layer.inbound_nodes, layer.outbound_nodes)

How to put a Scanner input into an array... for example a couple of numbers

import  java.util.Scanner;

class Array {
public static void main(String a[]){

    Scanner input = new Scanner(System.in);

    System.out.println("Enter the size of an Array");

    int num = input.nextInt();

    System.out.println("Enter the Element "+num+" of an Array");

    double[] numbers = new double[num];

    for (int i = 0; i < numbers.length; i++)
    {

        System.out.println("Please enter number");

        numbers[i] = input.nextDouble();

    }

    for (int i = 0; i < numbers.length; i++)
    {

        if ( (i%3) !=0){

            System.out.print("");

            System.out.print(numbers[i]+"\t");

        } else {
            System.out.println("");

            System.out.print(numbers[i]+"\t");
        }

    }

}

os.walk without digging into directories below

for path, dirs, files in os.walk('.'):
    print path, dirs, files
    del dirs[:] # go only one level deep

How can I parse a CSV string with JavaScript, which contains comma in data?

No regexp, readable, and according to https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules:

function csv2arr(str: string) {
    let line = ["",];
    const ret = [line,];
    let quote = false;

    for (let i = 0; i < str.length; i++) {
        const cur = str[i];
        const next = str[i + 1];

        if (!quote) {
            const cellIsEmpty = line[line.length - 1].length === 0;
            if (cur === '"' && cellIsEmpty) quote = true;
            else if (cur === ",") line.push("");
            else if (cur === "\r" && next === "\n") { line = ["",]; ret.push(line); i++; }
            else if (cur === "\n" || cur === "\r") { line = ["",]; ret.push(line); }
            else line[line.length - 1] += cur;
        } else {
            if (cur === '"' && next === '"') { line[line.length - 1] += cur; i++; }
            else if (cur === '"') quote = false;
            else line[line.length - 1] += cur;
        }
    }
    return ret;
}

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

There is problem in name spacing as in laravel 5.2.3

use DB;
use App\ApiModel; OR  use App\name of model; 

DB::table('tbl_users')->insert($users); 

OR

DB::table('table name')->insert($users);



model 

class ApiModel extends Model
    {

        protected $table='tbl_users';

}

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

It looks like whichever program or process you're trying to initialize either isn't installed on your machine, has a damaged installation or needs to be registered.

Either install it, repair it (via Add/Remove Programs) or register it (via Regsvr32.exe).

You haven't provided enough information for us to help you any more than this.

How to set the component size with GridLayout? Is there a better way?

For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.

Angular ng-if not true

Just use for True:

<li ng-if="area"></li>

and for False:

<li ng-if="area === false"></li>

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

Find and extract a number from a string

  string verificationCode ="dmdsnjds5344gfgk65585";
            string code = "";
            Regex r1 = new Regex("\\d+");
          Match m1 = r1.Match(verificationCode);
           while (m1.Success)
            {
                code += m1.Value;
                m1 = m1.NextMatch();
            }

How to get row index number in R?

If i understand your question, you just want to be able to access items in a data frame (or list) by row:

x = matrix( ceiling(9*runif(20)), nrow=5  )   
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x)      # create a small data frame

df[1,]                  # get the first row
df[3,]                  # get the third row
df[nrow(df),]           # get the last row

lf = as.list(df)        

lf[[1]]                 # get first row
lf[[3]]                 # get third row

etc.

How can I declare a global variable in Angular 2 / Typescript?

A shared service is the best approach

export class SharedService {
  globalVar:string;
}

But you need to be very careful when registering it to be able to share a single instance for whole your application. You need to define it when registering your application:

bootstrap(AppComponent, [SharedService]);

But not to define it again within the providers attributes of your components:

@Component({
  (...)
  providers: [ SharedService ], // No
  (...)
})

Otherwise a new instance of your service will be created for the component and its sub-components.

You can have a look at this question regarding how dependency injection and hierarchical injectors work in Angular 2:

You should notice that you can also define Observable properties in the service to notify parts of your application when your global properties change:

export class SharedService {
  globalVar:string;
  globalVarUpdate:Observable<string>;
  globalVarObserver:Observer;

  constructor() {
    this.globalVarUpdate = Observable.create((observer:Observer) => {
      this.globalVarObserver = observer;
    });
  }

  updateGlobalVar(newValue:string) {
    this.globalVar = newValue;
    this.globalVarObserver.next(this.globalVar);
  }
}

See this question for more details:

How to get access token from FB.login method in javascript SDK

If you are already connected, simply type this in the javascript console:

FB.getAuthResponse()['accessToken']

How to identify server IP address in PHP

The previous answers all give $_SERVER['SERVER_ADDR']. This will not work on some IIS installations. If you want this to work on IIS, then use the following:

$server_ip = gethostbyname($_SERVER['SERVER_NAME']);

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

Ran into this in prezto another zsh variant. There the issue was my git repo was new and did not have the node_modules added to .gitignore. As soon as I added the node_modules to .gitignore the issue was no more to be seen. So my assumption is git-info was taking time due to these large node_modules.

Serialize object to query string in JavaScript/jQuery

For a quick non-JQuery function...

function jsonToQueryString(json) {
    return '?' + 
        Object.keys(json).map(function(key) {
            return encodeURIComponent(key) + '=' +
                encodeURIComponent(json[key]);
        }).join('&');
}

Note this doesn't handle arrays or nested objects.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

Error: The 'brew link' step did not complete successfully

I also managed to mess up my NPM and installed packages between these Homebrew versions and no matter how many time I unlinked / linked and uninstalled / installed node it still didn't work.

As it turns out you have to remove NPM from the path otherwise Homebrew won't install it: https://github.com/mxcl/homebrew/blob/master/Library/Formula/node.rb#L117

Hope this will help someone with the same problem and save that hour or so I had to spend looking for the problem...

Creating NSData from NSString in Swift

In Swift 3

let data = string.data(using: .utf8)

In Swift 2 (or if you already have a NSString instance)

let data = string.dataUsingEncoding(NSUTF8StringEncoding)

In Swift 1 (or if you have a swift String):

let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)

Also note that data is an Optional<NSData> (since the conversion might fail), so you'll need to unwrap it before using it, for instance:

if let d = data {
    println(d)
}

Defining TypeScript callback type

If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.

class CallbackTest {
  myCallback: Function;
}   

Python Key Error=0 - Can't find Dict error in code

The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

Protecting cells in Excel but allow these to be modified by VBA script

I don't think you can set any part of the sheet to be editable only by VBA, but you can do something that has basically the same effect -- you can unprotect the worksheet in VBA before you need to make changes:

wksht.Unprotect()

and re-protect it after you're done:

wksht.Protect()

Edit: Looks like this workaround may have solved Dheer's immediate problem, but for anyone who comes across this question/answer later, I was wrong about the first part of my answer, as Joe points out below. You can protect a sheet to be editable by VBA-only, but it appears the "UserInterfaceOnly" option can only be set when calling "Worksheet.Protect" in code.

How to update maven repository in Eclipse?

Sometimes the dependencies don't update even with Maven->Update Project->Force Update option checked using m2eclipse plugin.

In case it doesn't work for anyone else, this method worked for me:

  • mvn eclipse:eclipse

    This will update your .classpath file with the new dependencies while preserving your .project settings and other eclipse config files.

If you want to clear your old settings for whatever reason, you can run:

  • mvn eclipse:clean
  • mvn eclipse:eclipse

    mvn eclipse:clean will erase your old settings, then mvn eclipse:eclipse will create new .project, .classpath and other eclipse config files.

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

get everything between <tag> and </tag> with php

You can use the following:

$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
  • \b ensures that a typo (like <codeS>) is not captured.
  • The first pattern [^>]* captures the content of a tag with attributes (eg a class).
  • Finally, the flag s capture content with newlines.

See the result here : http://lumadis.be/regex/test_regex.php?id=1081

How do I copy to the clipboard in JavaScript?

This solution was found here. The document.execCommand("copy"); is not supported on Internet Explorer 8 and earlier.

_x000D_
_x000D_
const copyBtn =  document.getElementById("copyBtn");
const input = document.getElementById("input");

function copyText() {
  const value = input.value;
  
  input.select(); // selects the input variable as the text to be copied
  input.setSelectionRange(0, 99999); // this is used to set the selection range for mobile devices
  
  document.execCommand("copy"); // copies the selected text
  
  alert("Copied the text " + value); // displays the copied text in a prompt
}

copyBtn.onmousedown = function () {
  copyText();
}
_x000D_
<input type="text" id="input" placeholder="Type text to copy... "/>
<button id="copyBtn">
  Copy
</button>
_x000D_
_x000D_
_x000D_

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

How to check if memcache or memcached is installed for PHP?

Use this code to not only check if the memcache extension is enabled, but also whether the daemon is running and able to store and retrieve data successfully:

<?php
if (class_exists('Memcache')) {
    $server = 'localhost';
    if (!empty($_REQUEST['server'])) {
        $server = $_REQUEST['server'];
    }
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect($server);

    if ($isMemcacheAvailable) {
        $aData = $memcache->get('data');
        echo '<pre>';
        if ($aData) {
            echo '<h2>Data from Cache:</h2>';
            print_r($aData);
        } else {
            $aData = array(
                'me' => 'you',
                'us' => 'them',
            );
            echo '<h2>Fresh Data:</h2>';
            print_r($aData);
            $memcache->set('data', $aData, 0, 300);
        }
        $aData = $memcache->get('data');
        if ($aData) {
            echo '<h3>Memcache seem to be working fine!</h3>';
        } else {
            echo '<h3>Memcache DOES NOT seem to be working!</h3>';
        }
        echo '</pre>';
    }
}
if (!$isMemcacheAvailable) {
    echo 'Memcache not available';
}

?>

Set style for TextView programmatically

I do not believe you can set the style programatically. To get around this you can create a template layout xml file with the style assigned, for example in res/layout create tvtemplate.xml as with the following content:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is a template"
        style="@style/my_style" />

then inflate this to instantiate your new TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);

Hope this helps.

Difference between Running and Starting a Docker container

run command creates a container from the image and then starts the root process on this container. Running it with run --rm flag would save you the trouble of removing the useless dead container afterward and would allow you to ignore the existence of docker start and docker remove altogether.

enter image description here

run command does a few different things:

docker run --name dname image_name bash -c "whoami"
  1. Creates a Container from the image. At this point container would have an id, might have a name if one is given, will show up in docker ps
  2. Starts/executes the root process of the container. In the code above that would execute bash -c "whoami". If one runs docker run --name dname image_name without a command to execute container would go into stopped state immediately.
  3. Once the root process is finished, the container is stopped. At this point, it is pretty much useless. One can not execute anything anymore or resurrect the container. There are basically 2 ways out of stopped state: remove the container or create a checkpoint (i.e. an image) out of stopped container to run something else. One has to run docker remove before launching container under the same name.

How to remove container once it is stopped automatically? Add an --rm flag to run command:

docker run --rm --name dname image_name bash -c "whoami"

How to execute multiple commands in a single container? By preventing that root process from dying. This can be done by running some useless command at start with --detached flag and then using "execute" to run actual commands:

docker run --rm -d --name dname image_name tail -f /dev/null
docker exec dname bash -c "whoami"
docker exec dname bash -c "echo 'Nnice'"

Why do we need docker stop then? To stop this lingering container that we launched in the previous snippet with the endless command tail -f /dev/null.

Loading a .json file into c# program

Another good way to serialize json into c# is below:

RootObject ro = new RootObject();
     try
    {

        StreamReader sr = new StreamReader(FileLoc);
        string jsonString = sr.ReadToEnd();
        JavaScriptSerializer ser = new JavaScriptSerializer();
        ro = ser.Deserialize<RootObject>(jsonString);


   }

you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client

Why am I seeing "TypeError: string indices must be integers"?

data is a dict object. So, iterate over it like this:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

In SQL Server Enterprise Manager, open \Server Objects\Linked Servers\Providers, right click on the OraOLEDB.Oracle provider, select properties and check the "Allow inprocess" option. Recreate your linked server and test again.

You can also execute the following query if you don't have access to SQL Server Management Studio :

EXEC master.dbo.sp_MSset_oledb_prop N'OraOLEDB.Oracle', N'AllowInProcess', 1

Meaning of - <?xml version="1.0" encoding="utf-8"?>

This is the XML optional preamble.

  • version="1.0" means that this is the XML standard this file conforms to
  • encoding="utf-8" means that the file is encoded using the UTF-8 Unicode encoding

$(...).datepicker is not a function - JQuery - Bootstrap

Need to include jquery-ui too:

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Skip certain tables with mysqldump

I like Rubo77's solution, I hadn't seen it before I modified Paul's. This one will backup a single database, excluding any tables you don't want. It will then gzip it, and delete any files over 8 days old. I will probably use 2 versions of this that do a full (minus logs table) once a day, and another that just backs up the most important tables that change the most every hour using a couple cron jobs.

#!/bin/sh
PASSWORD=XXXX
HOST=127.0.0.1
USER=root
DATABASE=MyFavoriteDB

now="$(date +'%d_%m_%Y_%H_%M')"
filename="${DATABASE}_db_backup_$now"
backupfolder="/opt/backups/mysql"
DB_FILE="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt

EXCLUDED_TABLES=(
logs
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE}  > ${DB_FILE} 
echo "Dump structure finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
gzip ${DB_FILE}

find "$backupfolder" -name ${DATABASE}_db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0

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

Here are the READY TO USE METHODS:

To invoke a method, without Arguments:

public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    object.getClass().getDeclaredMethod(methodName).invoke(object);
}

To invoke a method, with Arguments:

    public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);
    }

Use the above methods as below:

package practice;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class MethodInvoke {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
        String methodName1 = "methodA";
        String methodName2 = "methodB";
        MethodInvoke object = new MethodInvoke();
        callMethodByName(object, methodName1);
        callMethodByName(object, methodName2, 1, "Test");
    }

    public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        object.getClass().getDeclaredMethod(methodName).invoke(object);
    }

    public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);
    }

    void methodA() {
        System.out.println("Method A");
    }

    void methodB(int i, String s) {
        System.out.println("Method B: "+"\n\tParam1 - "+i+"\n\tParam 2 - "+s);
    }
}

Output:

Method A  
Method B:  
	Param1 - 1  
	Param 2 - Test

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

Please incre max_iter to 10000 as default value is 1000. Possibly, increasing no. of iterations will help algorithm to converge. For me it converged and solver was -'lbfgs'

log_reg = LogisticRegression(solver='lbfgs',class_weight='balanced', max_iter=10000)

Scala: write string to file in one statement

Use ammonite ops library. The syntax is very minimal, but the breadth of the library is almost as wide as what one would expect from attempting such a task in a shell scripting language like bash.

On the page I linked to, it shows numerous operations one can do with the library, but to answer this question, this is an example of writing to a file

import ammonite.ops._
write(pwd/'"file.txt", "file contents")

Unable to copy ~/.ssh/id_rsa.pub

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub didn't work for me (ubuntu 14.04), but you can use :

cat ~/.ssh/id_rsa.pub

to get your public key

Writing a dict to txt file and reading it back?

Hi there is a way to write and read the dictionary to file you can turn your dictionary to JSON format and read and write quickly just do this :

To write your date:

 import json

 your_dictionary = {"some_date" : "date"}
 f = open('destFile.txt', 'w+')
 f.write(json.dumps(your_dictionary))

and to read your data:

 import json

 f = open('destFile.txt', 'r')
 your_dictionary = json.loads(f.read())

How are software license keys generated?

CD-Keys aren't much of a security for any non-networked stuff, so technically they don't need to be securely generated. If you're on .net, you can almost go with Guid.NewGuid().

Their main use nowadays is for the Multiplayer component, where a server can verify the CD Key. For that, it's unimportant how securely it was generated as it boils down to "Lookup whatever is passed in and check if someone else is already using it".

That being said, you may want to use an algorhithm to achieve two goals:

  • Have a checksum of some sort. That allows your Installer to display "Key doesn't seem valid" message, solely to detect typos (Adding such a check in the installer actually means that writing a Key Generator is trivial as the hacker has all the code he needs. Not having the check and solely relying on server-side validation disables that check, at the risk of annoying your legal customers who don't understand why the server doesn't accept their CD Key as they aren't aware of the typo)
  • Work with a limited subset of characters. Trying to type in a CD Key and guessing "Is this an 8 or a B? a 1 or an I? a Q or an O or a 0?" - by using a subset of non-ambigous chars/digits you eliminate that confusion.

That being said, you still want a large distribution and some randomness to avoid a pirate simply guessing a valid key (that's valid in your database but still in a box on a store shelf) and screwing over a legitimate customer who happens to buy that box.

qmake: could not find a Qt installation of ''

For my Qt 5.7, open QtCreator, go to Tools -> Options -> Build & Run -> Qt Versions gave me the location of qmake.

How to remove all of the data in a table using Django

As per the latest documentation, the correct method to call would be:

Reporter.objects.all().delete()

Python str vs unicode types

Your terminal happens to be configured to UTF-8.

The fact that printing a works is a coincidence; you are writing raw UTF-8 bytes to the terminal. a is a value of length two, containing two bytes, hex values C3 and A1, while ua is a unicode value of length one, containing a codepoint U+00E1.

This difference in length is one major reason to use Unicode values; you cannot easily measure the number of text characters in a byte string; the len() of a byte string tells you how many bytes were used, not how many characters were encoded.

You can see the difference when you encode the unicode value to different output encodings:

>>> a = 'á'
>>> ua = u'á'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> a
'\xc3\xa1'

Note that the first 256 codepoints of the Unicode standard match the Latin 1 standard, so the U+00E1 codepoint is encoded to Latin 1 as a byte with hex value E1.

Furthermore, Python uses escape codes in representations of unicode and byte strings alike, and low code points that are not printable ASCII are represented using \x.. escape values as well. This is why a Unicode string with a code point between 128 and 255 looks just like the Latin 1 encoding. If you have a unicode string with codepoints beyond U+00FF a different escape sequence, \u.... is used instead, with a four-digit hex value.

It looks like you don't yet fully understand what the difference is between Unicode and an encoding. Please do read the following articles before you continue:

Rubymine: How to make Git ignore .idea files created by Rubymine

In the rubymine gui, there is an ignore list (settings/version control). Maybe try disabling it there. I got the hint from their support guys.

enter image description here

How to check date of last change in stored procedure or function in SQL server

You can use this for check modify date of functions and stored procedures together ordered by date :

SELECT 'Stored procedure' as [Type] ,name, create_date, modify_date 
FROM sys.objects
WHERE type = 'P' 

UNION all

Select 'Function' as [Type],name, create_date, modify_date
FROM sys.objects
WHERE type = 'FN'
ORDER BY modify_date DESC

or :

SELECT type ,name, create_date, modify_date 
FROM sys.objects
WHERE type in('P','FN') 
ORDER BY modify_date DESC
-- this one shows type like : FN for function and P for stored procedure

Result will be like this :

Type                 |  name      | create_date              |  modify_date
'Stored procedure'   | 'firstSp'  | 2018-08-04 07:36:40.890  |  2019-09-05 05:18:53.157
'Stored procedure'   | 'secondSp' | 2017-10-15 19:39:27.950  |  2019-09-05 05:15:14.963
'Function'           | 'firstFn'  | 2019-09-05 05:08:53.707  |  2019-09-05 05:08:53.707

DIV height set as percentage of screen?

By using absolute positioning, you can make <body> or <form> or <div>, fit to your browser page. For example:

<body style="position: absolute; bottom: 0px; top: 0px; left: 0px; right: 0px;">

and then simply put a <div> inside it and use whatever percentage of either height or width you wish

<div id="divContainer" style="height: 100%;">

Javascript .querySelector find <div> by innerTEXT

OP's question is about plain JavaScript and not jQuery. Although there are plenty of answers and I like @Pawan Nogariya answer, please check this alternative out.

You can use XPATH in JavaScript. More info on the MDN article here.

The document.evaluate() method evaluates an XPATH query/expression. So you can pass XPATH expressions there, traverse into the HTML document and locate the desired element.

In XPATH you can select an element, by the text node like the following, whch gets the div that has the following text node.

//div[text()="Hello World"]

To get an element that contains some text use the following:

//div[contains(., 'Hello')]

The contains() method in XPATH takes a node as first parameter and the text to search for as second parameter.

Check this plunk here, this is an example use of XPATH in JavaScript

Here is a code snippet:

var headings = document.evaluate("//h1[contains(., 'Hello')]", document, null, XPathResult.ANY_TYPE, null );
var thisHeading = headings.iterateNext();

console.log(thisHeading); // Prints the html element in console
console.log(thisHeading.textContent); // prints the text content in console

thisHeading.innerHTML += "<br />Modified contents";  

As you can see, I can grab the HTML element and modify it as I like.

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

Relative URLs in WordPress

Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.

I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Styling the last td in a table with css

you could use the last-child psuedo class

table tr td:last-child {
    border: none;
}

This will style the last td only. It's not fully supported yet so it may be unsuitable

Generating UNIQUE Random Numbers within a range

You can try next code:

function unique_randoms($min, $max, $count) {

 $arr = array();
 while(count($arr) < $count){
      $tmp =mt_rand($min,$max);
      if(!in_array($tmp, $arr)){
         $arr[] = $tmp;
      }
 }
return $arr;
}

How can I do string interpolation in JavaScript?

Word of caution: avoid any template system which does't allow you to escape its own delimiters. For example, There would be no way to output the following using the supplant() method mentioned here.

"I am 3 years old thanks to my {age} variable."

Simple interpolation may work for small self-contained scripts, but often comes with this design flaw that will limit any serious use. I honestly prefer DOM templates, such as:

<div> I am <span id="age"></span> years old!</div>

And use jQuery manipulation: $('#age').text(3)

Alternately, if you are simply just tired of string concatenation, there's always alternate syntax:

var age = 3;
var str = ["I'm only", age, "years old"].join(" ");

Referring to a Column Alias in a WHERE Clause

For me, the simplest way to use ALIAS in WHERE class is to create a subquery and select from it instead.

Example:

WITH Q1 AS (
    SELECT LENGTH(name) AS name_length,
    id,
    name
    FROM any_table
)

SELECT id, name, name_length form Q1 where name_length > 0

Cheers, Kel

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Dto response = softConvertValue(jsonData, Dto.class);


     public static <T> T softConvertValue(Object fromValue, Class<T> toValueType) 
        {
            ObjectMapper objMapper = new ObjectMapper();
            return objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                    .convertValue(fromValue, toValueType);
        }

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

What's wrong with:

clob.getSubString(1, (int) clob.length());

?

For example Oracle oracle.sql.CLOB performs getSubString() on internal char[] which defined in oracle.jdbc.driver.T4CConnection and just System.arraycopy() and next wrap to String... You never get faster reading than System.arraycopy().

UPDATE Get driver ojdbc6.jar, decompile CLOB implementation, and study which case could be faster based on the internals knowledge.

Parse JSON from JQuery.ajax success data

The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbName';

Source

This is mine:

USE databasename; 
SHOW TABLES; 
SELECT FOUND_ROWS();

Search text in fields in every table of a MySQL database

I used Union to string together queries. Don't know if it's the most efficient way, but it works.

SELECT * FROM table1 WHERE name LIKE '%Bob%' Union
SELCET * FROM table2 WHERE name LIKE '%Bob%';

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

Simple dictionary in C++

If you are into optimization, and assuming the input is always one of the four characters, the function below might be worth a try as a replacement for the map:

char map(const char in)
{ return ((in & 2) ? '\x8a' - in : '\x95' - in); }

It works based on the fact that you are dealing with two symmetric pairs. The conditional works to tell apart the A/T pair from the G/C one ('G' and 'C' happen to have the second-least-significant bit in common). The remaining arithmetics performs the symmetric mapping. It's based on the fact that a = (a + b) - b is true for any a,b.

Load local images in React.js

If you want load image with a local relative URL as you are doing. React project has a default public folder. You should put your images folder inside. It will work.

enter image description here

Non-alphanumeric list order from os.listdir()

It's probably just the order that C's readdir() returns. Try running this C program:

#include <dirent.h>
#include <stdio.h>
int main(void)
{   DIR *dirp;
    struct dirent* de;
    dirp = opendir(".");
    while(de = readdir(dirp)) // Yes, one '='.
        printf("%s\n", de->d_name);
    closedir(dirp);
    return 0;
}

The build line should be something like gcc -o foo foo.c.

P.S. Just ran this and your Python code, and they both gave me sorted output, so I can't reproduce what you're seeing.

Why AVD Manager options are not showing in Android Studio

Follow these steps:

There could be a better way but this worked for me:

1) Open android studio, go to preferences by clicking on the top left 'Android Studio'

2) Search for 'avd' in the search bar. You'll see 'AVD Manager' in search results. It will be under 'Tools' folder.

3) Click on it and it will ask you to set up a short cut. Set it up. Say for example use 'V' as a shortcut.

4) Now open android studio and create a new project. After the project is created, press your shortcut that you had set. Like 'V' in our case. It will open the 'Virtual Devices Screen'

Regex: match everything but specific pattern

Regex: match everything but:

Demo note: the newline \n is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.

Anchor note: In many languages, use \A to define the unambiguous start of string, and \z (in Python, it is \Z, in JavaScript, $ is OK) to define the very end of the string.

Dot note: In many flavors (but not POSIX, TRE, TCL), . matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s in PCRE/Boost/.NET/Python/Java and /m in Ruby) for the . to match any char including a newline.

Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\. will be declared as "world\\.", or use a character class: "world[.]"). Use raw string literals (Python r'\bworld\b'), C# verbatim string literals @"world\.", or slashy strings/regex literal notations like /world\./.

How to change Rails 3 server default port in develoment?

I like to append the following to config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    alias :default_options_alias :default_options
    def default_options
      default_options_alias.merge!(:Port => 3333)
    end    
  end
end

Convert data.frame columns from factors to characters

Update: Here's an example of something that doesn't work. I thought it would, but I think that the stringsAsFactors option only works on character strings - it leaves the factors alone.

Try this:

bob2 <- data.frame(bob, stringsAsFactors = FALSE)

Generally speaking, whenever you're having problems with factors that should be characters, there's a stringsAsFactors setting somewhere to help you (including a global setting).

Effect of NOLOCK hint in SELECT statements

1) Yes, a select with NOLOCK will complete faster than a normal select.

2) Yes, a select with NOLOCK will allow other queries against the effected table to complete faster than a normal select.

Why would this be?

NOLOCK typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous.

You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a NOLOCK read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed.

You really have no way to know what the state of the data is.

If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then NOLOCK is a good way to boost performance for these queries and avoid having them negatively impact database performance.

Always use the NOLOCK hint with great caution and treat any data it returns suspiciously.

What is an OS kernel ? How does it differ from an operating system?

A kernel is the part of the operating system that mediates access to system resources. It's responsible for enabling multiple applications to effectively share the hardware by controlling access to CPU, memory, disk I/O, and networking.

An operating system is the kernel plus applications that enable users to get something done (i.e compiler, text editor, window manager, etc).

Validate that text field is numeric usiung jQuery

You don't need a regex for this one. Use the isNAN() JavaScript function.

The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not.

if (isNaN($('#Field').val()) == false) {

    // It's a number
}

Date difference in minutes in Python

In case someone doesn't realize it, one way to do this would be to combine Christophe and RSabet's answers:

from datetime import datetime
import time

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)

diff = d2 -d1
diff_minutes = (diff.days * 24 * 60) + (diff.seconds/60)

print(diff_minutes)
> 3043

How to linebreak an svg text within javascript?

I think this does what you want:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

Modify a Column's Type in sqlite3

SQLite doesn't support removing or modifying columns, apparently. But do remember that column data types aren't rigid in SQLite, either.

See also:

Remove file extension from a file name string

There's a method in the framework for this purpose, which will keep the full path except for the extension.

System.IO.Path.ChangeExtension(path, null);

If only file name is needed, use

System.IO.Path.GetFileNameWithoutExtension(path);

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

It took me ages to work this one out, so for the benefit of searchers:

I had a bizarre issue whereby the application worked in debug, but gave the XamlParseException once released.

After fixing the x86/x64 issue as detailed by Katjoek, the issue remained.

The issue was that a CEF tutorial said to bring down System.Windows.Interactivity from NuGet (even thought it's in the Extensions section of references in .NET) and bringing down from NuGet sets specific version to true.

Once deployed, a different version of System.Windows.Interactivity was being packed by a different application.

It's refusal to use a different version of the dll caused the whole application to crash with XamlParseException.

How to create full path with node's fs.mkdirSync?

Edit

NodeJS version 10.12.0 has added a native support for both mkdir and mkdirSync to create a directory recursively with recursive: true option as the following:

fs.mkdirSync(targetDir, { recursive: true });

And if you prefer fs Promises API, you can write

fs.promises.mkdir(targetDir, { recursive: true });

Original Answer

Create directories recursively if they do not exist! (Zero dependencies)

const fs = require('fs');
const path = require('path');

function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
  const sep = path.sep;
  const initDir = path.isAbsolute(targetDir) ? sep : '';
  const baseDir = isRelativeToScript ? __dirname : '.';

  return targetDir.split(sep).reduce((parentDir, childDir) => {
    const curDir = path.resolve(baseDir, parentDir, childDir);
    try {
      fs.mkdirSync(curDir);
    } catch (err) {
      if (err.code === 'EEXIST') { // curDir already exists!
        return curDir;
      }

      // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
      if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
        throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
      }

      const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
      if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
        throw err; // Throw if it's just the last created dir.
      }
    }

    return curDir;
  }, initDir);
}

Usage

// Default, make directories relative to current working directory.
mkDirByPathSync('path/to/dir');

// Make directories relative to the current script.
mkDirByPathSync('path/to/dir', {isRelativeToScript: true});

// Make directories with an absolute path.
mkDirByPathSync('/path/to/dir');

Demo

Try It!

Explanations

  • [UPDATE] This solution handles platform-specific errors like EISDIR for Mac and EPERM and EACCES for Windows. Thanks to all the reporting comments by @PediT., @JohnQ, @deed02392, @robyoder and @Almenon.
  • This solution handles both relative and absolute paths. Thanks to @john comment.
  • In the case of relative paths, target directories will be created (resolved) in the current working directory. To Resolve them relative to the current script dir, pass {isRelativeToScript: true}.
  • Using path.sep and path.resolve(), not just / concatenation, to avoid cross-platform issues.
  • Using fs.mkdirSync and handling the error with try/catch if thrown to handle race conditions: another process may add the file between the calls to fs.existsSync() and fs.mkdirSync() and causes an exception.
    • The other way to achieve that could be checking if a file exists then creating it, I.e, if (!fs.existsSync(curDir) fs.mkdirSync(curDir);. But this is an anti-pattern that leaves the code vulnerable to race conditions. Thanks to @GershomMaes comment about the directory existence check.
  • Requires Node v6 and newer to support destructuring. (If you have problems implementing this solution with old Node versions, just leave me a comment)

Deep-Learning Nan loss reasons

The reason for nan, inf or -inf often comes from the fact that division by 0.0 in TensorFlow doesn't result in a division by zero exception. It could result in a nan, inf or -inf "value". In your training data you might have 0.0 and thus in your loss function it could happen that you perform a division by 0.0.

a = tf.constant([2., 0., -2.])
b = tf.constant([0., 0., 0.])
c = tf.constant([1., 1., 1.])
print((a / b) + c)

Output is the following tensor:

tf.Tensor([ inf  nan -inf], shape=(3,), dtype=float32)

Adding a small eplison (e.g., 1e-5) often does the trick. Additionally, since TensorFlow 2 the opteration tf.math.division_no_nan is defined.

How do you find the first key in a dictionary?

The dict type is an unordered mapping, so there is no such thing as a "first" element.

What you want is probably collections.OrderedDict.

How do you convert a JavaScript date to UTC?

Here's my method:

var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);

The resulting utc object isn't really a UTC date, but a local date shifted to match the UTC time (see comments). However, in practice it does the job.

How can I use std::maps with user-defined types as key?

I'd like to expand a little bit on Pavel Minaev's answer, which you should read before reading my answer. Both solutions presented by Pavel won't compile if the member to be compared (such as id in the question's code) is private. In this case, VS2013 throws the following error for me:

error C2248: 'Class1::id' : cannot access private member declared in class 'Class1'

As mentioned by SkyWalker in the comments on Pavel's answer, using a friend declaration helps. If you wonder about the correct syntax, here it is:

class Class1
{
public:
    Class1(int id) : id(id) {}

private:
    int id;
    friend struct Class1Compare;      // Use this for Pavel's first solution.
    friend struct std::less<Class1>;  // Use this for Pavel's second solution.
};

Code on Ideone

However, if you have an access function for your private member, for example getId() for id, as follows:

class Class1
{
public:
    Class1(int id) : id(id) {}
    int getId() const { return id; }

private:
    int id;
};

then you can use it instead of a friend declaration (i.e. you compare lhs.getId() < rhs.getId()). Since C++11, you can also use a lambda expression for Pavel's first solution instead of defining a comparator function object class. Putting everything together, the code could be writtem as follows:

auto comp = [](const Class1& lhs, const Class1& rhs){ return lhs.getId() < rhs.getId(); };
std::map<Class1, int, decltype(comp)> c2int(comp);

Code on Ideone

An invalid form control with name='' is not focusable

There are many ways to fix this like

  1. Add novalidate to your form but its totally wrong as it will remove form validation which will lead to wrong information entered by the users.

<form action="...." class="payment-details" method="post" novalidate>

  1. Use can remove the required attribute from required fields which is also wrong as it will remove form validation once again.

    Instead of this:

<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" required="required">

   Use this:

<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text">

  1. Use can disable the required fields when you are not going to submit the form instead of doing some other option. This is the recommended solution in my opinion.

    like:

<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" disabled="disabled">

or disable it through javascript / jquery code dependes upon your scenario.

Getting the parent of a directory in Bash

use this : export MYVAR="$(dirname "$(dirname "$(dirname "$(dirname $PWD)")")")" if you want 4th parent directory

export MYVAR="$(dirname "$(dirname "$(dirname $PWD)")")" if you want 3rd parent directory

export MYVAR="$(dirname "$(dirname $PWD)")" if you want 2nd parent directory

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Which Ruby version am I really running?

On your terminal, try running:

which -a ruby

This will output all the installed Ruby versions (via RVM, or otherwise) on your system in your PATH. If 1.8.7 is your system Ruby version, you can uninstall the system Ruby using:

sudo apt-get purge ruby

Once you have made sure you have Ruby installed via RVM alone, in your login shell you can type:

rvm --default use 2.0.0

You don't need to do this if you have only one Ruby version installed.

If you still face issues with any system Ruby files, try running:

dpkg-query -l '*ruby*'

This will output a bunch of Ruby-related files and packages which are, or were, installed on your system at the system level. Check the status of each to find if any of them is native and is causing issues.

Fill Combobox from database

private void StudentForm_Load(object sender, EventArgs e)

{
         string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
         SqlDataReader reader = DB.Query(q);

         while (reader.Read())
         {
             cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
         }
  }

Restart pods when configmap updates in Kubernetes?

The current best solution to this problem (referenced deep in https://github.com/kubernetes/kubernetes/issues/22368 linked in the sibling answer) is to use Deployments, and consider your ConfigMaps to be immutable.

When you want to change your config, create a new ConfigMap with the changes you want to make, and point your deployment at the new ConfigMap. If the new config is broken, the Deployment will refuse to scale down your working ReplicaSet. If the new config works, then your old ReplicaSet will be scaled to 0 replicas and deleted, and new pods will be started with the new config.

Not quite as quick as just editing the ConfigMap in place, but much safer.

How to force the input date format to dd/mm/yyyy?

No such thing. the input type=date will pick up whatever your system default is and show that in the GUI but will always store the value in ISO format (yyyy-mm-dd). Beside be aware that not all browsers support this so it's not a good idea to depend on this input type yet.

If this is a corporate issue, force all the computer to use local regional format (dd-mm-yyyy) and your UI will show it in this format (see wufoo link before after changing your regional settings, you need to reopen the browser).

Your best bet is still to use JavaScript based component that will allow you to customize this to whatever you wish.

Given URL is not permitted by the application configuration

  1. From the menu item of your app name which is located on the top left corner, create a test app.
  2. In the settings section of the new test app: add 'http://localhost:3000' to the Website url and add 'localhost' to App domains.
  3. Update your app with the new Facebook APP Id
  4. Use Facebook sdk v2.2 or whatever the latest in your app.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Call and receive output from Python script in Java?

ProcessBuilder is very easy to use.

ProcessBuilder pb = new ProcessBuilder("python","Your python file",""+Command line arguments if any);
Process p = pb.start();

This should call python. Refer to the process approach here for full example!

https://bytes.com/topic/python/insights/949995-three-ways-run-python-programs-java

Sorting a Python list by two fields

employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])

We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).

employees[0] = Employee's Name
employees[1] = Employee's Salary

This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))

How to reload .bash_profile from the command line?

I like the fact that after you have just edited the file, all you need to do is type:

. !$

This sources the file you had just edited in history. See What is bang dollar in bash.

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

Parse string to date with moment.js

  • How to change any string date to object date (also with moment.js):

let startDate = "2019-01-16T20:00:00.000"; let endDate = "2019-02-11T20:00:00.000"; let sDate = new Date(startDate); let eDate = new Date(endDate);

  • with moment.js:

startDate = moment(sDate); endDate = moment(eDate);

Current date and time as string

Using C++ in MS Visual Studio 2015 (14), I use:

#include <chrono>

string NowToString()
{
  chrono::system_clock::time_point p = chrono::system_clock::now();
  time_t t = chrono::system_clock::to_time_t(p);
  char str[26];
  ctime_s(str, sizeof str, &t);
  return str;
}

What's the strangest corner case you've seen in C# or .NET?

Consider this weird case:

public interface MyInterface {
  void Method();
}
public class Base {
  public void Method() { }
}
public class Derived : Base, MyInterface { }

If Base and Derived are declared in the same assembly, the compiler will make Base::Method virtual and sealed (in the CIL), even though Base doesn't implement the interface.

If Base and Derived are in different assemblies, when compiling the Derived assembly, the compiler won't change the other assembly, so it will introduce a member in Derived that will be an explicit implementation for MyInterface::Method that will just delegate the call to Base::Method.

The compiler has to do this in order to support polymorphic dispatch with regards to the interface, i.e. it has to make that method virtual.

How can I convert a dictionary into a list of tuples?

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

It's not in the order you want, but dicts don't have any specific order anyway.1 Sort it or organize it as necessary.

See: items(), iteritems()


In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a "view" into the dictionary items. See the What's New document for Python 3.0, and the new documentation on views.

1: Insertion-order preservation for dicts was added in Python 3.7

Javascript foreach loop on associative array object

If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

_x000D_
_x000D_
const h = {_x000D_
  a: 1,_x000D_
  b: 2_x000D_
};_x000D_
_x000D_
Object.entries(h).forEach(([key, value]) => console.log(value));_x000D_
// logs 1, 2
_x000D_
_x000D_
_x000D_

in this example, forEach uses Destructuring assignment of an array.

Why doesn't C++ have a garbage collector?

The idea behind C++ was that you would not pay any performance impact for features that you don't use. So adding garbage collection would have meant having some programs run straight on the hardware the way C does and some within some sort of runtime virtual machine.

Nothing prevents you from using some form of smart pointers that are bound to some third-party garbage collection mechanism. I seem to recall Microsoft doing something like that with COM and it didn't go to well.

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

Programs to monitor if a process on a system is running.

Script is stored in crontab and runs once every minute.

This works with if process is not running or process is running multiple times:

#! /bin/bash

case "$(pidof amadeus.x86 | wc -w)" in

0)  echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
    /etc/amadeus/amadeus.x86 &
    ;;
1)  # all ok
    ;;
*)  echo "Removed double Amadeus: $(date)" >> /var/log/amadeus.txt
    kill $(pidof amadeus.x86 | awk '{print $1}')
    ;;
esac

0 If process is not found, restart it.
1 If process is found, all ok.
* If process running 2 or more, kill the last.


A simpler version. This just test if process is running, and if not restart it.

It just tests the exit flag $? from the pidof program. It will be 0 of process is running and 1 if not.

#!/bin/bash
pidof  amadeus.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
        echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
        /etc/amadeus/amadeus.x86 &
fi

And at last, a one liner

pidof amadeus.x86 >/dev/null ; [[ $? -ne 0 ]] && echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt && /etc/amadeus/amadeus.x86 &

cccam oscam

Design DFA accepting binary strings divisible by a number 'n'

I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.

Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.

In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.

Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.

For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :

20/2 = 10 
10/2 = 5

Hence our answer is 5 + 1 + 1 = 7. (The 1 + 1 because we divided the number 20 twice).

Is there a method to generate a UUID with go language

From Russ Cox's post:

There's no official library. Ignoring error checking, this seems like it would work fine:

f, _ := os.Open("/dev/urandom")
b := make([]byte, 16)
f.Read(b)
f.Close()
uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

Note: In the original, pre Go 1 version the first line was:

f, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)

Here it compiles and executes, only /dev/urandom returns all zeros in the playground. Should work fine locally.

In the same thread there are some other methods/references/packages found.

Event binding on dynamically created elements?

You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.

var mouseOverHandler = function() {
    // Do stuff
};
var mouseOutHandler = function () {
    // Do stuff
};

$(function() {
    // On the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);
});

// This next part would be in the callback from your Ajax call
$("<select></select>")
    .append( /* Your <option>s */ )
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo( /* Wherever you need the select box */ )
;

How to remove leading and trailing whitespace in a MySQL field?

you can use ltrim or rtrim to clean whitespaces for the right or left or a string.

What is the question mark for in a Typescript parameter name

This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.

export interface ISearchResult {  
  title: string;  
  listTitle:string;
  entityName?: string,
  lookupName?:string,
  lookupId?:string  
}

What's the most useful and complete Java cheat sheet?

Here is a great one http://download.oracle.com/javase/1.5.0/docs/api/

These languages are big. You cant expect a cheat sheet to fit on a piece of paper

why is plotting with Matplotlib so slow?

For the first solution proposed by Joe Kington ( .copy_from_bbox & .draw_artist & canvas.blit), I had to capture the backgrounds after the fig.canvas.draw() line, otherwise the background had no effect and I got the same result as you mentioned. If you put it after the fig.show() it still does not work as proposed by Michael Browne.

So just put the background line after the canvas.draw():

[...]
fig.show()

# We need to draw the canvas before we start animating...
fig.canvas.draw()

# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]

What is the right way to debug in iPython notebook?

You can always add this in any cell:

import pdb; pdb.set_trace()

and the debugger will stop on that line. For example:

In[1]: def fun1(a):
           def fun2(a):
               import pdb; pdb.set_trace() # debugging starts here
           return fun2(a)

In[2]: fun1(1)

Server.Mappath in C# classlibrary

You can get the base path by using the following code and append your needed path with that.

string  path = System.AppDomain.CurrentDomain.BaseDirectory;

Android: Getting a file URI from a content URI?

If you have a content Uri with content://com.externalstorage... you can use this method to get absolute path of a folder or file on Android 19 or above.

public static String getPath(final Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        System.out.println("getPath() uri: " + uri.toString());
        System.out.println("getPath() uri authority: " + uri.getAuthority());
        System.out.println("getPath() uri path: " + uri.getPath());

        // ExternalStorageProvider
        if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            System.out.println("getPath() docId: " + docId + ", split: " + split.length + ", type: " + type);

            // This is for checking Main Memory
            if ("primary".equalsIgnoreCase(type)) {
                if (split.length > 1) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1] + "/";
                } else {
                    return Environment.getExternalStorageDirectory() + "/";
                }
                // This is for checking SD Card
            } else {
                return "storage" + "/" + docId.replace(":", "/");
            }

        }
    }
    return null;
}

You can check each part of Uri using println. Returned values for my SD card and device main memory are listed below. You can access and delete if file is on memory, but I wasn't able to delete file from SD card using this method, only read or opened image using this absolute path. If you find a solution to delete using this method, please share.

SD CARD

getPath() uri: content://com.android.externalstorage.documents/tree/612E-B7BF%3A/document/612E-B7BF%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/612E-B7BF:/document/612E-B7BF:
getPath() docId: 612E-B7BF:, split: 1, type: 612E-B7BF

MAIN MEMORY

getPath() uri: content://com.android.externalstorage.documents/tree/primary%3A/document/primary%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/primary:/document/primary:
getPath() docId: primary:, split: 1, type: primary

If you wish to get Uri with file:/// after getting path use

DocumentFile documentFile = DocumentFile.fromFile(new File(path));
documentFile.getUri() // will return a Uri with file Uri

How to write hello world in assembler under Windows?

If you want to use NASM and Visual Studio's linker (link.exe) with anderstornvig's Hello World example you will have to manually link with the C Runtime Libary that contains the printf() function.

nasm -fwin32 helloworld.asm
link.exe helloworld.obj libcmt.lib

Hope this helps someone.

nodemon not found in npm

I tried to list global packages using npm list -g --depth=0, but couldn't find nodemon.
Hence, tried installing it using global flag.
sudo npm install nodemon -g
This worked fine for me.

How do you keep parents of floated elements from collapsing?

Although the code isn't perfectly semantic, I think it's more straightforward to have what I call a "clearing div" at the bottom of every container with floats in it. In fact, I've included the following style rule in my reset block for every project:

.clear 
{
   clear: both;
}

If you're styling for IE6 (god help you), you might want to give this rule a 0px line-height and height as well.

startsWith() and endsWith() functions in PHP

For PHP 8 or newer, use the str_starts_with function:

str_starts_with('http://www.google.com', 'http')

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

Yes you can:

Use this method to prevent errors:

<script> 
query=location.hash;
document.cookie= 'anchor'+query;
</script>

And of course in PHP, explode that puppy and get one of the values

$split = explode('/', $_COOKIE['anchor']);
print_r($split[1]); //to test it, use print_r. this line will print the value after the anchortag

list.clear() vs list = new ArrayList<Integer>();

I think that the answer is that it depends on a whole range of factors such as:

  • whether the list size can be predicted beforehand (i.e. can you set the capacity accurately),
  • whether the list size is variable (i.e. each time it is filled),
  • how long the lifetime of the list will be in both versions, and
  • your heap / GC parameters and CPU.

These make it hard to predict which will be better. But my intuition is that the difference will not be that great.

Two bits of advice on optimization:

  • Don't waste time trying to optimize this ... unless the application is objectively too slow AND measurement using a profiler tells you that this is a performance hotspot. (The chances are that one of those preconditions won't be true.)

  • If you do decide to optimize this, do it scientifically. Try both (all) of the alternatives and decide which is best by measuring the performance in your actual application on a realistic problem / workload / input set. (An artificial benchmark is liable to give you answers that do not predict real-world behavior, because of factors like those I listed previously.)

Writing a string to a cell in excel

I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.

Try this:

Sub varchanger()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim TxtRng  As Range

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("Sheet1")
    'or ws.Unprotect Password:="yourpass"
    ws.Unprotect

    Set TxtRng = ws.Range("A1")
    TxtRng.Value = "SubTotal"
    'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
    ' or ws.Protect Password:="yourpass"
    ws.Protect

End Sub

If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.

NOTES:

  1. I'm re-setting sheet protection after writing to the range. I'm assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you'll need to remove that line.
  2. I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
  3. The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

How to solve "The directory is not empty" error when running rmdir command in a batch script?

Similar to Harry Johnston's answer, I loop until it works.

set dirPath=C:\temp\mytest
:removedir
if exist "%dirPath%" (
    rd /s /q "%dirPath%" 
    goto removedir
)

How to specify the download location with wget?

"-P" is the right option, please read on for more related information:

wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2

Relevant snippets from man pages for convenience:

   -P prefix
   --directory-prefix=prefix
       Set directory prefix to prefix.  The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree.  The default is . (the current directory).

   -nd
   --no-directories
       Do not create a hierarchy of directories when retrieving recursively.  With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
       filenames will get extensions .n).


   -np
   --no-parent
       Do not ever ascend to the parent directory when retrieving recursively.  This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.

XPath with multiple conditions

Here, we can do this way as well:

//category [@name='category name']/author[contains(text(),'authorname')]

OR

//category [@name='category name']//author[contains(text(),'authorname')]

To Learn XPATH in detail please visit- selenium xpath in detail

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

size of struct in C

Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.

Javascript onHover event

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

mysqli::query(): Couldn't fetch mysqli

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");

Hope it helps.

Google Authenticator available as a public service?

You can use my solution, posted as the answer to my question (there is full Python code and explanation):

Google Authenticator implementation in Python

It is rather easy to implement it in PHP or Perl, I think. If you have any problems with this, please let me know.

I have also posted my code on GitHub as Python module.

"Could not find or load main class" Error while running java program using cmd prompt

I used IntelliJ to create my .jar, which included some unpacked jars from my libraries. One of these other jars had some signed stuff in the MANIFEST which prevented the .jar from being loaded. No warnings, or anything, just didn't work. Could not find or load main class

Removing the unpacked jar which contained the manifest fixed it.

Using Laravel Homestead: 'no input file specified'

This is easy to fix, because you have changed the folder name to: exampleproject

So SSH to your vagrant:

ssh [email protected] -p 2222

Then change your nginx config:

sudo vi /etc/nginx/sites-enabled/homestead.app

Edit the correct URI to the root on line 3 to this with the new folder name:

root "/Users/MYUSERNAME/Code/exampleproject/public";

Restart Nginx

sudo service nginx reload

Reload the web browser, it should work now

Why not inherit from List<T>?

What if the FootballTeam has a reserves team along with the main team?

class FootballTeam
{
    List<FootballPlayer> Players { get; set; }
    List<FootballPlayer> ReservePlayers { get; set; }
}

How would you model that with?

class FootballTeam : List<FootballPlayer> 
{ 
    public string TeamName; 
    public int RunningTotal 
}

The relationship is clearly has a and not is a.

or RetiredPlayers?

class FootballTeam
{
    List<FootballPlayer> Players { get; set; }
    List<FootballPlayer> ReservePlayers { get; set; }
    List<FootballPlayer> RetiredPlayers { get; set; }
}

As a rule of thumb, if you ever want to inherit from a collection, name the class SomethingCollection.

Does your SomethingCollection semantically make sense? Only do this if your type is a collection of Something.

In the case of FootballTeam it doesn't sound right. A Team is more than a Collection. A Team can have coaches, trainers, etc as the other answers have pointed out.

FootballCollection sounds like a collection of footballs or maybe a collection of football paraphernalia. TeamCollection, a collection of teams.

FootballPlayerCollection sounds like a collection of players which would be a valid name for a class that inherits from List<FootballPlayer> if you really wanted to do that.

Really List<FootballPlayer> is a perfectly good type to deal with. Maybe IList<FootballPlayer> if you are returning it from a method.

In summary

Ask yourself

  1. Is X a Y? or Has X a Y?

  2. Do my class names mean what they are?

C++ Get name of type in template

This trick was mentioned under a few other questions, but not here yet.

All major compilers support __PRETTY_FUNC__ (GCC & Clang) /__FUNCSIG__ (MSVC) as an extension.

When used in a template like this:

template <typename T> const char *foo()
{
    #ifdef _MSC_VER
    return __FUNCSIG__;
    #else
    return __PRETTY_FUNCTION__;
    #endif
}

It produces strings in a compiler-dependent format, that contain, among other things, the name of T.

E.g. foo<float>() returns:

  • "const char* foo() [with T = float]" on GCC
  • "const char *foo() [T = float]" on Clang
  • "const char *__cdecl foo<float>(void)" on MSVC

You can easily parse the type names out of those strings. You just need to figure out how many 'junk' characters your compiler inserts before and after the type.

You can even do that completely at compile-time.


The resulting names can slightly vary between different compilers. E.g. GCC omits default template arguments, and MSVC prefixes classes with the word class.


Here's an implementation that I've been using. Everything is done at compile-time.

Example usage:

std::cout << TypeName<float>() << '\n';
std::cout << TypeName(1.2f); << '\n';

Implementation:

#include <array>
#include <cstddef>

namespace impl
{
    template <typename T>
    constexpr const auto &RawTypeName()
    {
        #ifdef _MSC_VER
        return __FUNCSIG__;
        #else
        return __PRETTY_FUNCTION__;
        #endif
    }

    struct RawTypeNameFormat
    {
        std::size_t leading_junk = 0, trailing_junk = 0;
    };

    // Returns `false` on failure.
    inline constexpr bool GetRawTypeNameFormat(RawTypeNameFormat *format)
    {
        const auto &str = RawTypeName<int>();
        for (std::size_t i = 0;; i++)
        {
            if (str[i] == 'i' && str[i+1] == 'n' && str[i+2] == 't')
            {
                if (format)
                {
                    format->leading_junk = i;
                    format->trailing_junk = sizeof(str)-i-3-1; // `3` is the length of "int", `1` is the space for the null terminator.
                }
                return true;
            }
        }
        return false;
    }

    inline static constexpr RawTypeNameFormat format =
    []{
        static_assert(GetRawTypeNameFormat(nullptr), "Unable to figure out how to generate type names on this compiler.");
        RawTypeNameFormat format;
        GetRawTypeNameFormat(&format);
        return format;
    }();
}

// Returns the type name in a `std::array<char, N>` (null-terminated).
template <typename T>
[[nodiscard]] constexpr auto CexprTypeName()
{
    constexpr std::size_t len = sizeof(impl::RawTypeName<T>()) - impl::format.leading_junk - impl::format.trailing_junk;
    std::array<char, len> name{};
    for (std::size_t i = 0; i < len-1; i++)
        name[i] = impl::RawTypeName<T>()[i + impl::format.leading_junk];
    return name;
}

template <typename T>
[[nodiscard]] const char *TypeName()
{
    static constexpr auto name = CexprTypeName<T>();
    return name.data();
}
template <typename T>
[[nodiscard]] const char *TypeName(const T &)
{
    return TypeName<T>();
}

Asp.net - Add blank item at top of dropdownlist

The databinding takes place after you've added your blank list item, and it replaces what's there already, you need to add the blank item to the beginning of the List from your controller, or add it after databinding.

EDIT:

After googling this quickly as of ASP.Net 2.0 there's an "AppendDataBoundItems" true property that you can set to...append the databound items.

for details see

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=281 or

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

'cl' is not recognized as an internal or external command,

I sometimes get this problem when changing from Debug to Release or vice-versa. Closing and reopening QtCreator and building again solves the problem for me.

Qt Creator 2.8.1; Qt 5.1.1 (MSVC2010, 32bit)

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

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

You can use stepi or nexti (which can be abbreviated to si or ni) to step through your machine code.

Is there a naming convention for git repositories?

If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer. Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens.

If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.

Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens and name your packages in composer or npm identically to your package on GitHub.

How to download videos from youtube on java?

ytd2 is a fully functional YouTube video downloader. Check out its source code if you want to see how it's done.

Alternatively, you can also call an external process like youtube-dl to do the job. This is probably the easiest solution but it isn't in "pure" Java.

TransactionRequiredException Executing an update/delete query

I faced the same exception "TransactionRequiredException Executing an update/delete query" but for me the reason was that I've created another bean in the spring applicationContext.xml file with the name "transactionManager" refering to "org.springframework.jms.connection.JmsTransactionManager" however there was another bean with the same name "transactionManager" refering to "org.springframework.orm.jpa.JpaTransactionManager". So the JPA bean is overriten by the JMS bean.

After renaming the bean name of the Jms, issue is resolved.

How to put a List<class> into a JSONObject and then read that object?

This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this.( with or without an external library).

 Type collectionType = new TypeToken<List<Class>>() {
                } // end new
                        .getType();

                String gsonString = 
                new Gson().toJson(objList, collectionType);

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

How to schedule a function to run every hour on Flask?

I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:

#!/usr/bin/python3
""" Demonstrating Flask, using APScheduler. """

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

def sensor():
    """ Function for test purposes. """
    print("Scheduler is alive!")

sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=60)
sched.start()

app = Flask(__name__)

@app.route("/home")
def home():
    """ Function for test purposes. """
    return "Welcome Home :) !"

if __name__ == "__main__":
    app.run()

I'm also leaving this Gist here, if anyone have interest on updates for this example.

Here are some references, for future readings:

Get the first key name of a JavaScript object

There's no such thing as the "first" key in a hash (Javascript calls them objects). They are fundamentally unordered. Do you mean just choose any single key:

for (var k in ahash) {
    break
}

// k is a key in ahash.

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.