Programs & Examples On #Patricia trie

Patricia trees are a term for a specialised kind of Radix tree. A radix tree is a space-optimized trie data structure where each node with only one child is merged with its child. This means every internal node has at least two children. Unlike in regular tries, edges can be labeled with sequences of characters as well as single characters. This makes them much more efficient for small sets and for sets of strings that share long prefixes.

Is it possible to set ENV variables for rails development environment in my code?

Script for loading of custom .env file: Add the following lines to /config/environment.rb, between the require line, and the Application.initialize line:

# Load the app's custom environment variables here, so that they are loaded before environments/*.rb

app_environment_variables = File.join(Rails.root, 'config', 'local_environment.env')
if File.exists?(app_environment_variables)
  lines = File.readlines(app_environment_variables)
  lines.each do |line|
    line.chomp!
    next if line.empty? or line[0] == '#'
    parts = line.partition '='
    raise "Wrong line: #{line} in #{app_environment_variables}" if parts.last.empty?
    ENV[parts.first] = parts.last
  end
end

And config/local_environment.env (you will want to .gitignore it) will look like:

# This is ignored comment
DATABASE_URL=mysql2://user:[email protected]:3307/database
RACK_ENV=development

(Based on solution of @user664833)

Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

_x000D_
_x000D_
#container :nth-last-child(-n+2) {
  background-color: cyan;
}
_x000D_
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
_x000D_
_x000D_
_x000D_

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

This error started happening to me out of nowhere last week, affecting the existing web sites on my machine. I had no luck with it trying any of the suggestions here. Eventually I removed WebDAV from IIS completely (Windows Features -> Internet Information Services -> World Wide Web Services -> Common HTTP Features -> WebDAV Publishing). I did an IIS reset after this for good measure, and my error was finally resolved.

I can only guess that a Windows update started the issue, but I can't be sure.

How can I properly handle 404 in ASP.NET MVC?

Posting an answer since my comment was too long...

It's both a comment and questions to the unicorn post/answer:

https://stackoverflow.com/a/7499406/687549

I prefer this answer over the others for it's simplicity and the fact that apparently some folks at Microsoft were consulted. I got three questions however and if they can be answered then I will call this answer the holy grail of all 404/500 error answers on the interwebs for an ASP.NET MVC (x) app.

@Pure.Krome

  1. Can you update your answer with the SEO stuff from the comments pointed out by GWB (there was never any mentioning of this in your answer) - <customErrors mode="On" redirectMode="ResponseRewrite"> and <httpErrors errorMode="Custom" existingResponse="Replace">?

  2. Can you ask your ASP.NET team friends if it is okay to do it like that - would be nice to have some confirmation - maybe it's a big no-no to change redirectMode and existingResponse in this way to be able to play nicely with SEO?!

  3. Can you add some clarification surrounding all that stuff (customErrors redirectMode="ResponseRewrite", customErrors redirectMode="ResponseRedirect", httpErrors errorMode="Custom" existingResponse="Replace", REMOVE customErrors COMPLETELY as someone suggested) after talking to your friends at Microsoft?

As I was saying; it would be supernice if we could make your answer more complete as this seem to be a fairly popular question with 54 000+ views.

Update: Unicorn answer does a 302 Found and a 200 OK and cannot be changed to only return 404 using a route. It has to be a physical file which is not very MVC:ish. So moving on to another solution. Too bad because this seemed to be the ultimate MVC:ish answer this far.

Algorithm to compare two images

Read the paper: Porikli, Fatih, Oncel Tuzel, and Peter Meer. “Covariance Tracking Using Model Update Based on Means on Riemannian Manifolds”. (2006) IEEE Computer Vision and Pattern Recognition.

I was successfully able to detect overlapping regions in images captured from adjacent webcams using the technique presented in this paper. My covariance matrix was composed of Sobel, canny and SUSAN aspect/edge detection outputs, as well as the original greyscale pixels.

Adding elements to a C# array

If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:

var  oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0

How to list the files in current directory?

Your code gives expected result,if you compile and run your code standalone(from commandline). As in eclipse for each project by default working directory is project directory that's why you are getting this result.

You can set user.dir property in java as:

   System.setProperty("user.dir", "absolute path of src folder");

then it will give expected result.

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

SQL Server: Filter output of sp_who2

Slight improvement to Astander's answer. I like to put my criteria at top, and make it easier to reuse day to day:

DECLARE @Spid INT, @Status VARCHAR(MAX), @Login VARCHAR(MAX), @HostName VARCHAR(MAX), @BlkBy VARCHAR(MAX), @DBName VARCHAR(MAX), @Command VARCHAR(MAX), @CPUTime INT, @DiskIO INT, @LastBatch VARCHAR(MAX), @ProgramName VARCHAR(MAX), @SPID_1 INT, @REQUESTID INT

    --SET @SPID = 10
    --SET @Status = 'BACKGROUND'
    --SET @LOGIN = 'sa'
    --SET @HostName = 'MSSQL-1'
    --SET @BlkBy = 0
    --SET @DBName = 'master'
    --SET @Command = 'SELECT INTO'
    --SET @CPUTime = 1000
    --SET @DiskIO = 1000
    --SET @LastBatch = '10/24 10:00:00'
    --SET @ProgramName = 'Microsoft SQL Server Management Studio - Query'
    --SET @SPID_1 = 10
    --SET @REQUESTID = 0

    SET NOCOUNT ON 
    DECLARE @Table TABLE(
            SPID INT,
            Status VARCHAR(MAX),
            LOGIN VARCHAR(MAX),
            HostName VARCHAR(MAX),
            BlkBy VARCHAR(MAX),
            DBName VARCHAR(MAX),
            Command VARCHAR(MAX),
            CPUTime INT,
            DiskIO INT,
            LastBatch VARCHAR(MAX),
            ProgramName VARCHAR(MAX),
            SPID_1 INT,
            REQUESTID INT
    )
    INSERT INTO @Table EXEC sp_who2
    SET NOCOUNT OFF
    SELECT  *
    FROM    @Table
    WHERE
    (@Spid IS NULL OR SPID = @Spid)
    AND (@Status IS NULL OR Status = @Status)
    AND (@Login IS NULL OR Login = @Login)
    AND (@HostName IS NULL OR HostName = @HostName)
    AND (@BlkBy IS NULL OR BlkBy = @BlkBy)
    AND (@DBName IS NULL OR DBName = @DBName)
    AND (@Command IS NULL OR Command = @Command)
    AND (@CPUTime IS NULL OR CPUTime >= @CPUTime)
    AND (@DiskIO IS NULL OR DiskIO >= @DiskIO)
    AND (@LastBatch IS NULL OR LastBatch >= @LastBatch)
    AND (@ProgramName IS NULL OR ProgramName = @ProgramName)
    AND (@SPID_1 IS NULL OR SPID_1 = @SPID_1)
    AND (@REQUESTID IS NULL OR REQUESTID = @REQUESTID)

OR, AND Operator

Use '&&' for AND and use '||' for OR, for example:

bool A;
bool B;

bool resultOfAnd = A && B; // Returns the result of an AND
bool resultOfOr = A || B; // Returns the result of an OR

Required attribute HTML5

Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute

Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.

reading text file with utf-8 encoding using java

You need to specify the encoding of the InputStreamReader using the Charset parameter.

Charset inputCharset = Charset.forName("ISO-8859-1");
InputStreamReader isr = new InputStreamReader(fis, inputCharset));

This is work for me. i hope to help you.

How to determine the version of android SDK installed in computer?

Android Studio is now (early 2015) out of beta. If you're using it as your development platform, the SDK Manager is probably the easiest way to see what's available. To start the SDK Manager from within Android Studio, use the menu bar: Tools > Android > SDK Manager.

This will provide not only the SDK version, but the versions of SDK Build Tools and SDK Platform Tools. It also works if you've installed them somewhere other than in Program Files.

Get row-index values of Pandas DataFrame as list?

To get the index values as a list/list of tuples for Index/MultiIndex do:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

list(df.index.values)  # this will always work in pandas

Bootstrap 3: Text overlay on image

Set the position to absolute; to move the caption area in the correct position

CSS

.post-content {
    background: none repeat scroll 0 0 #FFFFFF;
    opacity: 0.5;
    margin: -54px 20px 12px; 
    position: absolute;
}

Bootply

Difference between array_push() and $array[] =

I know this is an old answer but it might be helpful for others to know that another difference between the two is that if you have to add more than 2/3 values per loop to an array it's faster to use:

     for($i = 0; $i < 10; $i++){
          array_push($arr, $i, $i*2, $i*3, $i*4, ...)
     }

instead of:

     for($i = 0; $i < 10; $i++){
         $arr[] = $i;
         $arr[] = $i*2;
         $arr[] = $i*3;
         $arr[] = $i*4;
         ...
     }

edit- Forgot to close the bracket for the for conditional

Resize image with javascript canvas (smoothly)

Based on K3N answer, I rewrite code generally for anyone wants

var oc = document.createElement('canvas'), octx = oc.getContext('2d');
    oc.width = img.width;
    oc.height = img.height;
    octx.drawImage(img, 0, 0);
    while (oc.width * 0.5 > width) {
       oc.width *= 0.5;
       oc.height *= 0.5;
       octx.drawImage(oc, 0, 0, oc.width, oc.height);
    }
    oc.width = width;
    oc.height = oc.width * img.height / img.width;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

UPDATE JSFIDDLE DEMO

Here is my ONLINE DEMO

Create new user in MySQL and give it full access to one database

Syntax

To create user in MySQL/MariaDB 5.7.6 and higher, use CREATE USER syntax:

CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password';

then to grant all access to the database (e.g. my_db), use GRANT Syntax, e.g.

GRANT ALL ON my_db.* TO 'new_user'@'localhost';

Where ALL (priv_type) can be replaced with specific privilege such as SELECT, INSERT, UPDATE, ALTER, etc.

Then to reload newly assigned permissions run:

FLUSH PRIVILEGES;

Executing

To run above commands, you need to run mysql command and type them into prompt, then logout by quit command or Ctrl-D.

To run from shell, use -e parameter (replace SELECT 1 with one of above commands):

$ mysql -e "SELECT 1"

or print statement from the standard input:

$ echo "FOO STATEMENT" | mysql

If you've got Access denied with above, specify -u (for user) and -p (for password) parameters, or for long-term access set your credentials in ~/.my.cnf, e.g.

[client]
user=root
password=root

Shell integration

For people not familiar with MySQL syntax, here are handy shell functions which are easy to remember and use (to use them, you need to load the shell functions included further down).

Here is example:

$ mysql-create-user admin mypass
| CREATE USER 'admin'@'localhost' IDENTIFIED BY 'mypass'

$ mysql-create-db foo
| CREATE DATABASE IF NOT EXISTS foo

$ mysql-grant-db admin foo
| GRANT ALL ON foo.* TO 'admin'@'localhost'
| FLUSH PRIVILEGES

$ mysql-show-grants admin
| SHOW GRANTS FOR 'admin'@'localhost'
| Grants for admin@localhost                                                                                   
| GRANT USAGE ON *.* TO 'admin'@'localhost' IDENTIFIED BY PASSWORD '*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4' |
| GRANT ALL PRIVILEGES ON `foo`.* TO 'admin'@'localhost'

$ mysql-drop-user admin
| DROP USER 'admin'@'localhost'

$ mysql-drop-db foo
| DROP DATABASE IF EXISTS foo

To use above commands, you need to copy&paste the following functions into your rc file (e.g. .bash_profile) and reload your shell or source the file. In this case just type source .bash_profile:

# Create user in MySQL/MariaDB.
mysql-create-user() {
  [ -z "$2" ] && { echo "Usage: mysql-create-user (user) (password)"; return; }
  mysql -ve "CREATE USER '$1'@'localhost' IDENTIFIED BY '$2'"
}

# Delete user from MySQL/MariaDB
mysql-drop-user() {
  [ -z "$1" ] && { echo "Usage: mysql-drop-user (user)"; return; }
  mysql -ve "DROP USER '$1'@'localhost';"
}

# Create new database in MySQL/MariaDB.
mysql-create-db() {
  [ -z "$1" ] && { echo "Usage: mysql-create-db (db_name)"; return; }
  mysql -ve "CREATE DATABASE IF NOT EXISTS $1"
}

# Drop database in MySQL/MariaDB.
mysql-drop-db() {
  [ -z "$1" ] && { echo "Usage: mysql-drop-db (db_name)"; return; }
  mysql -ve "DROP DATABASE IF EXISTS $1"
}

# Grant all permissions for user for given database.
mysql-grant-db() {
  [ -z "$2" ] && { echo "Usage: mysql-grand-db (user) (database)"; return; }
  mysql -ve "GRANT ALL ON $2.* TO '$1'@'localhost'"
  mysql -ve "FLUSH PRIVILEGES"
}

# Show current user permissions.
mysql-show-grants() {
  [ -z "$1" ] && { echo "Usage: mysql-show-grants (user)"; return; }
  mysql -ve "SHOW GRANTS FOR '$1'@'localhost'"
}

Note: If you prefer to not leave trace (such as passwords) in your Bash history, check: How to prevent commands to show up in bash history?

"Rate This App"-link in Google Play store app on the phone

Here is my version using the BuildConfig class:

Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);

marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}

try {
    startActivity(marketIntent);
} catch (ActivityNotFoundException e) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID)));
}

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

This works:

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time" // or "runtime"
)

func cleanup() {
    fmt.Println("cleanup")
}

func main() {
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        cleanup()
        os.Exit(1)
    }()

    for {
        fmt.Println("sleeping...")
        time.Sleep(10 * time.Second) // or runtime.Gosched() or similar per @misterbee
    }
}

Sum function in VBA

Function is not a property/method from range.

If you want to sum values then use the following:

Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))

EDIT:

if you want the formula then use as follows:

Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"

'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).

In case you are allways going to use the same range address then you can use as Rory sugested:

Range("A1").Formula ="=Sum(A2:B3)"

How to check compiler log in sql developer?

control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).

if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up

for instance, hit Control-shift-L then execute this

CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;

and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "

(You can also see this in "View--Log")

One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)

"elseif" syntax in JavaScript

Actually, technically when indented properly, it would be:

if (condition) {
    ...
} else {
    if (condition) {
        ...
    } else {
        ...
    }
}

There is no else if, strictly speaking.

(Update: Of course, as pointed out, the above is not considered good style.)

How to make background of table cell transparent

It is possible
You just also need to apply the color to 'tbody' element as that's the table body that's been causing our trouble by peeking underneath.
table, tbody, tr, th, td{ background-color: rgba(0, 0, 0, 0.0) !important; }

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff option ensures that a fast forward merge will not happen, and that a new commit object will always be created. This can be desirable if you want git to maintain a history of feature branches.             git merge --no-ff vs git merge In the above image, the left side is an example of the git history after using git merge --no-ff and the right side is an example of using git merge where an ff merge was possible.

EDIT: A previous version of this image indicated only a single parent for the merge commit. Merge commits have multiple parent commits which git uses to maintain a history of the "feature branch" and of the original branch. The multiple parent links are highlighted in green.

Git/GitHub can't push to master

To set https globally instead of git://:

git config --global url.https://github.com/.insteadOf git://github.com/

How to check if a textbox is empty using javascript

<pre><form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" /> 
<input type="submit"/>
</form></pre>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false); 
    frmvalidator.EnableMsgsTogether(); 
    frmvalidator.addValidation("name","req","Plese Enter Name"); 

</script>

Note: before using the code above you have to add the gen_validatorv31.js file.

Eclipse comment/uncomment shortcut?

  1. Single line comment Ctrl + /
  2. Single line uncomment Ctrl + /

  1. Multiline comment Ctrl + Shift + /
  2. Multiline uncomment Ctrl + Shift + \ (note the backslash)

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.

Syntax

ALTER TRIGGER trigger Name DISABLE;

ALTER TRIGGER trigger_Name ENABLE;

How do I change the string representation of a Python class?

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

CSS grid wrapping

Here's my attempt. Excuse the fluff, I was feeling extra creative.

My method is a parent div with fixed dimensions. The rest is just fitting the content inside that div accordingly.

This will rescale the images regardless of the aspect ratio. There will be no hard cropping either.

_x000D_
_x000D_
body {_x000D_
    background: #131418;_x000D_
    text-align: center;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
_x000D_
.my-image-parent {_x000D_
    display: inline-block;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
    line-height: 300px; /* Should match your div height */_x000D_
    text-align: center;_x000D_
    font-size: 0;_x000D_
}_x000D_
_x000D_
/* Start demonstration background fluff */_x000D_
    .bg1 {background: url(https://unsplash.it/801/799);}_x000D_
    .bg2 {background: url(https://unsplash.it/799/800);}_x000D_
    .bg3 {background: url(https://unsplash.it/800/799);}_x000D_
    .bg4 {background: url(https://unsplash.it/801/801);}_x000D_
    .bg5 {background: url(https://unsplash.it/802/800);}_x000D_
    .bg6 {background: url(https://unsplash.it/800/802);}_x000D_
    .bg7 {background: url(https://unsplash.it/802/802);}_x000D_
    .bg8 {background: url(https://unsplash.it/803/800);}_x000D_
    .bg9 {background: url(https://unsplash.it/800/803);}_x000D_
    .bg10 {background: url(https://unsplash.it/803/803);}_x000D_
    .bg11 {background: url(https://unsplash.it/803/799);}_x000D_
    .bg12 {background: url(https://unsplash.it/799/803);}_x000D_
    .bg13 {background: url(https://unsplash.it/806/799);}_x000D_
    .bg14 {background: url(https://unsplash.it/805/799);}_x000D_
    .bg15 {background: url(https://unsplash.it/798/804);}_x000D_
    .bg16 {background: url(https://unsplash.it/804/799);}_x000D_
    .bg17 {background: url(https://unsplash.it/804/804);}_x000D_
    .bg18 {background: url(https://unsplash.it/799/804);}_x000D_
    .bg19 {background: url(https://unsplash.it/798/803);}_x000D_
    .bg20 {background: url(https://unsplash.it/803/797);}_x000D_
/* end demonstration background fluff */_x000D_
_x000D_
.my-image {_x000D_
    width: auto;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
    background-size: contain;_x000D_
    background-position: center;_x000D_
    background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg1"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg2"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg3"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg4"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg5"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg6"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg7"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg8"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg9"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg10"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg11"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg12"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg13"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg14"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg15"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg16"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg17"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg18"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg19"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg20"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Watch multiple $scope attributes

how about:

scope.$watch(function() { 
   return { 
      a: thing-one, 
      b: thing-two, 
      c: red-fish, 
      d: blue-fish 
   }; 
}, listener...);

Line break in HTML with '\n'

You could use the <pre> tag

_x000D_
_x000D_
<div class="text">_x000D_
<pre>_x000D_
  abc_x000D_
  def_x000D_
  ghi_x000D_
</pre>_x000D_
  abc_x000D_
  def_x000D_
  ghi_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to automatically generate N "distinct" colors?

I would try to fix saturation and lumination to maximum and focus on hue only. As I see it, H can go from 0 to 255 and then wraps around. Now if you wanted two contrasting colours you would take the opposite sides of this ring, i.e. 0 and 128. If you wanted 4 colours, you would take some separated by 1/4 of the 256 length of the circle, i.e. 0, 64,128,192. And of course, as others suggested when you need N colours, you could just separate them by 256/N.

What I would add to this idea is to use a reversed representation of a binary number to form this sequence. Look at this:

0 = 00000000  after reversal is 00000000 = 0
1 = 00000001  after reversal is 10000000 = 128
2 = 00000010  after reversal is 01000000 = 64
3 = 00000011  after reversal is 11000000 = 192

... this way if you need N different colours you could just take first N numbers, reverse them, and you get as much distant points as possible (for N being power of two) while at the same time preserving that each prefix of the sequence differs a lot.

This was an important goal in my use case, as I had a chart where colors were sorted by area covered by this colour. I wanted the largest areas of the chart to have large contrast, and I was ok with some small areas to have colours similar to those from top 10, as it was obvious for the reader which one is which one by just observing the area.

Maximum packet size for a TCP connection

There're no packets in TCP API.

There're packets in underlying protocols often, like when TCP is done over IP, which you have no interest in, because they have nothing to do with the user except for very delicate performance optimizations which you are probably not interested in (according to the question's formulation).

If you ask what is a maximum number of bytes you can send() in one API call, then this is implementation and settings dependent. You would usually call send() for chunks of up to several kilobytes, and be always ready for the system to refuse to accept it totally or partially, in which case you will have to manually manage splitting into smaller chunks to feed your data into the TCP send() API.

A regular expression to exclude a word/string

This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)

You can add as much ignored words as you like, here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');

preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);

Set up an HTTP proxy to insert a header

If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found here.

CSS Styling for a Button: Using <input type="button> instead of <button>

The issue isn't with the button, the issue is with the div. As divs are block elements, they default to occupying the full width of their parent element (as a general rule; I'm pretty sure there are some exceptions if you're messing around with different positioning schemes in one document that would cause it to occupy the full width of a higher element in the hierarchy).

Anyway, try adding float: left; to the rules for the .button selector. That will cause the div with class button to fit around the button, and would allow you to have multiple floated divs on the same line if you wanted more div.buttons.

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

My solution on Windows was to either run console window as Administrator or change the environment variable MAVEN_OPTS to use a hardcoded path to trust.jks (e.g. 'C:\Users\oddros') instead of '%USERPROFILE%'. My MAVEN_OPTS now looks like this:

-Djavax.net.ssl.trustStore=C:\Users\oddros\trust.jks -Djavax.net.ssl.trustStorePassword=changeit

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

How to kill all processes with a given partial name?

If you do not want to take headache of finding process id, use regexp to kill process by name. For example, to kill chrome following code will do the trick.

killall -r chrome

How to select the rows with maximum values in each group with dplyr?

More generally, I think you might want to get "top" of the rows that are sorted within a given group.

For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).

# Answering the question of getting row with max "value".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in descending order by "value" column.
  arrange( desc(value) ) %>% 
  # Pick the top 1 value
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

# Answering an extension of the question of 
# getting row with the max value of the lowest "C".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in ascending order by C, and then within that by 
  # descending order by "value" column.
  arrange( C, desc(value) ) %>% 
  # Pick the one top row based on the sort
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

How to add a href link in PHP?

Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.

.box{
  float:right;
}
.box a img{
  vertical-align: middle;
  border: 0px;
}

<div class="box">
    <a href="<?php echo "http://www.someotherwebsite.com"; ?>">
        <img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
    </a>
</div>

As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.

<div class="box">
    <a href="http://www.someotherwebsite.com">
        <img src="file_location/media/img/twitter.png" alt="Image Decription">
    </a>
</div>

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

for eg if CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci replace it to CHARSET=latin1 and remove the collate

You are good to go

Allowed memory size of 536870912 bytes exhausted in Laravel

While using Laravel on apache server there is another php.ini

 /etc/php/7.2/apache2/php.ini

Modify the memory limit value in this file

 memory_limit=1024M

and restart the apache server

 sudo service apache2 restart

How to remove focus without setting focus to another control?

First of all, it will 100% work........

  1. Create onResume() method.
  2. Inside this onResume() find the view which is focusing again and again by findViewById().
  3. Inside this onResume() set requestFocus() to this view.
  4. Inside this onResume() set clearFocus to this view.
  5. Go in xml of same layout and find that top view which you want to be focused and set focusable true and focusableInTuch true.
  6. Inside this onResume() find the above top view by findViewById
  7. Inside this onResume() set requestFocus() to this view at the last.
  8. And now enjoy......

How to escape "&" in XML?

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

Granting Rights on Stored Procedure to another user of Oracle

I'm not sure that I understand what you mean by "rights of ownership".

If User B owns a stored procedure, User B can grant User A permission to run the stored procedure

GRANT EXECUTE ON b.procedure_name TO a

User A would then call the procedure using the fully qualified name, i.e.

BEGIN
  b.procedure_name( <<list of parameters>> );
END;

Alternately, User A can create a synonym in order to avoid having to use the fully qualified procedure name.

CREATE SYNONYM procedure_name FOR b.procedure_name;

BEGIN
  procedure_name( <<list of parameters>> );
END;

How do I handle ImeOptions' done button click?

I ended up with a combination of Roberts and chirags answers:

((EditText)findViewById(R.id.search_field)).setOnEditorActionListener(
        new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // Identifier of the action. This will be either the identifier you supplied,
        // or EditorInfo.IME_NULL if being called due to the enter key being pressed.
        if (actionId == EditorInfo.IME_ACTION_SEARCH
                || actionId == EditorInfo.IME_ACTION_DONE
                || event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            onSearchAction(v);
            return true;
        }
        // Return true if you have consumed the action, else false.
        return false;
    }
});

Update: The above code would some times activate the callback twice. Instead I've opted for the following code, which I got from the Google chat clients:

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    // If triggered by an enter key, this is the event; otherwise, this is null.
    if (event != null) {
        // if shift key is down, then we want to insert the '\n' char in the TextView;
        // otherwise, the default action is to send the message.
        if (!event.isShiftPressed()) {
            if (isPreparedForSending()) {
                confirmSendMessageIfNeeded();
            }
            return true;
        }
        return false;
    }

    if (isPreparedForSending()) {
        confirmSendMessageIfNeeded();
    }
    return true;
}

BackgroundWorker vs background Thread

The basic difference is, like you stated, generating GUI events from the BackgroundWorker. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.

Find all matches in workbook using Excel VBA

Using the Range.Find method, as pointed out above, along with a loop for each worksheet in the workbook, is the fastest way to do this. The following, for example, locates the string "Question?" in each worksheet and replaces it with the string "Answered!".

Sub FindAndExecute()

Dim Sh As Worksheet
Dim Loc As Range

For Each Sh In ThisWorkbook.Worksheets
    With Sh.UsedRange
        Set Loc = .Cells.Find(What:="Question?")
        If Not Loc Is Nothing Then
            Do Until Loc Is Nothing
                Loc.Value = "Answered!"
                Set Loc = .FindNext(Loc)
            Loop
        End If
    End With
    Set Loc = Nothing
Next

End Sub

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

I had the same problem in my tomcat server but when i check deeply i found that i add a new tag in my web.xml file and the server doesn't accept it so check your file to if any update happened then restart your tomcat and will be good .

How to prevent user from typing in text field without disabling the field?

A non-Javascript alternative that can be easily overlooked: can you use the readonly attribute instead of the disabled attribute? It prevents editing the text in the input, but browsers style the input differently (less likely to "grey it out") e.g. <input readonly type="text" ...>

Visual Studio Code how to resolve merge conflicts with git?

With VSCode you can find the merge conflicts easily with the following UI. enter image description here

(if you do not have the topbar, set "editor.codeLens": true in User Preferences)

It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD.

If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming, etc.

Removing object from array in Swift 3

Try this in Swift 3

array.remove(at: Index)

Instead of

array.removeAtIndex(index)

Update

"Declaration is only valid at file scope".

Make sure the object is in scope. You can give scope "internal", which is default.

index(of:<Object>) to work, class should conform to Equatable

How to set the UITableView Section title programmatically (iPhone/iPad)?

If you are writing code in Swift it would look as an example like this

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
    switch section
    {
        case 0:
            return "Apple Devices"
        case 1:
            return "Samsung Devices"
        default:
            return "Other Devices"
    }
}

Adding images to an HTML document with javascript

You need to use document.getElementById() in line 3.

If you try this right now in the console:

_x000D_
_x000D_
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
_x000D_
_x000D_

... you'd get this:

enter image description here

How to split a string between letters and digits (or between digits and letters)?

Didn't use Java for ages, so just some pseudo code, that should help get you started (faster for me than looking up everything :) ).

 string a = "123abc345def";
 string[] result;
 while(a.Length > 0)
 {
      string part;
      if((part = a.Match(/\d+/)).Length) // match digits
           ;
      else if((part = a.Match(/\a+/)).Length) // match letters
           ;
      else
           break; // something invalid - neither digit nor letter
      result.append(part);
      a = a.SubStr(part.Length - 1); // remove the part we've found
 }

Variable not accessible when initialized outside function

My guess is that the system-status element is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?

You should declare it only, then assign its value from an onLoad handler instead, because then you will be sure that it has properly initialized (loaded) the element in question.

You could also try putting the script at the bottom of the page (or at least somewhere after the system-status element is declared) but it's not guaranteed to always work.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

I've been watching Douglas Crockford's video on this and his explanation for not using increment and decrement is that

  1. It has been used in the past in other languages to break the bounds of arrays and cause all manners of badness and
  2. That it is more confusing and inexperienced JS developers don't know exactly what it does.

Firstly arrays in JavaScript are dynamically sized and so, forgive me if I'm wrong, it is not possible to break the bounds of an array and access data that shouldn't be accessed using this method in JavaScript.

Secondly, should we avoid things that are complicated, surely the problem is not that we have this facility but the problem is that there are developers out there that claim to do JavaScript but don't know how these operators work?? It is simple enough. value++, give me the current value and after the expression add one to it, ++value, increment the value before giving me it.

Expressions like a ++ + ++ b, are simple to work out if you just remember the above.

var a = 1, b = 1, c;
c = a ++ + ++ b;
// c = 1 + 2 = 3; 
// a = 2 (equals two after the expression is finished);
// b = 2;

I suppose you've just got to remember who has to read through the code, if you have a team that knows JS inside out then you don't need to worry. If not then comment it, write it differently, etc. Do what you got to do. I don't think increment and decrement is inherently bad or bug generating, or vulnerability creating, maybe just less readable depending on your audience.

Btw, I think Douglas Crockford is a legend anyway, but I think he's caused a lot of scare over an operator that didn't deserve it.

I live to be proven wrong though...

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

UPDATE 2014-11-14: The solution below is too old, I recommend using flex box layout method. Here is a overview: http://learnlayout.com/flexbox.html


My solution

html

<li class="grid-list-header row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

<li class="grid-list-item row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

scss

.row-cw {
  position: relative;
}

.col-cw {
  position: absolute;
  top: 0;
}


.ir-msg-list {

  $col-reply-width: 140px;
  $col-action-width: 130px;

  .row-cw-msg-list {
    padding-right: $col-reply-width + $col-action-width;
  }

  .col-cw-name {
    width: 50%;
  }

  .col-cw-keyword {
    width: 50%;
  }

  .col-cw-reply {
    width: $col-reply-width;
    right: $col-action-width;
  }

  .col-cw-action {
    width: $col-action-width;
    right: 0;
  }
}

Without modify too much bootstrap layout code.


Update (not from OP): adding code snippet below to facilitate understanding of this answer. But it doesn't seem to work as expected.

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
.row-cw {_x000D_
  position: relative;_x000D_
  height: 20px;_x000D_
}_x000D_
.col-cw {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  background-color: rgba(150, 150, 150, .5);_x000D_
}_x000D_
.row-cw-msg-list {_x000D_
  padding-right: 270px;_x000D_
}_x000D_
.col-cw-name {_x000D_
  width: 50%;_x000D_
  background-color: rgba(150, 0, 0, .5);_x000D_
}_x000D_
.col-cw-keyword {_x000D_
  width: 50%;_x000D_
  background-color: rgba(0, 150, 0, .5);_x000D_
}_x000D_
.col-cw-reply {_x000D_
  width: 140px;_x000D_
  right: 130px;_x000D_
  background-color: rgba(0, 0, 150, .5);_x000D_
}_x000D_
.col-cw-action {_x000D_
  width: 130px;_x000D_
  right: 0;_x000D_
  background-color: rgba(150, 150, 0, .5);_x000D_
}
_x000D_
<ul class="ir-msg-list">_x000D_
  <li class="grid-list-header row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
_x000D_
  <li class="grid-list-item row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to see my Eclipse version?

Same issue i was getting , but When we open our eclipse software then automatically we can see eclipse version and workspace location like these pic below enter image description here

Use URI builder in Android or create URL with variables

You can do that with lambda expressions;

    private static final String BASE_URL = "http://api.example.org/data/2.5/forecast/daily";

    private String getBaseUrl(Map<String, String> params) {
        final Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
        params.entrySet().forEach(entry -> builder.appendQueryParameter(entry.getKey(), entry.getValue()));
        return builder.build().toString();
    }

and you can create params like that;

    Map<String, String> params = new HashMap<String, String>();
    params.put("zip", "94043,us");
    params.put("units", "metric");

Btw. If you will face any issue like “lambda expressions not supported at this language level”, please check this URL;

https://stackoverflow.com/a/22704620/2057154

How to update all MySQL table rows at the same time?

just use UPDATE query without condition like this

 UPDATE tablename SET online_status=0;

How to get first character of a string in SQL?

I prefer:

SUBSTRING (my_column, 1, 1)

because it is Standard SQL-92 syntax and therefore more portable.


Strictly speaking, the standard version would be

SUBSTRING (my_column FROM 1 FOR 1)

The point is, transforming from one to the other, hence to any similar vendor variation, is trivial.

p.s. It was only recently pointed out to me that functions in standard SQL are deliberately contrary, by having parameters lists that are not the conventional commalists, in order to make them easily identifiable as being from the standard!

How to hide a View programmatically?

You can call view.setVisibility(View.GONE) if you want to remove it from the layout.

Or view.setVisibility(View.INVISIBLE) if you just want to hide it.

From Android Docs:

INVISIBLE

This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.

GONE

This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.

SQL Select between dates

SELECT *
FROM TableName
WHERE julianday(substr(date,7)||'-'||substr(date,4,2)||'-'||substr(date,1,2)) BETWEEN julianday('2011-01-11') AND julianday('2011-08-11')

Note that I use the format : dd/mm/yyyy

If you use d/m/yyyy, Change in substr()

Hope this will help you.

How to use subprocess popen Python

In the recent Python version, subprocess has a big change. It offers a brand-new class Popen to handle os.popen1|2|3|4.

The new subprocess.Popen()

import subprocess
subprocess.Popen('ls -la', shell=True)

Its arguments:

subprocess.Popen(args, 
                bufsize=0, 
                executable=None, 
                stdin=None, stdout=None, stderr=None, 
                preexec_fn=None, close_fds=False, 
                shell=False, 
                cwd=None, env=None, 
                universal_newlines=False, 
                startupinfo=None, 
                creationflags=0)

Simply put, the new Popen includes all the features which were split into 4 separate old popen.

The old popen:

Method  Arguments
popen   stdout
popen2  stdin, stdout
popen3  stdin, stdout, stderr
popen4  stdin, stdout and stderr

You could get more information in Stack Abuse - Robert Robinson. Thank him for his devotion.

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

How to select a single column with Entity Framework?

You could use the LINQ select clause and reference the property that relates to your Name column.

Python Socket Multiple Clients

accept can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:

  • Open new threads to handle clients, while the main thread goes back to accepting new clients
  • As above but with processes, instead of threads
  • Use asynchronous socket frameworks like Twisted, or a plethora of others

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

Installing RubyGems in Windows

Use chocolatey in PowerShell

choco install ruby -y
refreshenv
gem install bundler

‘ant’ is not recognized as an internal or external command

ANT_HOME is not being resolved. Change %ANT_HOME%\bin in the Path system environment variable to c:\apache-ant\apache-ant-1.8.2\bin.

Populating a database in a Laravel migration file

Here is a very good explanation of why using Laravel's Database Seeder is preferable to using Migrations: https://web.archive.org/web/20171018135835/http://laravelbook.com/laravel-database-seeding/

Although, following the instructions on the official documentation is a much better idea because the implementation described at the above link doesn't seem to work and is incomplete. http://laravel.com/docs/migrations#database-seeding

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

I have the same problem, in build.gradle (Module:app) add the following line of code inside dependencies:

dependencies 
{
   ...
   compile 'com.android.support:support-annotations:27.1.1'
}

It worked for me perfectly

Gradient text color

I don't exactly know how the stop stuff works. But I've got a gradient text example. Maybe this will help you out!

_you can also add more colors to the gradient if you want or just select other colors from the color generator

_x000D_
_x000D_
.rainbow2 {_x000D_
    background-image: -webkit-linear-gradient(left, #E0F8F7, #585858, #fff); /* For Chrome and Safari */_x000D_
    background-image:    -moz-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Fx (3.6 to 15) */_x000D_
    background-image:     -ms-linear-gradient(left, #E0F8F7, #585858, #fff); /* For pre-releases of IE 10*/_x000D_
    background-image:      -o-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Opera (11.1 to 12.0) */_x000D_
    background-image:         linear-gradient(to right, #E0F8F7, #585858, #fff); /* Standard syntax; must be last */_x000D_
    color:transparent;_x000D_
    -webkit-background-clip: text;_x000D_
    background-clip: text;_x000D_
}_x000D_
.rainbow {_x000D_
_x000D_
  background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  color:transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>_x000D_
<br />_x000D_
<span class="rainbow2">No rainbow text</span>
_x000D_
_x000D_
_x000D_

Safely remove migration In Laravel

I accidentally created a migration with a bad name (command: php artisan migrate:make). I did not run (php artisan migrate) the migration, so I decided to remove it. My steps:

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Relax

If you did run the migration (php artisan migrate), you may do this:

a) Run migrate:rollback - it is the right way to undo the last migration (Thnx @Jakobud)

b) If migrate:rollback does not work, do it manually (I remember bugs with migrate:rollback in previous versions):

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Modify your database: Remove the last entry from the migrations table

scp files from local to remote machine error: no such file or directory

i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.

solution: i had to log out and run the command again and it worked

fe_sendauth: no password supplied

Do not use passwords. Use peer authentication instead:

postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb

Use of min and max functions in C++

Use std::min and std::max.

If the other versions are faster then your implementation can add overloads for these and you'll get the benefit of performance and portability:

template <typename T>
T min (T, T) {
  // ... default
}

inline float min (float f1, float f2) {
 return fmin( f1, f2);
}    

Finding the length of a Character Array in C

There is also a compact form for that, if you do not want to rely on strlen. Assuming that the character array you are considering is "msg":

  unsigned int len=0;
  while(*(msg+len) ) len++;

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

Grunt watch error - Waiting...Fatal error: watch ENOSPC

In my case I found that I have an aggressive plugin for Vim, just restarted it.

Size-limited queue that holds last N elements in Java

The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).

To my knowledge your trivial implementation is the easiest way to get such an behaviour.

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

You need to subclass UITableViewCell and subclass method willTransitionToState:(UITableViewCellStateMask)state which is called whenever user swipes the cell. The state flags will let you know if the Delete button is showing, and show/hide your More button there.

Unfortunately this method gives you neither the width of the Delete button nor the animation time. So you need to observer & hard-code your More button's frame and animation time into your code (I personally think Apple needs to do something about this).

Can't Autowire @Repository annotated interface in Spring Boot

If you're facing this problem when unit testing with @DataJpaTest then you'll find the solution below.

Spring boot do not initialize @Repository beans for @DataJpaTest. So try one of the two fix below to have them available:

First

Use @SpringBootTest instead. But this will boot up the whole application context.

Second(Better solutions)

Import the specific repository you need, like below

@DataJpaTest
@Import(MyRepository.class)
public class MyRepositoryTest {

@Autowired
private MyRepository myRepository;

How to animate button in android?

Dependency

Add it in your root build.gradle at the end of repositories:

allprojects {
repositories {
    ...
    maven { url "https://jitpack.io" }
}}

and then add dependency dependencies { compile 'com.github.varunest:sparkbutton:1.0.5' }

Usage

XML

<com.varunest.sparkbutton.SparkButton
        android:id="@+id/spark_button"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:sparkbutton_activeImage="@drawable/active_image"
        app:sparkbutton_inActiveImage="@drawable/inactive_image"
        app:sparkbutton_iconSize="40dp"
        app:sparkbutton_primaryColor="@color/primary_color"
        app:sparkbutton_secondaryColor="@color/secondary_color" />

Java (Optional)

SparkButton button  = new SparkButtonBuilder(context)
            .setActiveImage(R.drawable.active_image)
            .setInActiveImage(R.drawable.inactive_image)
            .setDisabledImage(R.drawable.disabled_image)
            .setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
            .setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
            .setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
            .build();

bash export command

SHELL is an environment variable, and so it's not the most reliable for what you're trying to figure out. If your tool is using a shell which doesn't set it, it will retain its old value.

Use ps to figure out what's really going on.

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

I ran into this error in a different situation, posting the resolution for those arriving via search: from within Visual Studio, I had copied a file from one project and pasted into another. Turns out that creates a symbolic link, not an actual copy. Thus the project did not find the file in the current working directory as expected. When I made a physical copy instead, in Windows Explorer, suddenly #include "myfile.h" worked.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why?

Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do not want one can make the difference in certain circumstances.

So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).

Get Max value from List<myType>

var maxAge = list.Max(x => x.Age);

Clearing Magento Log Data

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
SET FOREIGN_KEY_CHECKS=1;

Run AVD Emulator without Android Studio

You can make a batch file, that will open your emulator directly without opening Android Studio. If you are using Windows:

  • Open Notepad

  • New file

  • Copy the next lines into your file:

     cd /d C:\Users\%username%\AppData\Local\Android\sdk\tools
     emulator @[YOUR_EMULATOR_DEVICE_NAME]
    

    Notes:

  • Replace [YOUR_EMULATOR_DEVICE_NAME] with the device name you created in emulator

  • To get the device name go to: C:\Users\%username%\AppData\Local\Android\sdk\tools

  • Run cmd and type: emulator -list-avds

  • Copy the device name and paste it in the batch file

  • Save the file as emulator.bat and close

  • Now double click on emulator.bat and you got the emulator running!

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

Foreign Key Django Model

I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

So, expanding on Martijn Pieters' answer:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        'app_label.Anniversary', on_delete=models.CASCADE)
    address = models.ForeignKey(
        'app_label.Address', on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Logging levels - Logback - rule-of-thumb to assign log levels

I answer this coming from a component-based architecture, where an organisation may be running many components that may rely on each other. During a propagating failure, logging levels should help to identify both which components are affected and which are a root cause.

  • ERROR - This component has had a failure and the cause is believed to be internal (any internal, unhandled exception, failure of encapsulated dependency... e.g. database, REST example would be it has received a 4xx error from a dependency). Get me (maintainer of this component) out of bed.

  • WARN - This component has had a failure believed to be caused by a dependent component (REST example would be a 5xx status from a dependency). Get the maintainers of THAT component out of bed.

  • INFO - Anything else that we want to get to an operator. If you decide to log happy paths then I recommend limiting to 1 log message per significant operation (e.g. per incoming http request).

For all log messages be sure to log useful context (and prioritise on making messages human readable/useful rather than having reams of "error codes")

  • DEBUG (and below) - Shouldn't be used at all (and certainly not in production). In development I would advise using a combination of TDD and Debugging (where necessary) as opposed to polluting code with log statements. In production, the above INFO logging, combined with other metrics should be sufficient.

A nice way to visualise the above logging levels is to imagine a set of monitoring screens for each component. When all running well they are green, if a component logs a WARNING then it will go orange (amber) if anything logs an ERROR then it will go red.

In the event of an incident you should have one (root cause) component go red and all the affected components should go orange/amber.

how to modify the size of a column

This was done using Toad for Oracle 12.8.0.49

ALTER TABLE SCHEMA.TABLENAME 
    MODIFY (COLUMNNAME NEWDATATYPE(LENGTH)) ;

For example,

ALTER TABLE PAYROLL.EMPLOYEES 
    MODIFY (JOBTITLE VARCHAR2(12)) ;

How to set Java environment path in Ubuntu

  1. Update bashrc file to add JAVA_HOME

    sudo nano ~/.bashrc

  2. Add JAVA_HOME to bashrc file.

    export JAVA_HOME=/usr/java/<your version of java>
    export PATH=${PATH}:${JAVA_HOME}/bin

  3. Ensure Java is accessible

    java -version

  4. In Case of Manual installation of JDK, If you got an error as shown below

    Error occurred during initialization of VM
    java/lang/NoClassDefFoundError: java/lang/Object
    
  5. Execute the following command in your JAVA_HOME/lib directory:

    unpack200 -r -v -l "" tools.pack tools.jar

  6. Execute the following commands in your JAVA_HOME/jre/lib

    ../../bin/unpack200 rt.pack rt.jar ../../bin/unpack200 jsse.pack jsse.rar ../../bin/unpack200 charsets.pack charsets.jar

  7. Ensure Java is accessible

    java -version

How do I make a file:// hyperlink that works in both IE and Firefox?

In case someone else finds this topic while using localhost in the file URIs - Internet Explorer acts completely different if the host name is localhost or 127.0.0.1 - if you use the actual hostname, it works fine (from trusted sites/intranet zone).

Another big difference between IE and FF - IE is fine with uris like file://server/share/file.txt but FF requires additional slashes file:////server/share/file.txt.

Get the new record primary key ID from MySQL insert query?

You need to use the LAST_INSERT_ID() function: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

Eg:

INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();

This will get you back the PRIMARY KEY value of the last row that you inserted:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client.

So the value returned by LAST_INSERT_ID() is per user and is unaffected by other queries that might be running on the server from other users.

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

If you want to make a change global to the whole notebook:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

How can I show data using a modal when clicking a table row (using bootstrap)?

The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:

  $.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
    $('#orderDetails').html(data);
  }, 'script')

Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:

  <% @restaurant.orders.each do |order| %>
  <!-- you should add more class and id attr to help control the DOM -->
  <tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id  %>);">
    <td class="order_id"><%= order.id %></td>
    <td class="customer_id"><%= order.customer_id %></td>
    <td class="status"><%= order.status %></td>
  </tr>
  <% end %>

js:

function orderModal(order_id){
  var tr = $('#order_' + order_id);
  // get the current info in html table 
  var customer_id = tr.find('.customer_id');
  var status = tr.find('.status');

  // U should work on lines here:
  var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
  $('#orderDetails').html(info_to_insert);

  $('#orderModal').modal({
    keyboard: true,
    backdrop: "static"
  });
};

That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.

Custom Drawable for ProgressBar/ProgressDialog

Custom progress with scale!

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_on"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_on"
            android:scaleGravity="center" />
    </item>

</animation-list>

What does the construct x = x || y mean?

Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.

var title = title || 'Error';
var msg   = msg || 'Error on Request';

Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:

  • false.
  • 0 (zero)
  • "" (empty string)
  • null.
  • undefined.
  • NaN (a special Number value meaning Not-a-Number!)

So in the line

var title = title || 'Error';

If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).

If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.

It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.

i.e.

return ("" || undefined)

returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running

var foo = undefined
foo = foo || ""

foo would be set to ""

Is there a way to get the XPath in Google Chrome?

First open your Google Chrome

and open any website

and inspect that

Override intranet compatibility mode IE8

I found a working answer that allow to override the checked Intranet Compatibility View. Just add in the OnInit event of your page this line (no meta or web.config customHeader need):

Response.AddHeader("X-UA-Compatible", "IE=EmulateIE8");

How do I mount a host directory as a volume in docker compose

we have to create your own docker volume mapped with the host directory before we mention in the docker-compose.yml as external

1.Create volume named share

docker volume create --driver local \
--opt type=none \
--opt device=/home/mukundhan/share \
--opt o=bind share

2.Use it in your docker-compose

version: "3"

volumes:
  share:
    external: true

services:
  workstation:
    container_name: "workstation"
    image: "ubuntu"
    stdin_open: true
    tty: true
    volumes:
      - share:/share:consistent
      - ./source:/source:consistent
    working_dir: /source
    ipc: host
    privileged: true
    shm_size: '2gb'
  db:
    container_name: "db"
    image: "ubuntu"
    stdin_open: true
    tty: true
    volumes:
      - share:/share:consistent
    working_dir: /source
    ipc: host

This way we can share the same directory with many services running in different containers

Change the row color in DataGridView based on the quantity of a cell value

If drv.Item("Quantity").Value < 5  Then

use this to like this

If Cint(drv.Item("Quantity").Value) < 5  Then

Correct way to quit a Qt program?

You can call qApp.exit();. I always use that and never had a problem with it.

If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.

How to use responsive background image in css3 in bootstrap

The file path 'images/ip-box.png' implies that the css file is at the same level as the images folder.

It's probably more common to have 'images' and 'css' folders at the same level as the 'index.html' file.

If that were the case and the css file were one level down in its respective folder, then the path to ip-box.jpg as specified in the css file would be: '../images/ip-box.png'

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

Android: checkbox listener

If you are looking to do this in Kotlin with the interface implementation.

class MainActivity: AppCompatActivity(),CompoundButton.OnCheckedChangeListener{

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

      val yourCheckBox = findViewById<CheckBox>(R.id.check_box)
      yourCheckBox.setOnCheckedChangeListener(this)

    }

 override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        when(buttonView?.id){
            R.id.check_box -> Log.d("Checked: ","$isChecked")
        }
    }

}

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

Use In instead of =

 select * from dbo.books
 where isbn in (select isbn from dbo.lending 
                where act between @fdate and @tdate
                and stat ='close'
               )

or you can use Exists

SELECT t1.*,t2.*
FROM  books   t1 
WHERE  EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
                t2.act between @fdate and @tdate and t2.stat ='close' )

Android replace the current fragment with another fragment

Latest Stuff

Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.

Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.

  1. Add Kotlin extension for Fragments to your project.

In your app level build.gradle file add the following,

dependencies {
    def fragment_version = "1.2.5"

    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
  1. Then simple code to replace the fragment,

In your activity

supportFragmentManager.commit {
    replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
    addToBackStack(null)
}

References

Check latest version of Fragment extension

More on Fragments

Replace single quotes in SQL Server

Try escaping the single quote with a single quote:

Replace(@strip, '''', '')

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

Why is it string.join(list) instead of list.join(string)?

The variables my_list and "-" are both objects. Specifically, they're instances of the classes list and str, respectively. The join function belongs to the class str. Therefore, the syntax "-".join(my_list) is used because the object "-" is taking my_list as an input.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Here is a variant of Hogan's answer which I use in SQL Server Express 2012:

SELECT RIGHT(CONCAT('000', field), 3)

Instead of worrying if the field is a string or not, I just CONCAT it, since it'll output a string anyway. Additionally if the field can be a NULL, using ISNULL might be required to avoid function getting NULL results.

SELECT RIGHT(CONCAT('000', ISNULL(field,'')), 3)

Git: Remove committed file after push

If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:

git rm --cache /path/to/file
git commit -am "Remove file"
git push

(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

typedef fixed length array

From R..'s answer:

However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.

Users who don't see that it's an array will most likely write something like this (which fails):

#include <stdio.h>

typedef int twoInts[2];

void print(twoInts *twoIntsPtr);
void intermediate (twoInts twoIntsAppearsByValue);

int main () {
    twoInts a;
    a[0] = 0;
    a[1] = 1;
    print(&a);
    intermediate(a);
    return 0;
}
void intermediate(twoInts b) {
    print(&b);
}

void print(twoInts *c){
    printf("%d\n%d\n", (*c)[0], (*c)[1]);
}

It will compile with the following warnings:

In function ‘intermediate’:
warning: passing argument 1 of ‘print’ from incompatible pointer type [enabled by default]
    print(&b);
     ^
note: expected ‘int (*)[2]’ but argument is of type ‘int **’
    void print(twoInts *twoIntsPtr);
         ^

And produces the following output:

0
1
-453308976
32767

Determine a string's encoding in C#

My finally working approach is to try potential candidates of expected encodings by detecting invalid characters in the strings created from the byte array by the encodings. If I don't encounter invalid characters, I suppose the tested encoding works fine for the tested data.

For me, having only Latin and German special characters to consider, in order to determine the proper encoding for a byte array, I try to detect invalid characters in a string with this method:

    /// <summary>
    /// detect invalid characters in string, use to detect improper encoding
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool DetectInvalidChars(string s)
    {
        const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
        return s.Any(ch => !(
            specialChars.Contains(ch) ||
            (ch >= '0' && ch <= '9') ||
            (ch >= 'a' && ch <= 'z') ||
            (ch >= 'A' && ch <= 'Z')));
    }

(NB: if you have other Latin-based languages to consider, you might want to adapt the specialChars const string in the code)

Then I use it like this (I only expect UTF-8 or Default encoding):

        // determine encoding by detecting invalid characters in string
        var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
        if (StringFuncs.DetectInvalidChars(invoiceXmlText))
            invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default

Angular 2 Routing run in new tab

Late to this one, but I just discovered an alternative way of doing it:

On your template,

<a (click)="navigateAssociates()">Associates</a> 

And on your component.ts, you can use serializeUrl to convert the route into a string, which can be used with window.open()

navigateAssociates() {
  const url = this.router.serializeUrl(
    this.router.createUrlTree(['/page1'])
  );

  window.open(url, '_blank');
}

How to change spinner text size and text color?

Can change the text colour by overriding the getView method as follows:

 new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, list()){
                @Override
                public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    //change the color to which ever you want                    
                    ((CheckedTextView) view).setTextColor(Color.RED);
                    //change the size to which ever you want                    
                    ((CheckedTextView) view).setTextSize(5);
                    //for using sp values use setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    return view;
                }
    }

Applying a single font to an entire website with CSS

Ensure that mobile devices won't change the font with their default font by using important along with the universal selector * :

* { font-family: Algerian !important;}

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I think that the best solution currently for springBoot 2.0 is using profiles

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
public class ExcludeAutoConfigIntegrationTest {
    // ...
} 

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

anyway in the following link give 6 different alternatives to solve this.

How to use ArrayAdapter<myClass>

I think this is the best approach. Using generic ArrayAdapter class and extends your own Object adapter is as simple as follows:

public abstract class GenericArrayAdapter<T> extends ArrayAdapter<T> {

  // Vars
  private LayoutInflater mInflater;

  public GenericArrayAdapter(Context context, ArrayList<T> objects) {
    super(context, 0, objects);
    init(context);
  }

  // Headers
  public abstract void drawText(TextView textView, T object);

  private void init(Context context) {
    this.mInflater = LayoutInflater.from(context);
  }

  @Override public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
      convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
      vh = new ViewHolder(convertView);
      convertView.setTag(vh);
    } else {
      vh = (ViewHolder) convertView.getTag();
    }

    drawText(vh.textView, getItem(position));

    return convertView;
  }

  static class ViewHolder {

    TextView textView;

    private ViewHolder(View rootView) {
      textView = (TextView) rootView.findViewById(android.R.id.text1);
    }
  }
}

and here your adapter (example):

public class SizeArrayAdapter extends GenericArrayAdapter<Size> {

  public SizeArrayAdapter(Context context, ArrayList<Size> objects) {
    super(context, objects);
  }

  @Override public void drawText(TextView textView, Size object) {
    textView.setText(object.getName());
  }

}

and finally, how to initialize it:

ArrayList<Size> sizes = getArguments().getParcelableArrayList(Constants.ARG_PRODUCT_SIZES);
SizeArrayAdapter sizeArrayAdapter = new SizeArrayAdapter(getActivity(), sizes);
listView.setAdapter(sizeArrayAdapter);

I've created a Gist with TextView layout gravity customizable ArrayAdapter:

https://gist.github.com/m3n0R/8822803

Extract a single (unsigned) integer from a string

Follow this step it will convert string to number

$value = '$0025.123';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
settype($onlyNumeric,"float");

$result=($onlyNumeric+100);
echo $result;

Another way to do it :

$res = preg_replace("/[^0-9.]/", "", "$15645623.095605659");

Windows 7, 64 bit, DLL problems

This problem is related to missing the Visual Studio "redistributable package." It is not obvious which one is missing based on the dependency walk, but I would try the one that corresponds with your compiler version first and see if things run properly:

Visual Studio 2015

Visual Studio 2013

Visual Studio 2010

Visual Studio 2008

I ran into this problem because I am using the Visual Studio compilers, but not the full Visual Studio environment.


Going to dare to inject a new link here: The latest supported Visual C++ downloads. Stein Åsmul, 29.11.2018.

Disabling the button after once click

Use modern Js events, with "once"!

const button = document.getElementById(btnId);
button.addEventListener("click", function() {
    // Submit form
}, {once : true});

// Disabling works too, but this is a more standard approach for general one-time events

Documentation, CanIUse

ASP.Net which user account running Web Service on IIS 7?

Server 2008

Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.

In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity

Here's the info from Microsoft on setting up Application Pool Identites:

http://learn.iis.net/page.aspx/624/application-pool-identities/

NULL vs nullptr (Why was it replaced?)

You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

This problem falls into the following categories:

  • Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.

  • Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

  • Make C++ easier to teach and learn.

How to Copy Text to Clip Board in Android?

Here the method to copy text to clipboard:

private void setClipboard(Context context, String text) {
  if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(text);
  } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
    clipboard.setPrimaryClip(clip);
  }
}

This method is working on all android devices.

How to insert pandas dataframe via mysqldb into database?

The to_sql method works for me.

However, keep in mind that the it looks like it's going to be deprecated in favor of SQLAlchemy:

FutureWarning: The 'mysql' flavor with DBAPI connection is deprecated and will be removed in future versions. MySQL will be further supported with SQLAlchemy connectables. chunksize=chunksize, dtype=dtype)

How to sum up elements of a C++ vector?

I'm a Perl user, an a game we have is to find every different ways to increment a variable... that's not really different here. The answer to how many ways to find the sum of the elements of a vector in C++ is probably an infinity...

My 2 cents:

Using BOOST_FOREACH, to get free of the ugly iterator syntax:

sum = 0;
BOOST_FOREACH(int & x, myvector){
  sum += x;
}

iterating on indices (really easy to read).

int i, sum = 0;
for (i=0; i<myvector.size(); i++){
  sum += myvector[i];
}

This other one is destructive, accessing vector like a stack:

while (!myvector.empty()){
   sum+=myvector.back();
   myvector.pop_back();
}

How does numpy.newaxis work and when to use it?

What is np.newaxis?

The np.newaxis is just an alias for the Python constant None, which means that wherever you use np.newaxis you could also use None:

>>> np.newaxis is None
True

It's just more descriptive if you read code that uses np.newaxis instead of None.

How to use np.newaxis?

The np.newaxis is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis represents where I want to add dimensions.

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)

In the first example I use all elements from the first dimension and add a second dimension:

>>> a[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> a[:, np.newaxis].shape
(10, 1)

The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:

>>> a[np.newaxis, :]  # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)

Similarly you can use multiple np.newaxis to add multiple dimensions:

>>> a[np.newaxis, :, np.newaxis]  # note the 3 [] pairs in the output
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)

Are there alternatives to np.newaxis?

There is another very similar functionality in NumPy: np.expand_dims, which can also be used to insert one dimension:

>>> np.expand_dims(a, 1)  # like a[:, np.newaxis]
>>> np.expand_dims(a, 0)  # like a[np.newaxis, :]

But given that it just inserts 1s in the shape you could also reshape the array to add these dimensions:

>>> a.reshape(a.shape + (1,))  # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape)  # like a[np.newaxis, :]

Most of the times np.newaxis is the easiest way to add dimensions, but it's good to know the alternatives.

When to use np.newaxis?

In several contexts is adding dimensions useful:

  • If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow to display a 1D array.

  • If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]. This works because NumPy operations broadcast starting with the last dimension 1.

  • To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.


1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis:

>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[  1.,   2.,   3.],
       [ 11.,  12.,  13.],
       [ 21.,  22.,  23.],
       [ 31.,  32.,  33.]])

How to produce an csv output file from stored procedure in SQL Server

I have tried this and it is working fine for me:

sqlcmd -S servername -E -s~ -W -k1 -Q  "sql query here" > "\\file_path\file_name.csv"

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

Regular expression that matches valid IPv6 addresses

Try this small one-liner. It should only match valid uncompressed/compressed IPv6 addresses (no IPv4 hybrids)

/(?!.*::.*::)(?!.*:::.*)(?!:[a-f0-9])((([a-f0-9]{1,4})?[:](?!:)){7}|(?=(.*:[:a-f0-9]{1,4}::|^([:a-f0-9]{1,4})?::))(([a-f0-9]{1,4})?[:]{1,2}){1,6})[a-f0-9]{1,4}/

Storing image in database directly or as base64 data?

I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database

Retrieving the last record in each group - MySQL

The below query will work fine as per your question.

SELECT M1.* 
FROM MESSAGES M1,
(
 SELECT SUBSTR(Others_data,1,2),MAX(Others_data) AS Max_Others_data
 FROM MESSAGES
 GROUP BY 1
) M2
WHERE M1.Others_data = M2.Max_Others_data
ORDER BY Others_data;

Button text toggle in jquery

I preffer the following way, it can be used by any button.

<button class='pushme' data-default-text="PUSH ME" data-new-text="DON'T PUSH ME">PUSH ME</button>

$(".pushme").click(function () {
    var $element = $(this);
    $element.text(function(i, text) {
        return text == $element.data('default-text') ? $element.data('new-text')
                                                     : $element.data('default-text');
    });
});

demo

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

Error message "No exports were found that match the constraint contract name"

This will really work like a champ:

Solution: Try to delete ComponentModelCache folder from the below location.

[C:]\Users\[your user name]\AppData\Local\Microsoft\VisualStudio\[Visual Studio version number]

And after successful delete, recreate the folder with the same name, "ComponentModelCache".

Best practice to return errors in ASP.NET Web API

Building up upon Manish Jain's answer (which is meant for Web API 2 which simplifies things):

1) Use validation structures to response as many validation errors as possible. These structures can also be used to response to requests coming from forms.

public class FieldError
{
    public String FieldName { get; set; }
    public String FieldMessage { get; set; }
}

// a result will be able to inform API client about some general error/information and details information (related to invalid parameter values etc.)
public class ValidationResult<T>
{
    public bool IsError { get; set; }

    /// <summary>
    /// validation message. It is used as a success message if IsError is false, otherwise it is an error message
    /// </summary>
    public string Message { get; set; } = string.Empty;

    public List<FieldError> FieldErrors { get; set; } = new List<FieldError>();

    public T Payload { get; set; }

    public void AddFieldError(string fieldName, string fieldMessage)
    {
        if (string.IsNullOrWhiteSpace(fieldName))
            throw new ArgumentException("Empty field name");

        if (string.IsNullOrWhiteSpace(fieldMessage))
            throw new ArgumentException("Empty field message");

        // appending error to existing one, if field already contains a message
        var existingFieldError = FieldErrors.FirstOrDefault(e => e.FieldName.Equals(fieldName));
        if (existingFieldError == null)
            FieldErrors.Add(new FieldError {FieldName = fieldName, FieldMessage = fieldMessage});
        else
            existingFieldError.FieldMessage = $"{existingFieldError.FieldMessage}. {fieldMessage}";

        IsError = true;
    }

    public void AddEmptyFieldError(string fieldName, string contextInfo = null)
    {
        AddFieldError(fieldName, $"No value provided for field. Context info: {contextInfo}");
    }
}

public class ValidationResult : ValidationResult<object>
{

}

2) Service layer will return ValidationResults, regardless of operation being successful or not. E.g:

    public ValidationResult DoSomeAction(RequestFilters filters)
    {
        var ret = new ValidationResult();

        if (filters.SomeProp1 == null) ret.AddEmptyFieldError(nameof(filters.SomeProp1));
        if (filters.SomeOtherProp2 == null) ret.AddFieldError(nameof(filters.SomeOtherProp2 ), $"Failed to parse {filters.SomeOtherProp2} into integer list");

        if (filters.MinProp == null) ret.AddEmptyFieldError(nameof(filters.MinProp));
        if (filters.MaxProp == null) ret.AddEmptyFieldError(nameof(filters.MaxProp));


        // validation affecting multiple input parameters
        if (filters.MinProp > filters.MaxProp)
        {
            ret.AddFieldError(nameof(filters.MinProp, "Min prop cannot be greater than max prop"));
            ret.AddFieldError(nameof(filters.MaxProp, "Check"));
        }

        // also specify a global error message, if we have at least one error
        if (ret.IsError)
        {
            ret.Message = "Failed to perform DoSomeAction";
            return ret;
        }

        ret.Message = "Successfully performed DoSomeAction";
        return ret;
    }

3) API Controller will construct the response based on service function result

One option is to put virtually all parameters as optional and perform custom validation which return a more meaningful response. Also, I am taking care not to allow any exception to go beyond the service boundary.

    [Route("DoSomeAction")]
    [HttpPost]
    public HttpResponseMessage DoSomeAction(int? someProp1 = null, string someOtherProp2 = null, int? minProp = null, int? maxProp = null)
    {
        try
        {
            var filters = new RequestFilters 
            {
                SomeProp1 = someProp1 ,
                SomeOtherProp2 = someOtherProp2.TrySplitIntegerList() ,
                MinProp = minProp, 
                MaxProp = maxProp
            };

            var result = theService.DoSomeAction(filters);
            return !result.IsError ? Request.CreateResponse(HttpStatusCode.OK, result) : Request.CreateResponse(HttpStatusCode.BadRequest, result);
        }
        catch (Exception exc)
        {
            Logger.Log(LogLevel.Error, exc, "Failed to DoSomeAction");
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError("Failed to DoSomeAction - internal error"));
        }
    }

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

Simply run:

npm uninstall bcrypt

Followed by:

npm install bcrypt (or npm install, if bcrypt is declared as dependency in your package.json file)

html <input type="text" /> onchange event not working

onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

Read more about the change event here

Read more about the input event here

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

How Long Does it Take to Learn Java for a Complete Newbie?

10 weeks? Apparently you can do it in 24 hours!

http://www.amazon.com/Sams-Teach-Yourself-Programming-Hours/dp/0672328445

EDIT:

Okay, so only 1 person found my answer amusing, but not amusing enough to upvote. The real question is how good do you need to be in 10 weeks?

If you get yourself a good book (the one linked above has some good reviews on Amazon), then in 10 weeks you might be proficient enough to do something useful in Java, but it takes years to become expert. Any time spent between 10 weeks and several years will move you from beginner towards expert.

Oh and read Teach Yourself Programming in Ten Years.

MySQL WHERE: how to write "!=" or "not equals"?

The != operator most certainly does exist! It is an alias for the standard <> operator.

Perhaps your fields are not actually empty strings, but instead NULL?

To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

How to install PostgreSQL's pg gem on Ubuntu?

Try this

sudo apt-get install postgresql postgresql-contrib libpq-dev

You should install PG Database server in the first place to install clients. Afterwards, you install clients.

See this blog post to know about setting up PostGresSQL for the first time for Ruby on Rails development.

cleanest way to skip a foreach if array is empty

i've got the following function in my "standard library"

/// Convert argument to an array.
function a($a = null) {
    if(is_null($a))
        return array();
    if(is_array($a))
        return $a;
    if(is_object($a))
        return (array) $a;
    return $_ = func_get_args();
}

Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions

  foreach(a($whatever) as $item)....

  $foo = array_map(a($array_or_string)....

  etc

Private Variables and Methods in Python

Because thats coding convention. See here for more.

Creating a Custom Event

Based on @ionden's answer, the call to the delegate could be simplified using null propagation since C# 6.0.

Your code would simply be:

class MyClass {
    public event EventHandler MyEvent;

    public void Method() {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

Use it like this:

MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();

onclick on a image to navigate to another page using Javascript

I'd set up your HTML like so:

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />

Then use the following code:

<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function(event) {
         window.location.href = this.id + '.html';
    };
}
</script>

That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

What's the syntax to import a class in a default package in Java?

As others have said, this is bad practice, but if you don't have a choice because you need to integrate with a third-party library that uses the default package, then you could create your own class in the default package and access the other class that way. Classes in the default package basically share a single namespace, so you can access the other class even if it resides in a separate JAR file. Just make sure the JAR file is in the classpath.

This trick doesn't work if your class is not in the default package.

Getting "Cannot call a class as a function" in my React Project

For me it was because i used prototype instead of propTypes

class MyComponent extends Component {

 render() {
    return <div>Test</div>;
  }
}

MyComponent.prototype = {

};

it ought to be

MyComponent.propTypes = {

};

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

m2eclipse not finding maven dependencies, artifacts not found

I had problems with using m2eclipse (i.e. it did not appear to be installed at all) but I develop a project using IAM - maven plugin for eclipse supported by Eclipse Foundation (or hosted or something like that).

I had sometimes problems as sometimes some strange error appeared for project (it couldn't move something) but simple command (run from eclipse as task or from console) + refresh (F5) solved all problems:

mvn clean

However please note that I created project in eclipse. However I modified pom.xml by hand.

How to increase Java heap space for a tomcat app

For Windows Service, you need to run tomcat9w.exe (or 6w/7w/8w) depending on your version of tomcat. First, make sure tomcat is stopped. Then double click on tomcat9w.exe. Navigate to the Java tab. If you know you have 64 bit Windows with 64 bit Java and 64 bit Tomcat, then feel free to set the memory higher than 512. You'll need to do some task manager monitoring to determine how high to set it. For most apps developed in 2019... I'd recommend an initial memory pool of 1024, and the maximum memory pool of 2048. Of course if your computer has tons of RAM... feel free to go as high as you want. Also, see this answer: How to increase Maximum Memory Pool Size? Apache Tomcat 9

Add Insecure Registry to Docker

Create /etc/docker/daemon.json file where you want to pull docker images and add the following content to that file

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Refer to my blog article for an in-depth explanation of creating a private docker registry: https://geekdosage.com/how-to-create-a-private-docker-registry-in-ubuntu-20-04/

rejected master -> master (non-fast-forward)

My Remote was not in sync with the local so this worked for me

git pull --rebase

and make sure when you do git pull again it should say Already up to date and now you are ready to push to origin

assuming you have already git remote add origin remote repository URL

do

`git push origin master`  

The Screenshot says it all enter image description here

Alternatively you can do this

  1. git stash (stores uncommited work temporarily)
  2. git pull (make your local and remote in sync)
  3. git stash pop (get back you uncommited changes )
  4. git push

How to transition to a new view controller with code only using Swift

SWIFT

Usually for normal transition we use,

let next:SecondViewController = SecondViewController()
self.presentViewController(next, animated: true, completion: nil)

But sometimes when using navigation controller, you might face a black screen. In that case, you need to use like,

let next:ThirdViewController = storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController
self.navigationController?.pushViewController(next, animated: true)

Moreover none of the above solution preserves navigationbar when you call from storyboard or single xib to another xib. If you use nav bar and want to preserve it just like normal push, you have to use,

Let's say, "MyViewController" is identifier for MyViewController

let viewController = MyViewController(nibName: "MyViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)

Format number as percent in MS SQL Server

M.Ali's answer could be modified as

select Cast(Cast((37.0/38.0)*100 as decimal(18,2)) as varchar(5)) + ' %' as Percentage

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This one disables all bogus verbs and only allows GET and POST

<system.webServer>
  <security>
    <requestFiltering>
      <verbs allowUnlisted="false">
    <clear/>
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

How to check that a string is parseable to a double?

All answers are OK, depending on how academic you want to be. If you wish to follow the Java specifications accurately, use the following:

private static final Pattern DOUBLE_PATTERN = Pattern.compile(
    "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
    "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
    "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
    "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");

public static boolean isFloat(String s)
{
    return DOUBLE_PATTERN.matcher(s).matches();
}

This code is based on the JavaDocs at Double.

Converting URL to String and back again

Swift 3 version code:

let urlString = "file:///Users/Documents/Book/Note.txt"
let pathURL = URL(string: urlString)!
print("the url = " + pathURL.path)

How to find out whether a file is at its `eof`?

Get the EOF position of the file:

def get_eof_position(file_handle):
    original_position = file_handle.tell()
    eof_position = file_handle.seek(0, 2)
    file_handle.seek(original_position)
    return eof_position

and compare it with the current position: get_eof_position == file_handle.tell().

How do I revert all local changes in Git managed project to previous state?

DANGER AHEAD: (please read the comments. Executing the command proposed in my answer might delete more than you want)

to completely remove all files including directories I had to run

git clean -f -d

How to get the file name from a full path using JavaScript?

<html>
    <head>
        <title>Testing File Upload Inputs</title>
        <script type="text/javascript">
            <!--
            function showSrc() {
                document.getElementById("myframe").href = document.getElementById("myfile").value;
                var theexa = document.getElementById("myframe").href.replace("file:///","");
                alert(document.getElementById("myframe").href.replace("file:///",""));
            }
            // -->
        </script>
    </head>
    <body>
        <form method="get" action="#"  >
            <input type="file" 
                   id="myfile" 
                   onChange="javascript:showSrc();" 
                   size="30">
            <br>
            <a href="#" id="myframe"></a>
        </form>
    </body>
</html>

How to write the code for the back button?

<a href="javascript:history.back(1)">Back</a>

this one (by Eiko) is perfect, use css to make a button of <a>... eg you can use this css class in <a> as `

<a class=".back_button" href="javascript:history.back(1)">Back</a>`

.back_button {
display:block;
width:100px;
height:30px;
text-align:center;
background-color:yellow;
border:1px solid #000000;
}

Setting up an MS-Access DB for multi-user access

The first thing to do (if not already done) is to split your database into a front end (with all the forms/reports etc) and a back end(with all the data). The second thing is to setup version control on the front end.

The way I have done that in a lot of my databases is to have the users run a small “jumper” database to open the main database. This jumper does the following things

• Checks to see if the user has the database on their C drive

• If they do not then install and run

• If they do then check what version they have

• If the version numbers do not match then copy down the latest version

• Open the database

This whole checking process normally takes under half a second. Using this model you can do all your development on a separate database then when you are ready to “release” you just put the new mde up onto the network share and the next time the user opens the jumper the latest version is copied down.

There are also other things to think about in multiuser database and it might be worth checking for the common mistakes such as binding a form to a whole table etc

How can I determine if a String is non-null and not only whitespace in Groovy?

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

How to use Bash to create a folder if it doesn't already exist?

I think you should re-format your code a bit:

#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
    mkdir -p /home/mlzboy/b2c2/shared/db;
fi;

Objective-C: Reading a file line by line

Here's a nice simple solution i use for smaller files:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Terrain1" ofType:@"txt"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\r\n"]];
for (NSString* line in lines) {
    if (line.length) {
        NSLog(@"line: %@", line);
    }
}

What is the difference between require and require-dev sections in composer.json?

  1. According to composer's manual:

    require-dev (root-only)

    Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

    So running composer install will also download the development dependencies.

  2. The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.

Pandas count(distinct) equivalent

Using crosstab, this will return more information than groupby nunique

pd.crosstab(df.YEARMONTH,df.CLIENTCODE)
Out[196]: 
CLIENTCODE  1  2  3
YEARMONTH          
201301      2  1  0
201302      1  2  1

After a little bit modify ,yield the result

pd.crosstab(df.YEARMONTH,df.CLIENTCODE).ne(0).sum(1)
Out[197]: 
YEARMONTH
201301    2
201302    3
dtype: int64

Add a linebreak in an HTML text area

I believe this will work:

TextArea.Text = "Line 1" & vbCrLf & "Line 2"

System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.

How to use both onclick and target="_blank"

onclick="window.open('your_html', '_blank')"

Object of custom type as dictionary key

You override __hash__ if you want special hash-semantics, and __cmp__ or __eq__ in order to make your class usable as a key. Objects who compare equal need to have the same hash value.

Python expects __hash__ to return an integer, returning Banana() is not recommended :)

User defined classes have __hash__ by default that calls id(self), as you noted.

There is some extra tips from the documentation.:

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

Why do I get "'property cannot be assigned" when sending an SMTP email?

This just worked for me as of March 2017. Started with solution from above "Finally got working :)" which didn't work at first.

SmtpClient client = new SmtpClient();
client.Port =  587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("<me>@gmail.com", "<my pw>");
MailMessage mm = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

Add a link to an image in a css style sheet

You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.

Based only on your style you would have:

<a href="home.com" id="logo"></a>

Python - How do you run a .py file?

use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.

How to download/upload files from/to SharePoint 2013 using CSOM?

Just a suggestion SharePoint 2013 online & on-prem file encoding is UTF-8 BOM. Make sure your file is UTF-8 BOM, otherwise your uploaded html and scripts may not rendered correctly in browser.

How To Pass GET Parameters To Laravel From With GET Method ?

The simplest way is just to accept the incoming request, and pull out the variables you want in the Controller:

Route::get('search', ['as' => 'search', 'uses' => 'SearchController@search']);

and then in SearchController@search:

class SearchController extends BaseController {

    public function search()
    {
        $category = Input::get('category', 'default category');
        $term = Input::get('term', false);

        // do things with them...
    }
}

Usefully, you can set defaults in Input::get() in case nothing is passed to your Controller's action.

As joe_archer says, it's not necessary to put these terms into the URL, and it might be better as a POST (in which case you should update your call to Form::open() and also your search route in routes.php - Input::get() remains the same)

How do I break out of a loop in Scala?

The third-party breakable package is one possible alternative

https://github.com/erikerlandson/breakable

Example code:

scala> import com.manyangled.breakable._
import com.manyangled.breakable._

scala> val bkb2 = for {
     |   (x, xLab) <- Stream.from(0).breakable   // create breakable sequence with a method
     |   (y, yLab) <- breakable(Stream.from(0))  // create with a function
     |   if (x % 2 == 1) continue(xLab)          // continue to next in outer "x" loop
     |   if (y % 2 == 0) continue(yLab)          // continue to next in inner "y" loop
     |   if (x > 10) break(xLab)                 // break the outer "x" loop
     |   if (y > x) break(yLab)                  // break the inner "y" loop
     | } yield (x, y)
bkb2: com.manyangled.breakable.Breakable[(Int, Int)] = com.manyangled.breakable.Breakable@34dc53d2

scala> bkb2.toVector
res0: Vector[(Int, Int)] = Vector((2,1), (4,1), (4,3), (6,1), (6,3), (6,5), (8,1), (8,3), (8,5), (8,7), (10,1), (10,3), (10,5), (10,7), (10,9))

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

Determining the current foreground application from a background task or service

This worked for me. But it gives only the main menu name. That is if user has opened Settings --> Bluetooth --> Device Name screen, RunningAppProcessInfo calls it as just Settings. Not able to drill down furthur

ActivityManager activityManager = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
                PackageManager pm = context.getPackageManager();
                List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
                for(RunningAppProcessInfo appProcess : appProcesses) {              
                    if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(appProcess.processName, PackageManager.GET_META_DATA));
                        Log.i("Foreground App", "package: " + appProcess.processName + " App: " + c.toString());
                    }               
                }

Clear all fields in a form upon going back with browser back button

Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).

If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:

window.addEventListener("pageshow", () => {
  // update hidden input field
});

See more details for Gecko and WebKit implementations.