Programs & Examples On #Celerity

Celerity is a JRuby wrapper around HtmlUnit – a headless Java browser with JavaScript support. It provides a simple API for programmatic navigation through web applications. Celerity aims at being API compatible with Watir.

How to make multiple divs display in one line but still retain width?

You can use float:left in DIV or use SPAN tag, like

<div style="width:100px;float:left"> First </div> 
<div> Second </div> 
<br/>

or

<span style="width:100px;"> First </span> 
<span> Second </span> 
<br/>

Eclipse does not start when I run the exe?

The same thing was happening for me. All I had to do was uninstalled Java Update 8

jquery simple image slideshow tutorial

I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time

JAVASCRIPT

$(function () {

    /* SET PARAMETERS */
    var change_img_time     = 5000; 
    var transition_speed    = 100;

    var simple_slideshow    = $("#exampleSlider"),
        listItems           = simple_slideshow.children('li'),
        listLen             = listItems.length,
        i                   = 0,

        changeList = function () {

            listItems.eq(i).fadeOut(transition_speed, function () {
                i += 1;
                if (i === listLen) {
                    i = 0;
                }
                listItems.eq(i).fadeIn(transition_speed);
            });

        };

    listItems.not(':first').hide();
    setInterval(changeList, change_img_time);

});

.

HTML

<ul id="exampleSlider">
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>

.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO

.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX

Why do Twitter Bootstrap tables always have 100% width?

All tables within the bootstrap stretch according to their container, which you can easily do by placing your table inside a .span* grid element of your choice. If you wish to remove this property you can create your own table class and simply add it to the table you want to expand with the content within:

.table-nonfluid {
   width: auto !important;
}

You can add this class inside your own stylesheet and simply add it to the container of your table like so:

<table class="table table-nonfluid"> ... </table>

This way your change won't affect the bootstrap stylesheet itself (you might want to have a fluid table somewhere else in your document).

When should I use a table variable vs temporary table in sql server?

Your question shows you have succumbed to some of the common misconceptions surrounding table variables and temporary tables.

I have written quite an extensive answer on the DBA site looking at the differences between the two object types. This also addresses your question about disk vs memory (I didn't see any significant difference in behaviour between the two).

Regarding the question in the title though as to when to use a table variable vs a local temporary table you don't always have a choice. In functions, for example, it is only possible to use a table variable and if you need to write to the table in a child scope then only a #temp table will do (table-valued parameters allow readonly access).

Where you do have a choice some suggestions are below (though the most reliable method is to simply test both with your specific workload).

  1. If you need an index that cannot be created on a table variable then you will of course need a #temporary table. The details of this are version dependant however. For SQL Server 2012 and below the only indexes that could be created on table variables were those implicitly created through a UNIQUE or PRIMARY KEY constraint. SQL Server 2014 introduced inline index syntax for a subset of the options available in CREATE INDEX. This has been extended since to allow filtered index conditions. Indexes with INCLUDE-d columns or columnstore indexes are still not possible to create on table variables however.

  2. If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary table. That supports TRUNCATE (which is more efficient than DELETE for large tables) and additionally subsequent inserts following a TRUNCATE can have better performance than those following a DELETE as illustrated here.

  3. If you will be deleting or updating a large number of rows then the temp table may well perform much better than a table variable - if it is able to use rowset sharing (see "Effects of rowset sharing" below for an example).
  4. If the optimal plan using the table will vary dependent on data then use a #temporary table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).
  5. If the optimal plan for the query using the table is unlikely to ever change then you may consider a table variable to skip the overhead of statistics creation and recompiles (would possibly require hints to fix the plan you want).
  6. If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  7. If you need the data in the table to survive a rollback of an outer user transaction then use a table variable. A possible use case for this might be logging the progress of different steps in a long SQL batch.
  8. When using a #temp table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables.
  9. Within stored routines, both table variables and temporary tables can be cached. The metadata maintenance for cached table variables is less than that for #temporary tables. Bob Ward points out in his tempdb presentation that this can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.

Effects of rowset sharing

DECLARE @T TABLE(id INT PRIMARY KEY, Flag BIT);

CREATE TABLE #T (id INT PRIMARY KEY, Flag BIT);

INSERT INTO @T 
output inserted.* into #T
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), 0
FROM master..spt_values v1, master..spt_values v2

SET STATISTICS TIME ON

/*CPU time = 7016 ms,  elapsed time = 7860 ms.*/
UPDATE @T SET Flag=1;

/*CPU time = 6234 ms,  elapsed time = 7236 ms.*/
DELETE FROM @T

/* CPU time = 828 ms,  elapsed time = 1120 ms.*/
UPDATE #T SET Flag=1;

/*CPU time = 672 ms,  elapsed time = 980 ms.*/
DELETE FROM #T

DROP TABLE #T

Difference between $.ajax() and $.get() and $.load()

The methods provide different layers of abstraction.

  • $.ajax() gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax() or $.get().

Anaconda site-packages

I encountered this issue in my conda environment. The reason is that packages have been installed into two different folders, only one of which is recognised by the Python executable.

~/anaconda2/envs/[my_env]/site-packages ~/anaconda2/envs/[my_env]/lib/python2.7/site-packages

A proved solution is to add both folders to python path, using the following steps in command line (Please replace [my_env] with your own environment):

  1. conda activate [my_env].
  2. conda-develop ~/anaconda2/envs/[my_env]/site-packages
  3. conda-develop ~/anaconda2/envs/[my_env]/lib/python2.7/site-packages (conda-develop is to add a .pth file to the folder so that the Python executable knows of this folder when searching for packages.)

To ensure this works, try to activate Python in this environment, and import the package that was not found.

Can constructors be async?

Since it is not possible to make an async constructor, I use a static async method that returns a class instance created by a private constructor. This is not elegant but it works ok.

public class ViewModel       
{       
    public ObservableCollection<TData> Data { get; set; }       

    //static async method that behave like a constructor       
    async public static Task<ViewModel> BuildViewModelAsync()  
    {       
        ObservableCollection<TData> tmpData = await GetDataTask();  
        return new ViewModel(tmpData);
    }       

    // private constructor called by the async method
    private ViewModel(ObservableCollection<TData> Data)
    {
        this.Data = Data;   
    }
}  

VarBinary vs Image SQL Server Data Type to Store Binary Data?

There is also the rather spiffy FileStream, introduced in SQL Server 2008.

Show/hide forms using buttons and JavaScript

There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

_x000D_
_x000D_
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
    document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
    stuff hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

Have nginx access_log and error_log log to STDOUT and STDERR of master process

If the question is docker related... the official nginx docker images do this by making softlinks towards stdout/stderr

RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log

REF: https://microbadger.com/images/nginx

How to use if statements in LESS

LESS has guard expressions for mixins, not individual attributes.

So you'd create a mixin like this:

.debug(@debug) when (@debug = true) {
    header {
      background-color: yellow;
      #title {
          background-color: orange;
      }
    }

    article {
      background-color: red;
    }
}

And turn it on or off by calling .debug(true); or .debug(false) (or not calling it at all).

Group By Multiple Columns

Use an anonymous type.

Eg

group x by new { x.Column1, x.Column2 }

How to force view controller orientation in iOS 8?

If you are using navigationViewController you should create your own superclass for this and override:

- (BOOL)shouldAutorotate {
  id currentViewController = self.topViewController;

  if ([currentViewController isKindOfClass:[SecondViewController class]])
    return NO;

  return YES;
}

this will disable rotation in SecondViewController but if you push your SecondViewController when your device is on portrait orientation then your SecondViewController will appear in portrait mode.

Assume that you are using storyboard. You have to create manual segue (How to) and in your "onClick" method:

- (IBAction)onPlayButtonClicked:(UIBarButtonItem *)sender {
  NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
  [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  [self performSegueWithIdentifier:@"PushPlayerViewController" sender:self];
}

This will force landscape orientation before your superclass disable autorotate feature.

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

Simulating Button click in javascript

The smallest change to fix this would be to change

onClick="document.getElementById("datepicker").click()">

to

onClick="$('#datepicker').click()">

click() is a jQuery method. Also, you had a collision between the double-quotes used for the HTML element attribute and those use for the JavaScript function argument.

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

How do you create an asynchronous method in C#?

I don't recommend StartNew unless you need that level of complexity.

If your async method is dependent on other async methods, the easiest approach is to use the async keyword:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  for (int i = 0; i < num; i++)
  {
    await Task.Delay(TimeSpan.FromSeconds(1));
  }

  return DateTime.Now;
}

If your async method is doing CPU work, you should use Task.Run:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  await Task.Run(() => ...);
  return DateTime.Now;
}

You may find my async/await intro helpful.

Font awesome is not showing icon

I was following this tutorial to host Font Awesome Pro 5.13 myself.

https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself

For some reason I could not get <link href="%PUBLIC_URL%/font-awesome/all.min.css" rel="stylesheet"> to load webfonts that in turn resulted in only squares showing up. But when I used <script defer src="%PUBLIC_URL%/font-awesome/all.min.js"></script> everything started working. Both links were added in HTML <head>.

Quoting backslashes in Python string literals

If you are here for a filepath just use "\\"

import os
path = r"c:\file"+"\\"+"path"
os.path.normpath(path)

which will outputc:\file\path

Getting Serial Port Information

I'm not quite sure what you mean by "sorting the items after index 0", but if you just want to sort the array of strings returned by SerialPort.GetPortNames(), you can use Array.Sort.

What charset does Microsoft Excel use when saving files?

OOXML files like those that come from Excel 2007 are encoded in UTF-8, according to wikipedia. I don't know about CSV files, but it stands to reason it would use the same format...

Can HTML checkboxes be set to readonly?

What none of you are thinking about here is that you are all using JavaScript, which can be very easily bypassed by any user.

Simply disabling it disables all JQuery/Return False statements.

Your only option for readonly checkboxes is server side.

Display them, let them change them but don't accept the new post data from them.

Python not working in the command line of git bash

Another example of this issue is using the AWS Elastic Beanstalk command line interface (awsebcli, eb cli) from the git bash (MINGW64, Mintty) in windows (using git version 2.19.0.windows.1).

I'm just posting this because it took me a while to end up here, searching for eb-cli specific issues.

Commands such as eb init or eb config save, which require user input, appear to cause a freeze/hang. In reality I guess the console is not updated with the text requesting user input. Moreover, eb deploy only updates the console text after the command has finished, so I don't get to see progress updates until finished.

As mentioned in the git for windows release notes (for v2.19.0) and e.g. in Xun Yang's answer, a workaround is to run

winpty eb <command> (instead of just eb <command>)

A alternative, as suggested in this git for windows issue, could be to use the windows native console instead of mintty (option during git installation).

Illegal character in path at index 16

Had the same problem with spaces. Combination of URL and URI solved it:

URL url = new URL("file:/E:/Program Files/IBM/SDP/runtimes/base");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());

* Source: https://stackoverflow.com/a/749829/435605

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

Stan0 intial idea is not a good idea. There can be multiple files with the same name. Very error prone implementation. Stan0's second idea is the correct way.

When you first upload the file to google drive store its id (in SharedPreferences is probably easiest) for later use

ie.

file= mDrive.files().insert(body).execute();      //initial insert of file to google drive

whereverYouWantToStoreIt= file.getId(); //now you have the guaranteed unique id 
                                        //of the file just inserted. Store it and use it 
                                        //whenever you need to fetch this file

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan

Here is an extract from it:

openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>

openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>

openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>

UPDATE and REPLACE part of a string

query:

UPDATE tablename 
SET field_name = REPLACE(field_name , 'oldstring', 'newstring') 
WHERE field_name LIKE ('oldstring%');

Difference between __getattr__ vs __getattribute__

A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.

__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.

New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.

You almost certainly want __getattr__.

@UniqueConstraint annotation in Java

To ensure a field value is unique you can write

@Column(unique=true)
String username;

The @UniqueConstraint annotation is for annotating multiple unique keys at the table level, which is why you get an error when applying it to a field.

References (JPA TopLink):

Using ng-click vs bind within link function of Angular Directive

You may use a controller in directive:

angular.module('app', [])
  .directive('appClick', function(){
     return {
       restrict: 'A',
       scope: true,
       template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
       controller: function($scope, $element){
         $scope.clicked = 0;
         $scope.click = function(){
           $scope.clicked++
         }
       }
     }
   });

Demo on plunkr

More about directives in Angular guide. And very helpfull for me was videos from official Angular blog post About those directives.

TS1086: An accessor cannot be declared in ambient context

If it's just a library that's causing this, this will avoid the problem just fine. Typescript can be a pain on the neck sometimes so set this value on your tsconfig.json file.

"compilerOptions": {
    "skipLibCheck": true
}

How to remove a key from HashMap while iterating over it?

To remove specific key and element from hashmap use

hashmap.remove(key)

full source code is like

import java.util.HashMap;
public class RemoveMapping {
     public static void main(String a[]){
        HashMap hashMap = new HashMap();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : "+hashMap);
        hashMap.remove(3);   
        System.out.println("Changed HashMap : "+hashMap);        
    }
}

Source : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified--key-from-hashmap

Leverage browser caching, how on apache or .htaccess?

First we need to check if we have enabled mod_headers.c and mod_expires.c.

sudo apache2 -l

If we don't have it, we need to enable them

sudo a2enmod headers

Then we need to restart apache

sudo apache2 restart

At last, add the rules on .htaccess (seen on other answers), for example

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
Header set Cache-Control "public"
</FilesMatch>

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

OK, they all have got some similarities, they do the same things for you in different and similar ways, I divide them in 3 main groups as below:


1) Module bundlers

webpack and browserify as popular ones, work like task runners but with more flexibility, aslo it will bundle everything together as your setting, so you can point to the result as bundle.js for example in one single file including the CSS and Javascript, for more details of each, look at the details below:

webpack

webpack is a module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles - often only one - to be loaded by the browser.

It is incredibly configurable, but to get started you only need to understand Four Core Concepts: entry, output, loaders, and plugins.

This document is intended to give a high-level overview of these concepts, while providing links to detailed concept specific use-cases.

more here

browserify

Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exports variables. We can even require other modules using the require function, and if we omit the relative path it’ll resolve to the module in the node_modules directory.

more here


2) Task runners

gulp and grunt are task runners, basically what they do, creating tasks and run them whenever you want, for example you install a plugin to minify your CSS and then run it each time to do minifying, more details about each:

gulp

gulp.js is an open-source JavaScript toolkit by Fractal Innovations and the open source community at GitHub, used as a streaming build system in front-end web development. It is a task runner built on Node.js and Node Package Manager (npm), used for automation of time-consuming and repetitive tasks involved in web development like minification, concatenation, cache busting, unit testing, linting, optimization etc. gulp uses a code-over-configuration approach to define its tasks and relies on its small, single-purposed plugins to carry them out. gulp ecosystem has 1000+ such plugins made available to choose from.

more here

grunt

Grunt is a JavaScript task runner, a tool used to automatically perform frequently used tasks such as minification, compilation, unit testing, linting, etc. It uses a command-line interface to run custom tasks defined in a file (known as a Gruntfile). Grunt was created by Ben Alman and is written in Node.js. It is distributed via npm. Presently, there are more than five thousand plugins available in the Grunt ecosystem.

more here


3) Package managers

package managers, what they do is managing plugins you need in your application and install them for you through github etc using package.json, very handy to update you modules, install them and sharing your app across, more details for each:

npm

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public packages, called the npm registry. The registry is accessed via the client, and the available packages can be browsed and searched via the npm website.

more here

bower

Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies. To get started, Bower works by fetching and installing packages from all over, taking care of hunting, finding, downloading, and saving the stuff you’re looking for. Bower keeps track of these packages in a manifest file, bower.json.

more here

and the most recent package manager that shouldn't be missed, it's young and fast in real work environment compare to npm which I was mostly using before, for reinstalling modules, it do double checks the node_modules folder to check the existence of the module, also seems installing the modules takes less time:

yarn

Yarn is a package manager for your code. It allows you to use and share code with other developers from around the world. Yarn does this quickly, securely, and reliably so you don’t ever have to worry.

Yarn allows you to use other developers’ solutions to different problems, making it easier for you to develop your software. If you have problems, you can report issues or contribute back, and when the problem is fixed, you can use Yarn to keep it all up to date.

Code is shared through something called a package (sometimes referred to as a module). A package contains all the code being shared as well as a package.json file which describes the package.

more here


How to select distinct query using symfony2 doctrine query builder?

Just open your repository file and add this new function, then call it inside your controller:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

Then within your controller:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

Good luck!

Trim last character from a string

In .NET 5 / C# 8:

You can write the code marked as the answer as:

public static class StringExtensions
{
    public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}

However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:

    public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];

A quick explanation for the new stuff in C# 8:

The ^ is called the "index from end operator". The .. is called the "range operator". ^1 is a shortcut for arr.length - 1. You can get all items after the first character of an array with arr[1..] or all items before the last with arr[..^1]. These are just a few quick examples. For more information, see https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8, "Indices and ranges" section.

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

How to install multiple python packages at once using pip

Complementing the other answers, you can use the option --no-cache-dir to disable caching in pip. My virtual machine was crashing when installing many packages at once with pip install -r requirements.txt. What solved for me was:

pip install --no-cache-dir -r requirements.txt

Replace all occurrences of a String using StringBuilder?

Here is an in place replaceAll that will modify the passed in StringBuilder. I thought that I would post this as I was looking to do replaceAll with out creating a new String.

public static void replaceAll(StringBuilder sb, Pattern pattern, String replacement) {
    Matcher m = pattern.matcher(sb);
    while(m.find()) {
        sb.replace(m.start(), m.end(), replacement);
    }
}

I was shocked how simple the code to do this was (for some reason I thought changing the StringBuilder while using the matcher would throw of the group start/end but it does not).

This is probably faster than the other regex answers because the pattern is already compiled and your not creating a new String but I didn't do any benchmarking.

Why doesn't Java offer operator overloading?

Assuming you wanted to overwrite the previous value of the object referred to by a, then a member function would have to be invoked.

Complex a, b, c;
// ...
a = b.add(c);

In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and copy the resultant value from the temporary object into the existing object a.

However, in Java, operator= doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named Complex, assignment means to copy a reference to an existing value.

Consider instead:

b.set(1, 0); // initialize to real number '1'
a = b; 
b.set(2, 0);
assert( !a.equals(b) ); // this assertion will fail

In C++, this copies the value, so the comparison will result not-equal. In Java, operator= performs reference copy, so a and b are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.

The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- operator+ would likely deal with values and objects, but operator= is already implemented to deal with references.

In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on Complex, operator= and operator== are both working on values -- copying values and comparing values respectively.

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

Changing the text on a label

Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar

If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.

There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.

text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
                                                                    ^^^^^^^^^^^^^^^^^
  def depositCallBack(self,event):
      text.set('change the value')

What does "var" mean in C#?

  • As the name suggested, var is variable without any data type.
  • If you don't know which type of data will be returned by any method, such cases are good for using var.
  • var is Implicit type which means system will define the data type itself. The compiler will infer its type based on the value to the right of the "=" operator.
  • int/string etc. are the explicit types as it is defined by you explicitly.
  • Var can only be defined in a method as a local variable
  • Multiple vars cannot be declared and initialized in a single statement. For example, var i=1, j=2; is invalid.
int i = 100;// explicitly typed 
var j = 100; // implicitly typed

Rails: How does the respond_to block work?

The meta-programming behind responder registration (see Parched Squid's answer) also allows you to do nifty stuff like this:

def index
  @posts = Post.all

  respond_to do |format|
    format.html  # index.html.erb
    format.json  { render :json => @posts }
    format.csv   { render :csv => @posts }
    format.js
  end
end

The csv line will cause to_csv to be called on each post when you visit /posts.csv. This makes it easy to export data as CSV (or any other format) from your rails site.

The js line will cause a javascript file /posts.js (or /posts.js.coffee) to be rendered/executed. I've found that to be a light-weight way to create an Ajax enabled site using jQuery UI pop-ups.

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

Convert date time string to epoch in Bash

What you're looking for is date --date='06/12/2012 07:21:22' +"%s". Keep in mind that this assumes you're using GNU coreutils, as both --date and the %s format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.

Consult the appropriate manual page for other versions of date.

Note: bash --date and -d option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy or yyyy-mm-dd, not in UK, EU, or any other format.

How do I auto size columns through the Excel interop objects?

Add this at your TODO point:

aRange.Columns.AutoFit();

How to get DropDownList SelectedValue in Controller in MVC

Simple solution not sure if this has been suggested or not. This also may not work for some things. That being said this is the simple solution below.

new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}

List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });

@Html.DropDownList("InvoiceStatus", InvoiceStatusDD)

You can also do something like this for a database driven select list. you will need to set selected in your controller

@Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")

Something like this but better solutions exist this is just one method.

foreach (CountryModel item in CountryModel.GetCountryList())
    {
        if (item.CountryPhoneCode.Trim() != "974")
        {
            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });

        }
        else {


            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });

        }
    }

Read and write into a file using VBScript

You could open two textstreams, one for reading

Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)

and one for appending

Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)

The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.

Undefined or null for AngularJS

You can always add it exactly for your application

angular.isUndefinedOrNull = function(val) {
    return angular.isUndefined(val) || val === null 
}

How to mark-up phone numbers?

RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.

MongoDB or CouchDB - fit for production?

I am using CouchDB in production. Currently it stores all those 'optional' fields that weren't in the original DB schema. And right now I am thinking about moving all data to CouchDB.

It's quite a risky step, I admit. Firstly, because it's not v1.0 yet. And secondly, because it is drivespace-hungry. By my calculations, CouchDB file (with indexes) is ~30 times larger than MySQL database with the same rows. But I am pretty sure it will work out just fine.

VB.NET - How to move to next item a For Each Loop?

Only the "Continue For" is an acceptable standard (the rest leads to "spaghetti code").

At least with "continue for" the programmer knows the code goes directly to the top of the loop.

For purists though, something like this is best since it is pure "non-spaghetti" code.

Dim bKeepGoing as Boolean 
For Each I As Item In Items
  bKeepGoing = True
  If I = x Then
    bKeepGoing = False
  End If
  if bKeepGoing then
    ' Do something
  endif
Next

For ease of coding though, "Continue For" is OK. (Good idea to comment it though).

Using "Continue For"

For Each I As Item In Items
  If I = x Then
    Continue For   'skip back directly to top of loop
  End If
  ' Do something
Next

How can I select records ONLY from yesterday?

This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today

SELECT  * 
FROM 
WHERE date(tran_date) = CURRENT_DATE()

Yesterday

SELECT  * 
FROM yourtable 
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)

process.waitFor() never returns

For the same reason you can also use inheritIO() to map Java console with external app console like:

ProcessBuilder pb = new ProcessBuilder(appPath, arguments);

pb.directory(new File(appFile.getParent()));
pb.inheritIO();

Process process = pb.start();
int success = process.waitFor();

Python's time.clock() vs. time.time() accuracy?

Others have answered re: time.time() vs. time.clock().

However, if you're timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the timeit module.

An attempt was made to access a socket in a way forbidden by its access permissions

If You need to access SQL server on hostgator remotely using SSMS, you need to white list your IP in hostgator. Usually it takes 1 hour to open port for the whitelisted IP

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

How can I set a proxy server for gem?

You need to add http_proxy and https_proxy environment variables as described here.

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

How can I remove text within parentheses with a regex?

If you can stand to use sed (possibly execute from within your program, it'd be as simple as:

sed 's/(.*)//g'

Global variables in Java

public class GlobalImpl {   

 public static int global = 5;

}

you can call anywhere you want:

GlobalImpl.global // 5

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I created a small application which had similar functionality

MainActivity

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.open,
                R.string.close
        )

        {
            public void onDrawerClosed(View view)
            {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }

            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
                syncState();
            }
        };
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //Set the custom toolbar
        if (toolbar != null){
            setSupportActionBar(toolbar);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        actionBarDrawerToggle.syncState();
    }
}

My XML of that Activity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    android:id="@+id/drawer"
    >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <include layout="@layout/toolbar_custom"/>
    </FrameLayout>
    <!-- The navigation drawer -->
    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#457C50"/>


</android.support.v4.widget.DrawerLayout>

My Custom Toolbar XML

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

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimaryDark">
    <TextView android:text="U titel"
        android:textAppearance="@android:style/TextAppearance.Theme"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v7.widget.Toolbar>

My Theme Style

<resources>
    <style name="AppTheme" parent="Base.Theme.AppCompat"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDarker</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

    <color name="primary">#457C50</color>
    <color name="primaryDarker">#580C0C</color>
</resources>

My Styles in values-v21

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

How do I make a textbox that only accepts numbers?

i like terse code

    private void xmm_textbox_KeyPress(object sender, KeyPressEventArgs e) {
        double x;
        e.Handled = !double.TryParse(((TextBox)sender).Text, out x);
    }

java howto ArrayList push, pop, shift, and unshift

ArrayList is unique in its naming standards. Here are the equivalencies:

Array.push    -> ArrayList.add(Object o); // Append the list
Array.pop     -> ArrayList.remove(int index); // Remove list[index]
Array.shift   -> ArrayList.remove(0); // Remove first element
Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list

Note that unshift does not remove an element, but instead adds one to the list. Also note that corner-case behaviors are likely to be different between Java and JS, since they each have their own standards.

Python class inherits object

History from Learn Python the Hard Way:

Python's original rendition of a class was broken in many serious ways. By the time this fault was recognized it was already too late, and they had to support it. In order to fix the problem, they needed some "new class" style so that the "old classes" would keep working but you can use the new more correct version.

They decided that they would use a word "object", lowercased, to be the "class" that you inherit from to make a class. It is confusing, but a class inherits from the class named "object" to make a class but it's not an object really its a class, but don't forget to inherit from object.

Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object class or from another class that inherited from object:

class NewStyle(object):
    pass

Another example is:

class AnotherExampleOfNewStyle(NewStyle):
    pass

While an old-style base class looks like this:

class OldStyle():
    pass

And an old-style child class looks like this:

class OldStyleSubclass(OldStyle):
    pass

You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2

SQLite - getting number of rows in a database

If you want to use the MAX(id) instead of the count, after reading the comments from Pax then the following SQL will give you what you want

SELECT COALESCE(MAX(id)+1, 0) FROM words

How to change fonts in matplotlib (python)?

You can also use rcParams to change the font family globally.

 import matplotlib.pyplot as plt
 plt.rcParams["font.family"] = "cursive"
 # This will change to your computer's default cursive font

The list of matplotlib's font family arguments is here.

Read the package name of an Android APK

You get the package name programmatically using :

packageManager.getPackageArchiveInfo(apkFilePath, 0)?.packageName

Export specific rows from a PostgreSQL table as INSERT SQL script

I tried to write a procedure doing that, based on @PhilHibbs codes, on a different way. Please have a look and test.

 CREATE OR REPLACE FUNCTION dump(IN p_schema text, IN p_table text, IN p_where text)
   RETURNS setof text AS
 $BODY$
 DECLARE
     dumpquery_0 text;
     dumpquery_1 text;
     selquery text;
     selvalue text;
     valrec record;
     colrec record;
 BEGIN

     -- ------ --
     -- GLOBAL --
     --   build base INSERT
     --   build SELECT array[ ... ]
     dumpquery_0 := 'INSERT INTO ' ||  quote_ident(p_schema) || '.' || quote_ident(p_table) || '(';
     selquery    := 'SELECT array[';

     <<label0>>
     FOR colrec IN SELECT table_schema, table_name, column_name, data_type
                   FROM information_schema.columns
                   WHERE table_name = p_table and table_schema = p_schema
                   ORDER BY ordinal_position
     LOOP
         dumpquery_0 := dumpquery_0 || quote_ident(colrec.column_name) || ',';
         selquery    := selquery    || 'CAST(' || quote_ident(colrec.column_name) || ' AS TEXT),';
     END LOOP label0;

     dumpquery_0 := substring(dumpquery_0 ,1,length(dumpquery_0)-1) || ')';
     dumpquery_0 := dumpquery_0 || ' VALUES (';
     selquery    := substring(selquery    ,1,length(selquery)-1)    || '] AS MYARRAY';
     selquery    := selquery    || ' FROM ' ||quote_ident(p_schema)||'.'||quote_ident(p_table);
     selquery    := selquery    || ' WHERE '||p_where;
     -- GLOBAL --
     -- ------ --

     -- ----------- --
     -- SELECT LOOP --
     --   execute SELECT built and loop on each row
     <<label1>>
     FOR valrec IN  EXECUTE  selquery
     LOOP
         dumpquery_1 := '';
         IF not found THEN
             EXIT ;
         END IF;

         -- ----------- --
         -- LOOP ARRAY (EACH FIELDS) --
         <<label2>>
         FOREACH selvalue in ARRAY valrec.MYARRAY
         LOOP
             IF selvalue IS NULL
             THEN selvalue := 'NULL';
             ELSE selvalue := quote_literal(selvalue);
             END IF;
             dumpquery_1 := dumpquery_1 || selvalue || ',';
         END LOOP label2;
         dumpquery_1 := substring(dumpquery_1 ,1,length(dumpquery_1)-1) || ');';
         -- LOOP ARRAY (EACH FIELD) --
         -- ----------- --

         -- debug: RETURN NEXT dumpquery_0 || dumpquery_1 || ' --' || selquery;
         -- debug: RETURN NEXT selquery;
         RETURN NEXT dumpquery_0 || dumpquery_1;

     END LOOP label1 ;
     -- SELECT LOOP --
     -- ----------- --

 RETURN ;
 END
 $BODY$
   LANGUAGE plpgsql VOLATILE;

And then :

-- for a range
SELECT dump('public', 'my_table','my_id between 123456 and 123459'); 
-- for the entire table
SELECT dump('public', 'my_table','true');

tested on my postgres 9.1, with a table with mixed field datatype (text, double, int,timestamp without time zone, etc).

That's why the CAST in TEXT type is needed. My test run correctly for about 9M lines, looks like it fail just before 18 minutes of running.

ps : I found an equivalent for mysql on the WEB.

Can gcc output C code after preprocessing?

-save-temps

This is another good option to have in mind:

gcc -save-temps -c -o main.o main.c

main.c

#define INC 1

int myfunc(int i) {
    return i + INC;
}

and now, besides the normal output main.o, the current working directory also contains the following files:

  • main.i is the desired prepossessed file containing:

    # 1 "main.c"
    # 1 "<built-in>"
    # 1 "<command-line>"
    # 31 "<command-line>"
    # 1 "/usr/include/stdc-predef.h" 1 3 4
    # 32 "<command-line>" 2
    # 1 "main.c"
    
    
    int myfunc(int i) {
        return i + 1;
    }
    
  • main.s is a bonus :-) and contains the generated assembly:

        .file   "main.c"
        .text
        .globl  myfunc
        .type   myfunc, @function
    myfunc:
    .LFB0:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        movl    %edi, -4(%rbp)
        movl    -4(%rbp), %eax
        addl    $1, %eax
        popq    %rbp
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
    .LFE0:
        .size   myfunc, .-myfunc
        .ident  "GCC: (Ubuntu 8.3.0-6ubuntu1) 8.3.0"
        .section    .note.GNU-stack,"",@progbits
    

If you want to do it for a large number of files, consider using instead:

 -save-temps=obj

which saves the intermediate files to the same directory as the -o object output instead of the current working directory, thus avoiding potential basename conflicts.

The advantage of this option over -E is that it is easy to add it to any build script, without interfering much in the build itself.

Another cool thing about this option is if you add -v:

gcc -save-temps -c -o main.o -v main.c

it actually shows the explicit files being used instead of ugly temporaries under /tmp, so it is easy to know exactly what is going on, which includes the preprocessing / compilation / assembly steps:

/usr/lib/gcc/x86_64-linux-gnu/8/cc1 -E -quiet -v -imultiarch x86_64-linux-gnu main.c -mtune=generic -march=x86-64 -fpch-preprocess -fstack-protector-strong -Wformat -Wformat-security -o main.i
/usr/lib/gcc/x86_64-linux-gnu/8/cc1 -fpreprocessed main.i -quiet -dumpbase main.c -mtune=generic -march=x86-64 -auxbase-strip main.o -version -fstack-protector-strong -Wformat -Wformat-security -o main.s
as -v --64 -o main.o main.s

Tested in Ubuntu 19.04 amd64, GCC 8.3.0.

CMake predefined targets

CMake automatically provides a targets for the preprocessed file:

make help

shows us that we can do:

make main.i

and that target runs:

Preprocessing C source to CMakeFiles/main.dir/main.c.i
/usr/bin/cc    -E /home/ciro/bak/hello/main.c > CMakeFiles/main.dir/main.c.i

so the file can be seen at CMakeFiles/main.dir/main.c.i

Tested on cmake 3.16.1.

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

Find the greatest number in a list of numbers

    #Ask for number input
first = int(raw_input('Please type a number: '))
second = int(raw_input('Please type a number: '))
third = int(raw_input('Please type a number: '))
fourth = int(raw_input('Please type a number: '))
fifth = int(raw_input('Please type a number: '))
sixth = int(raw_input('Please type a number: '))
seventh = int(raw_input('Please type a number: '))
eighth = int(raw_input('Please type a number: '))
ninth = int(raw_input('Please type a number: '))
tenth = int(raw_input('Please type a number: '))

    #create a list for variables
sorted_list = [first, second, third, fourth, fifth, sixth, seventh, 
              eighth, ninth, tenth]
odd_numbers = []

    #filter list and add odd numbers to new list
for value in sorted_list:
    if value%2 != 0:
        odd_numbers.append(value)
print 'The greatest odd number you typed was:', max(odd_numbers)

Docker can't connect to docker daemon

If you use gitlab-ci / gitlab-runners you get that error if you don't have permissions to access /var/run/docker.sock.

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

To solve the problem:

sudo usermod -aG docker gitlab-runner

Verify with:

sudo -u gitlab-runner -H docker info

Hope that helps.

Spring Boot JPA - configuring auto reconnect

For those who want to do it from YAML with multiple data sources, there is a great blog post about it: https://springframework.guru/how-to-configure-multiple-data-sources-in-a-spring-boot-application/

It basically says you both need to configure data source properties and datasource like this:

@Bean
@Primary
@ConfigurationProperties("app.datasource.member")
public DataSourceProperties memberDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.member.hikari")
public DataSource memberDataSource() {
    return memberDataSourceProperties().initializeDataSourceBuilder()
            .type(HikariDataSource.class).build();
}

Do not forget to remove @Primary from other datasources.

Cannot find control with name: formControlName in angular reactive form

For me even with [formGroup] the error was popping up "Cannot find control with name:''".
It got fixed when I added ngModel Value to the input box along with formControlName="fileName"

  <form class="upload-form" [formGroup]="UploadForm">
  <div class="row">
    <div class="form-group col-sm-6">
      <label for="fileName">File Name</label>
      <!-- *** *** *** Adding [(ngModel)]="FileName" fixed the issue-->
      <input type="text" class="form-control" id="fileName" [(ngModel)]="FileName"
        placeholder="Enter file name" formControlName="fileName"> 
    </div>
    <div class="form-group col-sm-6">
      <label for="selectedType">File Type</label>
      <select class="form-control" formControlName="selectedType" id="selectedType" 
        (change)="TypeChanged(selectedType)" name="selectedType" disabled="true">
        <option>Type 1</option>
        <option>Type 2</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label for="fileUploader">Select {{selectedType}} file</label>
    <input type="file" class="form-control-file" id="fileUploader" (change)="onFileSelected($event)">
  </div>
  <div class="w-80 text-right mt-3">
    <button class="btn btn-primary mb-2 search-button cancel-button" (click)="cancelUpload()">Cancel</button>
    <button class="btn btn-primary mb-2 search-button" (click)="uploadFrmwrFile()">Upload</button>
  </div>
 </form>

And in the controller

ngOnInit() {
this.UploadForm= new FormGroup({
  fileName: new FormControl({value: this.FileName}),
  selectedType: new FormControl({value: this.selectedType, disabled: true}, Validators.required),
  frmwareFile: new FormControl({value: ['']})
});
}

How can I find the first occurrence of a sub-string in a python string?

verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"

enter code here

print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))

mkdir's "-p" option

The man pages is the best source of information you can find... and is at your fingertips: man mkdir yields this about -p switch:

-p, --parents
    no error if existing, make parent directories as needed

Use case example: Assume I want to create directories hello/goodbye but none exist:

$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$

-p created both, hello and goodbye

This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.

About rlidwka, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html

 Directory permissions

l (lookup)
    Allows one to list the contents of a directory. It does not allow the reading of files. 
i (insert)
    Allows one to create new files in a directory or copy new files to a directory. 
d (delete)
    Allows one to remove files and sub-directories from a directory. 
a (administer)
    Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory. 

File permissions

r (read)
    Allows one to read the contents of file in the directory. 
w (write)
    Allows one to modify the contents of files in a directory and use chmod on them. 
k (lock)
    Allows programs to lock files in a directory. 

Hence rlidwka means: All permissions on.

It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka concept doesn't apply here.

Simplest way to read json from a URL in java

Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

  ObjectMapper mapper = new ObjectMapper(); // just need one
  // Got a Java class that data maps to nicely? If so:
  FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
  // Or: if no class (and don't need one), just map to Map.class:
  Map<String,Object> map = mapper.readValue(url, Map.class);

And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);

Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

How to manage startActivityForResult on Android?

From your FirstActivity call the SecondActivity using startActivityForResult() method

For example:

int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);

In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

For example: In SecondActivity if you want to send back data:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don't want to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

Now in your FirstActivity class write following code for the onActivityResult() method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult

To implement passing data between two activities in much better way in Kotlin please go through this link 'A better way to pass data between Activities'

Can I have an IF block in DOS batch file?

I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.

    if "%COPYTOOL%" equ "R" (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    %TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    call %TOOLPATH%  "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
)

Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.

Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Delete all data rows from an Excel table (apart from the first)

Your code can be narrowed down to

Sub DeleteTableRows(ByRef Table As ListObject)
    On Error Resume Next
    '~~> Clear Header Row `IF` it exists
    Table.DataBodyRange.Rows(1).ClearContents
    '~~> Delete all the other rows `IF `they exist
    Table.DataBodyRange.Offset(1, 0).Resize(Table.DataBodyRange.Rows.Count - 1, _
    Table.DataBodyRange.Columns.Count).Rows.Delete
    On Error GoTo 0
End Sub

Edit:

On a side note, I would add proper error handling if I need to intimate the user whether the first row or the other rows were deleted or not

sys.argv[1], IndexError: list index out of range

I've done some research and it seems that the sys.argv might require an argument at the command line when running the script

Not might, but definitely requires. That's the whole point of sys.argv, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError.

Although the code uses try/except to trap some errors, the offending statement occurs in the first line.

So the script needs a directory name, and you can test if there is one by looking at len(sys.argv) and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.

To print an error and exit when the argument is missing, add this line before the first use of sys.argv:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

sys.argv[0] always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...

see also:

How do I get the SharedPreferences from a PreferenceActivity in Android?

Try following source code it worked for me

//Fetching id from shared preferences
    SharedPreferences sharedPreferences;
    sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

What I did:

      <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>

and

xsi:schemaLocation="
        http://www.springframework.org/schema/security 
        http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

works perfectlly. More Baeldung

Scala Doubles, and Precision

You may use implicit classes:

import scala.math._

object ExtNumber extends App {
  implicit class ExtendedDouble(n: Double) {
    def rounded(x: Int) = {
      val w = pow(10, x)
      (n * w).toLong.toDouble / w
    }
  }

  // usage
  val a = 1.23456789
  println(a.rounded(2))
}

Convert String with Dot or Comma as decimal separator to number in JavaScript

All the other solutions require you to know the format in advance. I needed to detect(!) the format in every case and this is what I end up with.

function detectFloat(source) {
    let float = accounting.unformat(source);
    let posComma = source.indexOf(',');
    if (posComma > -1) {
        let posDot = source.indexOf('.');
        if (posDot > -1 && posComma > posDot) {
            let germanFloat = accounting.unformat(source, ',');
            if (Math.abs(germanFloat) > Math.abs(float)) {
                float = germanFloat;
            }
        } else {
            // source = source.replace(/,/g, '.');
            float = accounting.unformat(source, ',');
        }
    }
    return float;
}

This was tested with the following cases:

        const cases = {
            "0": 0,
            "10.12": 10.12,
            "222.20": 222.20,
            "-222.20": -222.20,
            "+222,20": 222.20,
            "-222,20": -222.20,
            "-2.222,20": -2222.20,
            "-11.111,20": -11111.20,
        };

Suggestions welcome.

Count the number occurrences of a character in a string

spam = 'have a nice day'
var = 'd'


def count(spam, var):
    found = 0
    for key in spam:
        if key == var:
            found += 1
    return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))

How do you setLayoutParams() for an ImageView?

If you're changing the layout of an existing ImageView, you should be able to simply get the current LayoutParams, change the width/height, and set it back:

android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);

I don't know if that's your goal, but if it is, this is probably the easiest solution.

Colorized grep -- viewing the entire file with highlighted matches

another dirty way:

grep -A80 -B80 --color FIND_THIS IN_FILE

I did an

alias grepa='grep -A80 -B80 --color'

in bashrc.

useState set method not reflecting change immediately

You can solve it by using the useRef hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.

See this example:

var [state,setState,ref]=useStateRef(0)

It works exactly like useState but in addition, it gives you the current state under ref.current

Learn more:

Use of Greater Than Symbol in XML

CDATA is a better general solution.

how to convert JSONArray to List of Object using camel-jackson

/*
 It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
Gson gson = new Gson();
 try {
    BufferedReader br = new BufferedReader(new FileReader(
            "C:\\Temp\\jsonFileArr.json"));
    JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement str = jsonArray.get(i);
        Usuario obj = gson.fromJson(str, Usuario.class);
        //use the add method from the list and returns it.
        System.out.println(obj);
        System.out.println(str);
        System.out.println("-------");
    }
 } catch (IOException e) {
    e.printStackTrace();
 }
}

Effectively use async/await with ASP.NET Web API

I would change your service layer to:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    return Task.Run(() =>
    {
        return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
    }      
}

as you have it, you are still running your _service.Process call synchronously, and gaining very little or no benefit from awaiting it.

With this approach, you are wrapping the potentially slow call in a Task, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task.

how to use List<WebElement> webdriver

Try the following code:

//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
  System.out.println(e.getText());
}

It will returns with the whole content of the <li> tags, like:

<a class="extra">Vše</a> (950)</li>

But you can easily get the number now from it, for example by using split() and/or substring().

How to set TLS version on apache HttpClient

The solution is:

SSLContext sslContext = SSLContexts.custom()
    .useTLS()
    .build();

SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(
    sslContext,
    new String[]{"TLSv1", "TLSv1.1"},   
    null,
    BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

httpClient = HttpClients.custom()
    .setSSLSocketFactory(f)
    .build();

This requires org.apache.httpcomponents.httpclient 4.3.x though.

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

Can't access RabbitMQ web management interface after fresh install

Something that just happened to me and caused me some headaches:

I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).

The script had several of those "code" blocks:

rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"

Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.

Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.

... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:

rabbitmqctl change_password test test

(Another solution would have been to delete all users and then call the script again)

Angular 2.0 and Modal Dialog

Now available as a NPM package

angular-custom-modal


@Stephen Paul continuation...

  • Angular 2 and up Bootstrap css (animation is preserved)
  • NO JQuery
  • NO bootstrap.js
  • Supports custom modal content
  • Support for multiple modals on top of each other.
  • Moduralized
  • Disable scroll when modal is open
  • Modal gets destroyed when navigating away.
  • Lazy content initialization, which gets ngOnDestroy(ed) when the modal is exited.
  • Parent scrolling disabled when modal is visible

Lazy content initialization

Why?

In some cases you might not want to modal to retain its status after having been closed, but rather restored to the initial state.

Original modal issue

Passing the content straightforward into the view actually generates initializes it even before the modal gets it. The modal doesn't have a way to kill such content even if using a *ngIf wrapper.

Solution

ng-template. ng-template doesn't render until ordered to do so.

my-component.module.ts

...
imports: [
  ...
  ModalModule
]

my-component.ts

<button (click)="reuseModal.open()">Open</button>
<app-modal #reuseModal>
  <ng-template #header></ng-template>
  <ng-template #body>
    <app-my-body-component>
      <!-- This component will be created only when modal is visible and will be destroyed when it's not. -->
    </app-my-body-content>
    <ng-template #footer></ng-template>
</app-modal>

modal.component.ts

export class ModalComponent ... {
  @ContentChild('header') header: TemplateRef<any>;
  @ContentChild('body') body: TemplateRef<any>;
  @ContentChild('footer') footer: TemplateRef<any>;
 ...
}

modal.component.html

<div ... *ngIf="visible">
  ...
  <div class="modal-body">
    ng-container *ngTemplateOutlet="body"></ng-container>
  </div>

References

I have to say that it wouldn't have been possible without the excellent official and community documentation around the net. It might help some of you too to understand better how ng-template, *ngTemplateOutlet and @ContentChild work.

https://angular.io/api/common/NgTemplateOutlet
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e

Full copy-paste solution

modal.component.html

<div
  (click)="onContainerClicked($event)"
  class="modal fade"
  tabindex="-1"
  [ngClass]="{'in': visibleAnimate}"
  [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"
  *ngIf="visible">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <ng-container *ngTemplateOutlet="header"></ng-container>
        <button class="close" data-dismiss="modal" type="button" aria-label="Close" (click)="close()">×</button>
      </div>
      <div class="modal-body">
        <ng-container *ngTemplateOutlet="body"></ng-container>
      </div>
      <div class="modal-footer">
        <ng-container *ngTemplateOutlet="footer"></ng-container>
      </div>
    </div>
  </div>
</div>

modal.component.ts

/**
 * @Stephen Paul https://stackoverflow.com/a/40144809/2013580
 * @zurfyx https://stackoverflow.com/a/46949848/2013580
 */
import { Component, OnDestroy, ContentChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'app-modal',
  templateUrl: 'modal.component.html',
  styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnDestroy {
  @ContentChild('header') header: TemplateRef<any>;
  @ContentChild('body') body: TemplateRef<any>;
  @ContentChild('footer') footer: TemplateRef<any>;

  public visible = false;
  public visibleAnimate = false;

  ngOnDestroy() {
    // Prevent modal from not executing its closing actions if the user navigated away (for example,
    // through a link).
    this.close();
  }

  open(): void {
    document.body.style.overflow = 'hidden';

    this.visible = true;
    setTimeout(() => this.visibleAnimate = true, 200);
  }

  close(): void {
    document.body.style.overflow = 'auto';

    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 100);
  }

  onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.close();
    }
  }
}

modal.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ModalComponent } from './modal.component';

@NgModule({
  imports: [
    CommonModule,
  ],
  exports: [ModalComponent],
  declarations: [ModalComponent],
  providers: [],
})
export class ModalModule { }

Visual Studio Code includePath

For Mac users who only have Command Line Tools instead of Xcode, check the /Library/Developer/CommandLineTools directory, for example::

"configurations": [{
    "name": "Mac",
    "includePath": [
            "/usr/local/include",
            // others, e.g.: "/usr/local/opt/ncurses/include",
            "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include",
            "${workspaceFolder}/**"
    ]
}]

You probably need to adjust the path if you have different version of Command Line Tools installed.

Note: You can also open/generate the c_cpp_properties.json file via the C/Cpp: Edit Configurations command from the Command Palette (??P).

Converting a list to a set changes element order

You can remove the duplicated values and keep the list order of insertion with one line of code, Python 3.8.2

mylist = ['b', 'b', 'a', 'd', 'd', 'c']


results = list({value:"" for value in mylist})

print(results)

>>> ['b', 'a', 'd', 'c']

results = list(dict.fromkeys(mylist))

print(results)

>>> ['b', 'a', 'd', 'c']

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

If you are on Linux then make sure your File name must match with the string passed in the load model methods the first argument.

$this->load->model('Order_Model','order_model');

You can use the second argument using that you can call methods from your model and it will work on Linux and windows as well

$result = $this->order_model->get_order_details($orderID);

Index of Currently Selected Row in DataGridView

try this it will work...it will give you the index of selected row index...

int rowindex = dataGridView1.CurrentRow.Index;
MessageBox.Show(rowindex.ToString());

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I set up a simple 3-column range on Sheet1 with Country, City, and Language in columns A, B, and C. The following code autofilters the range and then pastes only one of the columns of autofiltered data to another sheet. You should be able to modify this for your purposes:

Sub CopyPartOfFilteredRange()
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim filterRange As Range
    Dim copyRange As Range
    Dim lastRow As Long

    Set src = ThisWorkbook.Sheets("Sheet1")
    Set tgt = ThisWorkbook.Sheets("Sheet2")

    ' turn off any autofilters that are already set
    src.AutoFilterMode = False

    ' find the last row with data in column A
    lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row

    ' the range that we are auto-filtering (all columns)
    Set filterRange = src.Range("A1:C" & lastRow)

    ' the range we want to copy (only columns we want to copy)
    ' in this case we are copying country from column A
    ' we set the range to start in row 2 to prevent copying the header
    Set copyRange = src.Range("A2:A" & lastRow)

    ' filter range based on column B
    filterRange.AutoFilter field:=2, Criteria1:="Rio de Janeiro"

    ' copy the visible cells to our target range
    ' note that you can easily find the last populated row on this sheet
    ' if you don't want to over-write your previous results
    copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A1")

End Sub

Note that by using the syntax above to copy and paste, nothing is selected or activated (which you should always avoid in Excel VBA) and the clipboard is not used. As a result, Application.CutCopyMode = False is not necessary.

creating charts with angularjs

To collect more useful resources here:

As mentioned before D3.js is definitely the best visualization library for charts. To use it in AngularJS I developed angular-chart. It is an easy to use directive which connects D3.js with the AngularJS 2-Way-DataBinding. This way the chart gets automatically updated whenever you change the configuration options and at the same time the charts saves its state (zoom level, ...) to make it available in the AngularJS world.

Check out the examples to get convinced.

MySQL LEFT JOIN Multiple Conditions

Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result

SELECT a.* FROM a 
    LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']} 
    WHERE a.keyword LIKE '%".$keyword."%' 
    GROUP BY group_id

How to select multiple files with <input type="file">?

The whole thing should look like:

<form enctype='multipart/form-data' method='POST' action='submitFormTo.php'> 
    <input type='file' name='files[]' multiple />
    <button type='submit'>Submit</button>
</form>

Make sure you have the enctype='multipart/form-data' attribute in your <form> tag, or you can't read the files on the server side after submission!

What is the difference between the dot (.) operator and -> in C++?

It's simple, whenever you see

 x->y

know it is the same as

 (*x).y

How to solve a timeout error in Laravel 5

In Laravel:

Add set_time_limit(0) line on top of query.

set_time_limit(0);

$users = App\User::all();

It helps you in different large queries but you should need to improve query optimise.

How to perform keystroke inside powershell?

If I understand correctly, you want PowerShell to send the ENTER keystroke to some interactive application?

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('~')

If that interactive application is a PowerShell script, just use whatever is in the title bar of the PowerShell window as the argument to AppActivate (by default, the path to powershell.exe). To avoid ambiguity, you can have your script retitle its own window by using the title 'new window title' command.

A few notes:

  • The tilde (~) represents the ENTER keystroke. You can also use {ENTER}, though they're not identical - that's the keypad's ENTER key. A complete list is available here: http://msdn.microsoft.com/en-us/library/office/aa202943%28v=office.10%29.aspx.
  • The reason for the Sleep 1 statement is to wait 1 second because it takes a moment for the window to activate, and if you invoke SendKeys immediately, it'll send the keys to the PowerShell window, or to nowhere.
  • Be aware that this can be tripped up, if you type anything or click the mouse during the second that it's waiting, preventing to window you activate with AppActivate from being active. You can experiment with reducing the amount of time to find the minimum that's reliably sufficient on your system (Sleep accepts decimals, so you could try .5 for half a second). I find that on my 2.6 GHz Core i7 Win7 laptop, anything less than .8 seconds has a significant failure rate. I use 1 second to be safe.
  • IMPORTANT WARNING: Be extra careful if you're using this method to send a password, because activating a different window between invoking AppActivate and invoking SendKeys will cause the password to be sent to that different window in plain text!

Sometimes wscript.shell's SendKeys method can be a little quirky, so if you run into problems, replace the fourth line above with this:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('~');

'tuple' object does not support item assignment

You have misspelt the second pixels as pixel. The following works:

pixels = [1,2,3]
pixels[0] = 5

It appears that due to the typo you were trying to accidentally modify some tuple called pixel, and in Python tuples are immutable. Hence the confusing error message.

Making PHP var_dump() values display one line per value

I didn't wanna stop using var_dump($variable);die(); and using pre tags and loops seems overkill to me, so since I am looking at the dump in a browser, I just right click the page and choose Inspect (I use Chrome). The Elements section of the Developer Tools show the variable in a very readable format.

Connection refused on docker container

If you are using Docker toolkit on window 10 home you will need to access the webpage through docker-machine ip command. It is generally 192.168.99.100:

It is assumed that you are running with publish command like below.

docker run -it -p 8080:8080 demo

With Window 10 pro version you can access with localhost or corresponding loopback 127.0.0.1:8080 etc (Tomcat or whatever you wish). This is because you don't have a virtual box there and docker is running directly on Window Hyper V and loopback is directly accessible.

Verify the hosts file in window for any digression. It should have 127.0.0.1 mapped to localhost

Print list without brackets in a single row

','.join(list) will work only if all the items in the list are strings. If you are looking to convert a list of numbers to a comma separated string. such as a = [1, 2, 3, 4] into '1,2,3,4' then you can either

str(a)[1:-1] # '1, 2, 3, 4'

or

str(a).lstrip('[').rstrip(']') # '1, 2, 3, 4'

although this won't remove any nested list.

To convert it back to a list

a = '1,2,3,4'
import ast
ast.literal_eval('['+a+']')
#[1, 2, 3, 4]

alert() not working in Chrome

Here is a snippet that does not need ajQuery and will enable alerts in a disabled iframe (like on codepen)

for (var i = 0; i < document.getElementsByTagName('iframe').length; i++) {
    document.getElementsByTagName('iframe')[i].setAttribute('sandbox','allow-modals');
}

Here is a codepen demo working with an alert() after this fix as well: http://codepen.io/nicholasabrams/pen/vNpoBr?editors=001

How does ApplicationContextAware work in Spring?

ApplicationContextAware Interface ,the current application context, through which you can invoke the spring container services. We can get current applicationContext instance injected by below method in the class

public void setApplicationContext(ApplicationContext context) throws BeansException.

How to test that no exception is thrown?

This may not be the best way but it definitely makes sure that exception is not thrown from the code block that is being tested.

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class AssertionExample {

    @Test
    public void testNoException(){
        assertNoException();
    }    

    private void assertException(){
        Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
    }

    private void assertNoException(){
        Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
    }

    private void doNotThrowException(){
        //This method will never throw exception
    }
}

How to stop Python closing immediately when executed in Microsoft Windows

Put

input('Press ENTER to exit') 

at the end to have it stop.

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

JavaScript check if value is only undefined, null or false

Try like Below

var Boolify = require('node-boolify').Boolify;
if (!Boolify(val)) {
    //your instruction
}

Refer node-boolify

CheckBox in RecyclerView keeps on checking different items

That's an expected behavior. You are not setting your checkbox selected or not. You are selecting one and View holder keeps it selected. You can add a boolean variable into your ObjectIncome object and keep your item's selection status.

You may look at my example. You can do something like that:

public class AdapterTrashIncome extends RecyclerView.Adapter<AdapterTrashIncome.ViewHolder> {

    private ArrayList<ObjectIncome> myItems = new ArrayList<>();

    public AdapterTrashIncome(ArrayList<ObjectIncome> getItems, Context context){
        try {
            mContext = context;
            myItems = getItems;
            }catch (Exception e){
            Log.e(FILE_NAME, "51: " + e.toString());
            e.printStackTrace();
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tvContent;
        public CheckBox cbSelect;

        public ViewHolder(View v) {
            super(v);
            tvContent = (TextView) v.findViewById(R.id.tvContent);
            cbSelect = (CheckBox) v.findViewById(R.id.cbSelect);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final ObjectIncome objIncome = myItems.get(position);
        String content = "<b>lalalla</b>";
        holder.tvContent.setText(Html.fromHtml(content));

        //in some cases, it will prevent unwanted situations
        holder.cbSelect.setOnCheckedChangeListener(null);

        //if true, your checkbox will be selected, else unselected
        holder.cbSelect.setChecked(objIncome.isSelected());

        holder.cbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    //set your object's last status
                    objIncome.setSelected(isChecked);
            }
        });

    }
}

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

Set custom HTML5 required field validation message

Code snippet

Since this answer got very much attention, here is a nice configurable snippet I came up with:

/**
  * @author ComFreek <https://stackoverflow.com/users/603003/comfreek>
  * @link https://stackoverflow.com/a/16069817/603003
  * @license MIT 2013-2015 ComFreek
  * @license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
  * You MUST retain this license header!
  */
(function (exports) {
    function valOrFunction(val, ctx, args) {
        if (typeof val == "function") {
            return val.apply(ctx, args);
        } else {
            return val;
        }
    }

    function InvalidInputHelper(input, options) {
        input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));

        function changeOrInput() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
                input.setCustomValidity("");
            }
        }

        function invalid() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
               input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
            }
        }

        input.addEventListener("change", changeOrInput);
        input.addEventListener("input", changeOrInput);
        input.addEventListener("invalid", invalid);
    }
    exports.InvalidInputHelper = InvalidInputHelper;
})(window);

Usage

jsFiddle

<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
  defaultText: "Please enter an email address!",

  emptyText: "Please enter an email address!",

  invalidText: function (input) {
    return 'The email address "' + input.value + '" is invalid!';
  }
});

More details

  • defaultText is displayed initially
  • emptyText is displayed when the input is empty (was cleared)
  • invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)

You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.

Compatibility

Tested in:

  • Chrome Canary 47.0.2
  • IE 11
  • Microsoft Edge (using the up-to-date version as of 28/08/2015)
  • Firefox 40.0.3
  • Opera 31.0

Old answer

You can see the old revision here: https://stackoverflow.com/revisions/16069817/6

Using an if statement to check if a div is empty

I've encountered this today and the accepted answers did not work for me. Here is how I did it.

if( $('#div-id *').length === 0 ) {
    // your code here...
}

My solution checks if there are any elements inside the div so it would still mark the div empty if there is only text inside it.

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

How to show the last queries executed on MySQL?

You can do the flowing thing for monitoring mysql query logs.

Open mysql configuration file my.cnf

sudo nano /etc/mysql/my.cnf

Search following lines under a [mysqld] heading and uncomment these lines to enable log

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

Restart your mysql server for reflect changes

sudo service mysql start

Monitor mysql server log with following command in terminal

tail -f /var/log/mysql/mysql.log

How to check if an option is selected?

In my case I don't know why selected is always true. So the only way I was able to think up is:

var optionSelected = false;
$( '#select_element option' ).each( function( i, el ) {
    var optionHTMLStr = el.outerHTML;

    if ( optionHTMLStr.indexOf( 'selected' ) > 0 ) {
        optionSelected = true;
        return false;
    }
});

How to make a div 100% height of the browser window

This worked for me:

html, body {
    height: 100%; /* IMPORTANT!!! Stretches viewport to 100% */
}

#wrapper {
    min-height: 100%; /* Minimum height for a modern browser */
    height:auto !important; /* Important rule for a modern browser */
    height:100%; /* Minimum height for Internet Explorer */
    overflow: hidden !important; /* Firefox scroll-bar */
}

Taken from this page.

Summarizing multiple columns with dplyr?

The dplyr package contains summarise_all for this aim:

library(dplyr)
# summarise_all was replaced with the summarise(acrosss(..)) syntax dplyr >=1.00
df %>% group_by(grp) %>% summarise(across(everything(), list(mean)))
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Alternatively, the purrrlyr package provides the same functionality:

library(purrrlyr)
df %>% slice_rows("grp") %>% dmap(mean)
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Also don't forget about data.table (use keyby to sort sort groups):

library(data.table)
setDT(df)[, lapply(.SD, mean), keyby = grp]
#>    grp        a        b        c        d
#> 1:   1 3.079412 2.979412 2.979412 2.914706
#> 2:   2 3.029126 3.038835 2.967638 2.873786
#> 3:   3 2.854701 2.948718 2.951567 3.062678

Let's try to compare performance.

library(dplyr)
library(purrrlyr)
library(data.table)
library(bench)
set.seed(123)
n <- 10000
df <- data.frame(
  a = sample(1:5, n, replace = TRUE), 
  b = sample(1:5, n, replace = TRUE), 
  c = sample(1:5, n, replace = TRUE), 
  d = sample(1:5, n, replace = TRUE), 
  grp = sample(1:3, n, replace = TRUE)
)
dt <- setDT(df)
mark(
  dplyr = df %>% group_by(grp) %>% summarise(across(everything(), list(mean))),
  purrrlyr = df %>% slice_rows("grp") %>% dmap(mean),
  data.table = dt[, lapply(.SD, mean), keyby = grp],
  check = FALSE
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 dplyr        2.81ms   2.85ms      328.        NA     17.3
#> 2 purrrlyr     7.96ms   8.04ms      123.        NA     24.5
#> 3 data.table 596.33µs 707.91µs     1409.        NA     10.3

How do I seed a random class to avoid getting duplicate random values

A good seed generation for me is:

Random rand = new Random(Guid.NewGuid().GetHashCode());

It is very random. The seed is always different because the seed is also random generated.

Change drive in git bash for windows

Just consider your drive as a folder so do cd e:

How do I fix a NoSuchMethodError?

I fixed this problem in Eclipse by renaming a Junit test file.
In my Eclipse work space I have an App project and a Test project.
The Test project has the App project as a required project on the build path.

Started getting the NoSuchMethodError.
Then I realized the class in the Test project had the same name as the class in the App project.

App/  
  src/
     com.example/  
       Projection.java
Test/  
  src/
     com.example/
       Projection.java

After renaming the Test to the correct name "ProjectionTest.java" the exception went away.

startForeground fail after upgrade to Android 8.1

Here is my solution

private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";

private void startForeground() {

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            getApplicationContext(), CHANNEL_ID);

    Notification notification;



        notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
                .setOngoing(true)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Send SMS gateway is running background")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowWhen(true)
                .build();

        NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);

        //All notifications should go through NotificationChannel on Android 26 & above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);

        }
        notificationManager.notify(NOTIFICATION_ID, notification);

    }

Hope it will help :)

Git's famous "ERROR: Permission to .git denied to user"

I am using Mac and the issue is solved by deleting github record from keychain access app: Here is what i did:

  1. Open "Keychain Access.app" (You can find it in Spotlight orLaunchPad)
  2. Select "All items" in Category
  3. Search "git"
  4. Delete every old & strange items Try to Push again and it just WORKED

Above steps are copied from @spyar for the ease.

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

How to fill 100% of remaining height?

This can be done with tables:

<table cellpadding="0" cellspacing="0" width="100%" height="100%">
    <tr height="0%"><td>
        <div id="full">
            <!--contents of 1 -->
        </div>
    </td></tr>
    <tr><td>
        <div id="someid">
            <!--contents of 2 -->
        </div>
    </td></tr>
</table>

Then apply css to make someid fill the remaining space:

#someid {
    height: 100%;
}

Now, I can just hear the angry shouts from the crowd, "Oh noes, he's using tables! Feed him to the lions!" Please hear me out.

Unlike the accepted answer which accomplishes nothing aside from making the container div the full height of the page, this solution makes div #2 fill the remaining space as requested in the question. If you need that second div to fill the full height allotted to it, this is currently the only way to do it.

But feel free to prove me wrong, of course! CSS is always better.

HTML: can I display button text in multiple lines?

This CSS might work for <input type="button" ..:

white-space: normal

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

Update 2021, Bootstrap 5

In bootstrap 5 these classes have been renamed to .float-end and .float-start.

Docs: https://getbootstrap.com/docs/5.0/utilities/float/

Example:

<div class="row">
    <div class="col-12">
       <button class="btn btn-primary float-end">Login</div>
    </div>
</div>

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

How to set layout_weight attribute dynamically from code?

If you already define your view in your layout(xml) file, only want to change the weight programmatically, this way is better

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)   
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);

new a LayoutParams overwrites other params defined in you xml file like margins, or you need to specify all of them in LayoutParams.

Insert line at middle of file with Python?

Below is a slightly awkward solution for the special case in which you are creating the original file yourself and happen to know the insertion location (e.g. you know ahead of time that you will need to insert a line with an additional name before the third line, but won't know the name until after you've fetched and written the rest of the names). Reading, storing and then re-writing the entire contents of the file as described in other answers is, I think, more elegant than this option, but may be undesirable for large files.

You can leave a buffer of invisible null characters ('\0') at the insertion location to be overwritten later:

num_names = 1_000_000    # Enough data to make storing in a list unideal
max_len = 20             # The maximum allowed length of the inserted line
line_to_insert = 2       # The third line is at index 2 (0-based indexing)

with open(filename, 'w+') as file:
    for i in range(line_to_insert):
        name = get_name(i)                    # Returns 'Alfred' for i = 0, etc.
        file.write(F'{i + 1}. {name}\n')

    insert_position = file.tell()             # Position to jump back to for insertion
    file.write('\0' * max_len + '\n')         # Buffer will show up as a blank line

    for i in range(line_to_insert, num_names):
        name = get_name(i)
        file.write(F'{i + 2}. {name}\n')      # Line numbering now bumped up by 1.

# Later, once you have the name to insert...
with open(filename, 'r+') as file:            # Must use 'r+' to write to middle of file 
    file.seek(insert_position)                # Move stream to the insertion line
    name = get_bonus_name()                   # This lucky winner jumps up to 3rd place
    new_line = F'{line_to_insert + 1}. {name}'
    file.write(new_line[:max_len])            # Slice so you don't overwrite next line

Unfortunately there is no way to delete-without-replacement any excess null characters that did not get overwritten (or in general any characters anywhere in the middle of a file), unless you then re-write everything that follows. But the null characters will not affect how your file looks to a human (they have zero width).

jQuery .slideRight effect

Another solution is by using .animate() and appropriate CSS.

e.g.

   $('#mydiv').animate({ marginLeft: "100%"} , 4000);

JS Fiddle

Joda DateTime to Timestamp conversion

It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".

An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).

Their perception is different but the moment is the same.

You can find more details in this answer.

UPDATE

OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".

Let's look at your original question code broken down like this:

// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");

// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));

// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());

I haven't run this code but I am certain it will print true and the same number of milliseconds each time:

System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));

System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());

But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].

In your own answer you are artificially adding an offset and creating a "wrong" time. If you use that timestamp to create another DateTime and print it out it will be offset twice.

// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));

P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.

JUnit Test as proof

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

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


public class WorldTimeTest {
    private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
    private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private TimeZone londonTimeZone;
    private TimeZone newYorkTimeZone;
    private TimeZone sydneyTimeZone;
    private long nowInMillis;
    private Date now;

    public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
        SimpleDateFormat result = new SimpleDateFormat(pattern);
        // Must explicitly set the time zone with "setCalendar()".
        result.setCalendar(Calendar.getInstance(timeZone));
        return result;
    }

    public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
        return createDateFormat(pattern, TimeZone.getDefault());
    }

    public static SimpleDateFormat createDateFormat() throws Exception {
        return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
    }

    public void printSystemInfo() throws Exception {
        final String[] propertyNames = {
                "java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
                "os.name", "os.version", "os.arch",
                "user.language", "user.country", "user.script", "user.variant",
                "user.language.format", "user.country.format", "user.script.format",
                "user.timezone" };

        System.out.println();
        System.out.println("System Information:");
        for (String name : propertyNames) {
            if (name == null || name.length() == 0) {
                continue;
            }
            String value = System.getProperty(name);
            if (value != null && value.length() > 0) {
                System.out.println("  " + name + " = " + value);
            }
        }

        final TimeZone defaultTZ = TimeZone.getDefault();
        final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final int userOffset = TimeZone.getTimeZone(System
                .getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final Locale defaultLocale = Locale.getDefault();

        System.out.println("  default.timezone-offset (hours) = " + userOffset);
        System.out.println("  default.timezone = " + defaultTZ.getDisplayName());
        System.out.println("  default.timezone.id = " + defaultTZ.getID());
        System.out.println("  default.timezone-offset (hours) = " + defaultOffset);
        System.out.println("  default.locale = "
                + defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
                + " (" + defaultLocale.getDisplayLanguage()
                + "," + defaultLocale.getDisplayCountry() + ")");
        System.out.println("  now = " + nowInMillis + " [ms] or "
                + createDateFormat().format(now));
        System.out.println();
    }

    @Before
    public void setUp() throws Exception {
        // Remember this moment.
        now = new Date();
        nowInMillis = now.getTime(); // == System.currentTimeMillis();

        // Print out some system information.
        printSystemInfo();

        // "Europe/London" time zone is DST aware, we'll use fixed offset.
        londonTimeZone = TimeZone.getTimeZone("GMT");
        // The same applies to "America/New York" time zone ...
        newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
        // ... and for the "Australia/Sydney" time zone.
        sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
    }

    @Test
    public void testDateFormatting() throws Exception {
        int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
        Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
        londonCalendar.setTime(now);

        int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
        newYorkCalendar.setTime(now);

        int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
        sydneyCalendar.setTime(now);

        // Check each time zone offset.
        assertThat(londonOffset, equalTo(0));
        assertThat(newYorkOffset, equalTo(-5));
        assertThat(sydneyOffset, equalTo(10));

        // Check that calendars are not equals (due to time zone difference).
        assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
        assertThat(londonCalendar, not(equalTo(sydneyCalendar)));

        // Check if they all point to the same moment in time, in milliseconds.
        assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));

        // Check if they all point to the same moment in time, as Date.
        assertThat(londonCalendar.getTime(), equalTo(now));
        assertThat(newYorkCalendar.getTime(), equalTo(now));
        assertThat(sydneyCalendar.getTime(), equalTo(now));

        // Check if hours are all different (skip local time because
        // this test could be executed in those exact time zones).
        assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
        assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));


        // Display London time in multiple forms.
        SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + londonOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfLondonNoTZ.format(londonCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfLondonWithTZ.format(londonCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + londonCalendar.getTime() + " / " + londonCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
                + " / " + createDateFormat().format(londonCalendar.getTime()));


        // Display New York time in multiple forms.
        SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + newYorkOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
                + " / " + createDateFormat().format(newYorkCalendar.getTime()));


        // Display Sydney time in multiple forms.
        SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
        SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
        System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + sydneyOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfSydneyNoTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfSydneyWithTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
                + " / " + createDateFormat().format(sydneyCalendar.getTime()));
    }

    @Test
    public void testDateParsing() throws Exception {
        // Create date parsers that look for time zone information in a date-time string.
        final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);

        // Create date parsers that ignore time zone information in a date-time string.
        final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);

        // We are looking for the moment this millenium started, the famous Y2K,
        // when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
        // Which of these is the right one?
        // a) "2000-01-01T00:00:00.000-00:00"
        // b) "2000-01-01T00:00:00.000-05:00"
        // c) "2000-01-01T00:00:00.000+10:00"
        // None of them? All of them?
        // For those who guessed it - yes, it is a trick question because we didn't specify
        // the "where" part, or what kind of time (local/global) we are looking for.
        // The first (a) is the local Y2K moment in London, which is at the same time global.
        // The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
        // The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
        // The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
        // The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.

        // These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
        final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
        final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);

        // Check if they all point to the same moment in time.
        // And that parser ignores its own configured time zone and uses the information from the date-time string.
        assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
        assertThat(milleniumInSydney, equalTo(milleniumInLondon));


        // These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
        final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
        final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
        final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
        final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
        final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
        final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
        assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // These are also local Y2K moments, just withouth the time zone information.
        final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
        final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);

        // Check if these are the same as the local moments with time zone information.
        assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
        assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
        assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
        assertThat(midnightInSydney, not(equalTo(midnightInLondon)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // Final check - if Y2K moment is in London ..
        final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
        // .. New York local time would be still 5 hours in 1999 ..
        final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
        // .. and Sydney local time would be 10 hours in 2000.
        final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";

        final String londonTime = londonFormatTZ.format(milleniumInLondon);
        final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
        final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);

        // WHat do you think, will the test pass?
        assertThat(londonTime, equalTo(Y2K_LONDON));
        assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
        assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
    }
}

How to write MySQL query where A contains ( "a" or "b" )

Two options:

  1. Use the LIKE keyword, along with percent signs in the string

    select * from table where field like '%a%' or field like '%b%'.
    

    (note: If your search string contains percent signs, you'll need to escape them)

  2. If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):

    See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Of these, using LIKE is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.

Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.

If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE.

error: function returns address of local variable

Neither malloc or call by reference are needed. You can declare a pointer within the function and set it to the string/array you'd like to return.

Using @Gewure's code as the basis:

char *getStringNoMalloc(void){
    char string[100] = {};
    char *s_ptr = string;

    strcat(string, "bla");
    strcat(string, "/");
    strcat(string, "blub");
    //INSIDE this function "string" is OK
    printf("string : '%s'\n", string);

    return s_ptr; 
}

works perfectly.

With a non-loop version of the code in the original question:

char *foo(int x){    
    char a[1000];
    char *a_ptr = a;
    char *b = "blah";       

    strcpy(a, b);

    return a_ptr;
}

How to sort by two fields in Java?

You can do like this:

List<User> users = Lists.newArrayList(
  new User("Pedro", 12), 
  new User("Maria", 10), 
  new User("Rafael",12)
);

users.sort(
  Comparator.comparing(User::getName).thenComparing(User::getAge)
);

Oracle error : ORA-00905: Missing keyword

If you backup a table in Oracle Database. You try the statement below.

CREATE TABLE name_table_bk
AS
SELECT *
  FROM name_table;

I am using Oracle Database 12c.

How to send data with angularjs $http.delete() request?

My suggestion:

$http({
    method: 'DELETE',
    url: '/roles/' + roleid,
    data: {
        user: userId
    },
    headers: {
        'Content-type': 'application/json;charset=utf-8'
    }
})
.then(function(response) {
    console.log(response.data);
}, function(rejection) {
    console.log(rejection.data);
});

What is the easiest way to remove all packages installed by pip?

This works with the latest. I think it's the shortest and most declarative way to do it.

virtualenv --clear MYENV

But usually I just delete and recreate the virtualenv since immutability rules!

How do I tar a directory of files and folders without including the directory itself?

cd my_directory/ && tar -zcvf ../my_dir.tgz . && cd - 

should do the job in one line. It works well for hidden files as well. "*" doesn't expand hidden files by path name expansion at least in bash. Below is my experiment:

$ mkdir my_directory
$ touch my_directory/file1
$ touch my_directory/file2
$ touch my_directory/.hiddenfile1
$ touch my_directory/.hiddenfile2
$ cd my_directory/ && tar -zcvf ../my_dir.tgz . && cd ..
./
./file1
./file2
./.hiddenfile1
./.hiddenfile2
$ tar ztf my_dir.tgz
./
./file1
./file2
./.hiddenfile1
./.hiddenfile2

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

ASP.NET Web API application gives 404 when deployed at IIS 7

I you are using Visual Studio 2012, download and install Update 2 that Microsoft released recently (as of 4/2013).

Visual Studio 2012 Update 2

There are some bug fixes in that update related to the issue.

How to get element value in jQuery

  <div class="inter">
      <p>Liste des Produits</p>
      <ul>
          <li><a href="#1">P1</a></li>
          <li><a href="#2">P2</a></li>
          <li><a href="#3">P3</a></li>
      </ul>
  </div>

        $(document).ready(function(){
            $(".inter li").bind(
            "click", function(){
                alert($(this).children("a").text());
            });
        });

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

How to create a simple proxy in C#?

Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.

If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.

If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.

Class constants in python

You can get to SIZES by means of self.SIZES (in an instance method) or cls.SIZES (in a class method).

In any case, you will have to be explicit about where to find SIZES. An alternative is to put SIZES in the module containing the classes, but then you need to define all classes in a single module.

Why won't my PHP app send a 404 error?

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
    header('HTTP/1.0 404 Not Found');
    echo "<h1>404 Not Found</h1>";
    echo "The page that you have requested could not be found.";
    exit();
}

If you look at the last two echo lines, that's where you'll see the content. You can customize it however you want.

Copying Code from Inspect Element in Google Chrome

Right click on the particular element (e.g. div, table, td) and select the copy as html.

NuGet: 'X' already has a dependency defined for 'Y'

The only solution that worked for me was to uninstall nuget completely from Visual Studio 2013 and then install it again with the obligatory restart of VS in between.

Best way to check if a Data Table has a null value in it

You can null/blank/space Etc value using LinQ Use Following Query

   var BlankValueRows = (from dr1 in Dt.AsEnumerable()
                                  where dr1["Columnname"].ToString() == ""
                                  || dr1["Columnname"].ToString() == ""
                                   || dr1["Columnname"].ToString() == ""
                                  select Columnname);

Here Replace Columnname with table column name and "" your search item in above code we looking null value.

Can't use WAMP , port 80 is used by IIS 7.5

Left Click on wamp go to apache> select http.config Listen [::0]:8080

CSS background image URL failing to load

I know this is really old, but I'm posting my solution anyways since google finds this thread.

background-image: url('./imagefolder/image.jpg');

That is what I do. Two dots means drill back one directory closer to root ".." while one "." should mean start where you are at as if it were root. I was having similar issues but adding that fixed it for me. You can even leave the "." in it when uploading to your host because it should work fine so long as your directory setup is exactly the same.

How to configure static content cache per folder and extension in IIS7?

I had the same issue.For me the problem was how to configure a cache limit to images.And i came across this site which gave some insights to the procedure on how the issue can be handled.Hope it will be helpful for you too Link:[https://varvy.com/pagespeed/cache-control.html]

How to end C++ code

As Martin York mentioned, exit doesn't perform necessary clean-up like return does.

It's always better to use return in the place of exit. In case if you are not in main, wherever you would like to exit the program, return to main first.

Consider the below example. With the following program, a file will be created with the content mentioned. But if return is commented & uncommented exit(0), the compiler doesn't assure you that the file will have the required text.

int main()
{
    ofstream os("out.txt");
    os << "Hello, Can you see me!\n";
    return(0);
    //exit(0);
}

Not just this, Having multiple exit points in a program will make debugging harder. Use exit only when it can be justified.

How to copy text from a div to clipboard

<div id='myInputF2'> YES ITS DIV TEXT TO COPY  </div>

<script>

    function myFunctionF2()  {
        str = document.getElementById('myInputF2').innerHTML;
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Copied the text:' + el.value);
    };
</script>

more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

How can I output the value of an enum class in C++11

You could do something like this:

//outside of main
namespace A
{
    enum A
    {
        a = 0,
        b = 69,
        c = 666
    };
};

//in main:

A::A a = A::c;
std::cout << a << std::endl;

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To even do better boolean mapping to Y/N, add to your hibernate configuration:

<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<property name="hibernate.query.substitutions">true 'Y', false 'N'</property>

Now you can use booleans in HQL, for example:

"FROM " + SomeDomainClass.class.getName() + " somedomainclass " +
"WHERE somedomainclass.someboolean = false"

Matrix multiplication using arrays

Java. Matrix multiplication.

Tested with matrices of different size.

public class Matrix {

/**
 * Matrix multiplication method.
 * @param m1 Multiplicand
 * @param m2 Multiplier
 * @return Product
 */
    public static double[][] multiplyByMatrix(double[][] m1, double[][] m2) {
        int m1ColLength = m1[0].length; // m1 columns length
        int m2RowLength = m2.length;    // m2 rows length
        if(m1ColLength != m2RowLength) return null; // matrix multiplication is not possible
        int mRRowLength = m1.length;    // m result rows length
        int mRColLength = m2[0].length; // m result columns length
        double[][] mResult = new double[mRRowLength][mRColLength];
        for(int i = 0; i < mRRowLength; i++) {         // rows from m1
            for(int j = 0; j < mRColLength; j++) {     // columns from m2
                for(int k = 0; k < m1ColLength; k++) { // columns from m1
                    mResult[i][j] += m1[i][k] * m2[k][j];
                }
            }
        }
        return mResult;
    }

    public static String toString(double[][] m) {
        String result = "";
        for(int i = 0; i < m.length; i++) {
            for(int j = 0; j < m[i].length; j++) {
                result += String.format("%11.2f", m[i][j]);
            }
            result += "\n";
        }
        return result;
    }

    public static void main(String[] args) {
        // #1
        double[][] multiplicand = new double[][] {
                {3, -1, 2},
                {2,  0, 1},
                {1,  2, 1}
        };
        double[][] multiplier = new double[][] {
                {2, -1, 1},
                {0, -2, 3},
                {3,  0, 1}
        };
        System.out.println("#1\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
        // #2
        multiplicand = new double[][] {
                {1, 2, 0},
                {-1, 3, 1},
                {2, -2, 1}
        };
        multiplier = new double[][] {
                {2},
                {-1},
                {1}
        };
        System.out.println("#2\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
        // #3
        multiplicand = new double[][] {
                {1, 2, -1},
                {0,  1, 0}
        };
        multiplier = new double[][] {
                {1, 1, 0, 0},
                {0, 2, 1, 1},
                {1, 1, 2, 2}
        };
        System.out.println("#3\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
    }
}

Output:

#1
      12.00      -1.00       2.00
       7.00      -2.00       3.00
       5.00      -5.00       8.00

#2
       0.00
      -4.00
       7.00

#3
       0.00       4.00       0.00       0.00
       0.00       2.00       1.00       1.00

Having both a Created and Last Updated timestamp columns in MySQL 4.0

You can have them both, just take off the "CURRENT_TIMESTAMP" flag on the created field. Whenever you create a new record in the table, just use "NOW()" for a value.

Or.

On the contrary, remove the 'ON UPDATE CURRENT_TIMESTAMP' flag and send the NOW() for that field. That way actually makes more sense.

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

ng-repeat finish event

I had to render formulas using MathJax after ng-repeat ends, none of the above answers solved my problem, so I made like below. It's not a nice solution, but worked for me...

<div ng-repeat="formula in controller.formulas">
    <div>{{formula.string}}</div>
    {{$last ? controller.render_formulas() : ""}}
</div>

HTML SELECT - Change selected option by VALUE using JavaScript

You can select the value using javascript:

document.getElementById('sel').value = 'bike';

DEMO

How to move from one fragment to another fragment on click of an ImageView in Android?

Add this code where you want to click and load Fragment. I hope it's work for you.


Fragment fragment = new yourfragment();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

How to enable explicit_defaults_for_timestamp?

For me it worked to add the phrase "explicit_defaults_for_timestamp = ON" without quotes into the config file my.ini.

Make sure you add this phrase right underneath the [mysqld] statement in the config file.

You will find my.ini under C:\ProgramData\MySQL\MySQL Server 5.7 if you had conducted the default installation of MySQL.

Adding a 'share by email' link to website

Something like this might be the easiest way.

<a href="mailto:?subject=I wanted you to see this site&amp;body=Check out this site http://www.website.com."
   title="Share by Email">
  <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>

You could find another email image and add that if you wanted.

RuntimeWarning: DateTimeField received a naive datetime

Use django.utils.timezone.make_aware function to make your naive datetime objects timezone aware and avoid those warnings.

It converts naive datetime object (without timezone info) to the one that has timezone info (using timezone specified in your django settings if you don't specify it explicitly as a second argument):

import datetime
from django.conf import settings
from django.utils.timezone import make_aware

naive_datetime = datetime.datetime.now()
naive_datetime.tzinfo  # None

settings.TIME_ZONE  # 'UTC'
aware_datetime = make_aware(naive_datetime)
aware_datetime.tzinfo  # <UTC>

submit the form using ajax

I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
    formData.append(input.name, input.value);
}

fetch(oForm.action,
    {
        method: oForm.method,
        body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error.message))
    .finally(() => console.log("Done"));

As you can see it is very clean and much less verbose to use than XMLHttpRequest.

What is the difference between JSF, Servlet and JSP?

There are also situations where you can favor JSP over JSF. The application nature should be the deciding factor to choose the technology.

If you have a rich GUI interaction and lot of Java scripting needed then favor JSF. Basically if your GUI app architecture is like Component oriented & even driven like Swing then JSF is the best.

If the application is just a plain form submitting, not much of GUI interaction needed, then JSP could do well if learning a new tech is an overhead and also complex framework is unnecessary.

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

Check your TLS version:

python2 -c "import urllib2,json; print(json.loads(urllib2.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"

If your TLS version is less than 1.2 you have to upgrade it since the PyPI repository is on a brownout period of deprecating early TLS.

Source - Time To Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory

You can upgrade the TLS version using the following command:

sudo apt-get update && sudo apt-get install openssl libssl-dev

This should fix your problem. Good luck!

EDIT: You can download packages using your own private python package repository regardless of TLS version. Private Python Package Repository

How to upload & Save Files with Desired name

Just get the file extention then assign the file a new name with uniqid and pass the new name to the move_upload_file method. For example:

if(isset($_POST['submit'])){
  $total = count($_FILES['files']['tmp_name']);
  for($i=0;$i<$total;$i++){
    $fileName = $_FILES['files']['name'][$i];
    $ext = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = uniqid();
    $fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
    if($ext === 'pdf' || 'jpeg' || 'JPG'){
        move_uploaded_file($_FILES['files']['tmp_name'][$i], $fileDest);
        $fileUpload = $newFileName.'.'.$ext[$i].',<br>';
    }else{
      echo 'Pdfs and jpegs only please';
    }
  }
}

Get the selected value in a dropdown using jQuery.

The above solutions didn't work for me. Here is what I finally came up with:

$( "#ddl" ).find( "option:selected" ).text();           // Text
$( "#ddl" ).find( "option:selected" ).prop("value");    // Value

phonegap open link in browser

I'm using PhoneGap Build (v3.4.0), with focus on iOS, and I needed to have this entry in my config.xml for PhoneGap to recognize the InAppBrowser plug-in.

<gap:plugin name="org.apache.cordova.inappbrowser" />

After that, using window.open(url, target) should work as expected, as documented here.

Change arrow colors in Bootstraps carousel

In bootstrap 4 if you are just changing the colour of the controls you can use the sass variables, typically in custom.scss:

$carousel-control-color: #7b277d;

As highlighted in this github issue note: https://github.com/twbs/bootstrap/issues/21985#issuecomment-281402443

What are the benefits of learning Vim?

Vim is definitely worth learning to partly summarize what has been stated previously here are the main reasons:

  • Vi/Vim can be found on most unix systems.
  • Vim allows you to easily code without taking your hands off the keyboard.
  • If you plan you configure anything in a unix based system likelihood is you going to be editing a fair few config files, therefore you'll want to learn a terminal based editor, of which vim is one of the best (sorry emacs).
  • Vim compiles/has precompiled binaries for almost every OS out there. No need to post "I need a textmate alternative for [insert OS]", you'll have Vim instead!
  • There are a lot of good plugins out there to add alot of functionality, such as in-editor cvs diffs, although some of these require a fair amount of tinkering.

Also on a side note if you find you like the Vim key bindings, there are also IDEs which include vim bindings in their editors for simple commands, for example Komodo Edit.

For help on learning Vim, try typing 'vimtutor' into your terminal and follow the instructions. There is also a book which is particularly good Hacking Vim

scrollTop jquery, scrolling to div with id?

instead of

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

Solving Quadratic Equation

Here you go this should give you the correct answers every time!

a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))

d = b**2-4*a*c # discriminant

if d < 0:
    print ("This equation has no real solution")
elif d == 0:
    x = (-b+math.sqrt(b**2-4*a*c))/2*a
    print ("This equation has one solutions: "), x
else:
    x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
    x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
    print ("This equation has two solutions: ", x1, " or", x2)

jQuery textbox change event

There is no real solution to this - even in the links to other questions given above. In the end I have decided to use setTimeout and call a method that checks every second! Not an ideal solution, but a solution that works and code I am calling is simple enough to not have an effect on performance by being called all the time.

function InitPageControls() {
        CheckIfChanged();
    }

    function CheckIfChanged() {
        // do logic

        setTimeout(function () {
            CheckIfChanged();
        }, 1000);
    }

Hope this helps someone in the future as it seems there is no surefire way of acheiving this using event handlers...

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Turn on the fusion logging, see this question for lots of advice on how to do that. Debugging mixed-mode apps loading problems can be a right royal pain. The fusion logging can be a big help.

Multiple file upload in php

We can easy to upload multiple files using php by using the below script.

Download Full Source code and preview

<?php
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image 

 $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable

  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       

   if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
            } else {//if file was not moved.
                echo $j. ').<span id="error">please try again!.</span><br/><br/>';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
}
?>

When should one use a spinlock instead of mutex?

The rule for using spinlocks is simple: use a spinlock if and only if the real time the lock is held is bounded and sufficiently small.

Note that usually user implemented spinlocks DO NOT satisfy this requirement because they do not disable interrupts. Unless pre-emptions are disabled, a pre-emption whilst a spinlock is held violates the bounded time requirement.

Sufficiently small is a judgement call and depends on the context.

Exception: some kernel programming must use a spinlock even when the time is not bounded. In particular if a CPU has no work to do, it has no choice but to spin until some more work turns up.

Special danger: in low level programming take great care when multiple interrupt priorities exist (usually there is at least one non-maskable interrupt). In this higher priority pre-emptions can run even if interrupts at the thread priority are disabled (such as priority hardware services, often related to the virtual memory management). Provided a strict priority separation is maintained, the condition for bounded real time must be relaxed and replaced with bounded system time at that priority level. Note in this case not only can the lock holder be pre-empted but the spinner can also be interrupted; this is generally not a problem because there's nothing you can do about it.

Initializing a static std::map<int, int> in C++

Using C++11:

#include <map>
using namespace std;

map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};

Using Boost.Assign:

#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;

map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');

Drawing rotated text on a HTML5 canvas

Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.

I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:

When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:

 context.save();
 context.translate(newx, newy);
 context.rotate(-Math.PI/2);
 context.textAlign = "center";
 context.fillText("Your Label Here", labelXposition, 0);
 context.restore();

.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".


Scripting SQL Server permissions

SELECT
    dp.state_desc + ' ' 
       + dp.permission_name collate latin1_general_cs_as
       + ISNULL((' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(o.name)),'')
       + ' TO ' + QUOTENAME(dpr.name)
FROM sys.database_permissions AS dp
  LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
  LEFT JOIN sys.schemas AS s ON o.schema_id = s.schema_id
  LEFT JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
WHERE dpr.name NOT IN ('public','guest')

Slight change of the accepted answer if you want to grab permissions that are applied at database level in addition to object level. Basically switch to LEFT JOIN and make sure to handle NULL for object and schema names.

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

For me, I needed to enable Http Activation under the .Net features in "Add/Remove Windows Features"