Programs & Examples On #Distributed programming

Trying to get Laravel 5 email to work

Finally I got! Just to share, there are more config than just .env

This is .env

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

[email protected]

MAIL_PASSWORD=********

MAIL_ENCRYPTION=tls

config/mail.php also need to input address & name for it to work.

'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 587),
'from' => ['address' => '[email protected]' , 'name' => 'YourName' ],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,

Memcached vs. Redis?

Memcached is good at being a simple key/value store and is good at doing key => STRING. This makes it really good for session storage.

Redis is good at doing key => SOME_OBJECT.

It really depends on what you are going to be putting in there. My understanding is that in terms of performance they are pretty even.

Also good luck finding any objective benchmarks, if you do find some kindly send them my way.

replace String with another in java

     String s1 = "HelloSuresh";
     String m = s1.replace("Hello","");
     System.out.println(m);

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

How to sum all column values in multi-dimensional array?

example array here

Code here:

        $temp_arr = [];
        foreach ($a as $k => $v) {
            if(!is_null($v)) {
                $sum = isset($temp_arr[$v[0]]) ? ((int)$v[5] + $sum) : (int)$v[5];
                $temp_arr[$v[0]] = $sum;
            }
        }
        return $temp_arr;

Result:

{SEQ_OK: 1328,SEQ_ERROR: 561}

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

Reset IntelliJ UI to Default

From the main menu, select File | Manage IDE Settings | Restore Default Settings.

Alternatively, press Shift twice and type Restore default settings

Get request URL in JSP which is forwarded by Servlet

If you use RequestDispatcher.forward() to route the request from controller to the view, then request URI is exposed as a request attribute named javax.servlet.forward.request_uri. So, you can use

request.getAttribute("javax.servlet.forward.request_uri")

or

${requestScope['javax.servlet.forward.request_uri']}

Global variables in AngularJS

localStorage.username = 'blah'

If you're guaranteed to be on a modern browser. Though know your values will all be turned into strings.

Also has the handy benefit of being cached between reloads.

Find the smallest positive integer that does not occur in a given sequence

My solution having 100% result in codility with Swift 4.

func solution(_ A : [Int]) -> Int {
    let positive = A.filter { $0 > 0 }.sorted()
    var x = 1
    for val in positive{
        if(x < val) {
            return x
        }
        x = val + 1
    }
    return x
}

How do I restart my C# WinForm Application?

Take for instance an application that:

  1. While application is not registered; (upon start) the application should prompt the user to register the application and create a login account.

  2. Once registration is submitted and login credentials are created; the application should restart, check for registration and prompt the user to login with the inserted credentials (so the user can access to all the application features).

Problem: By building and launching the application from Visual Studio; any of the 4 alternatives bellow will fail to accomplish the tasks required.

/*
 * Note(s):
 * Take into consideration that the lines bellow don't represent a code block.
 * They are just a representation of possibilities,
 * that can be used to restart the application.
 */

Application.Restart();
Application.Exit();
Environment.Exit(int errorCode);
Process.GetCurrentProcess().Kill();

What happens is: After creating the Registration, Login and calling Application.Restart(); the application will (strangely) reopen the Registration Form and skip data in a Database (even though the resource is set to "Copy if Newer").

Solution: Batch Building the application was (for me) a proof that any of the lines above were actually working as expected. Just not when building and running the application with Visual Studio.

In first place I'd try batch building the application; run it outside Visual Studio and check if Application.Restart() actually works as expected.

Also Check further Info regarding this thread subject: How do I restart my C# WinForm Application?

How to get the number of days of difference between two dates on mysql?

What about the DATEDIFF function ?

Quoting the manual's page :

DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation


In your case, you'd use :

mysql> select datediff('2010-04-15', '2010-04-12');
+--------------------------------------+
| datediff('2010-04-15', '2010-04-12') |
+--------------------------------------+
|                                    3 | 
+--------------------------------------+
1 row in set (0,00 sec)

But note the dates should be written as YYYY-MM-DD, and not DD-MM-YYYY like you posted.

c# write text on bitmap

You need to use the Graphics class in order to write on the bitmap.

Specifically, one of the DrawString methods.

Bitmap a = new Bitmap(@"path\picture.bmp");

using(Graphics g = Graphics.FromImage(a))
{
  g.DrawString(....); // requires font, brush etc
}

pictuteBox1.Image = a;

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

Thanks to Joachim answer, I use the code to clear all back stack entry finally.

// In your FragmentActivity use getSupprotFragmentManager() to get the FragmentManager.

// Clear all back stack.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
for (int i = 0; i < backStackCount; i++) {

    // Get the back stack fragment id.
    int backStackId = getSupportFragmentManager().getBackStackEntryAt(i).getId();

    getSupportFragmentManager().popBackStack(backStackId, 
        FragmentManager.POP_BACK_STACK_INCLUSIVE);

} /* end of for */

Why are you not able to declare a class as static in Java?

So, I'm coming late to the party, but here's my two cents - philosophically adding to Colin Hebert's answer.

At a high level your question deals with the difference between objects and types. While there are many cars (objects), there is only one Car class (type). Declaring something as static means that you are operating in the "type" space. There is only one. The top-level class keyword already defines a type in the "type" space. As a result "public static class Car" is redundant.

android adb turn on wifi via adb

No need to edit any database directly, there is a command for it :)

svc wifi [enable|disable]

splitting a string based on tab in the file

Split on tab, but then remove all blank matches.

text = "hi\tthere\t\t\tmy main man"
print [splits for splits in text.split("\t") if splits is not ""]

Outputs:

['hi', 'there', 'my main man']

MySQL Insert query doesn't work with WHERE clause

You use the WHERE clause for UPDATE queries. When you INSERT, you are assuming that the row doesn't exist.

The OP's statement would then become;

UPDATE Users SET weight = 160, desiredWeight = 45 where id = 1;

In MySQL, if you want to INSERT or UPDATE, you can use the REPLACE query with a WHERE clause. If the WHERE doesn't exist, it INSERTS, otherwise it UPDATES.

EDIT

I think that Bill Karwin's point is important enough to pull up out of the comments and make it very obvious. Thanks Bill, it has been too long since I have worked with MySQL, I remembered that I had issues with REPLACE, but I forgot what they were. I should have looked it up.

That's not how MySQL's REPLACE works. It does a DELETE (which may be a no-op if the row does not exist), followed by an INSERT. Think of the consequences vis. triggers and foreign key dependencies. Instead, use INSERT...ON DUPLICATE KEY UPDATE.

Best way to get application folder path

In my experience, the best way is a combination of these.

  1. System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase Will give you the bin folder
  2. Directory.GetCurrentDirectory() Works fine on .Net Core but not .Net and will give you the root directory of the project
  3. System.AppContext.BaseDirectory and AppDomain.CurrentDomain.BaseDirectory Works fine in .Net but not .Net core and will give you the root directory of the project

In a class library that is supposed to target.Net and .Net core I check which framework is hosting the library and pick one or the other.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

On a related note: the java compiler uses int to represent boolean since JVM has a limited support for the boolean type.See Section 3.3.4 The boolean type.

In JVM, the integer zero represents false, and any non-zero integer represents true (Source : Inside Java Virtual Machine by Bill Venners)

Cannot find Dumpbin.exe

You probably need to open a command prompt with the PATH set up properly. Look for an icon in the start menu that says something like "Visual C++ 2005 Command Prompt". You should be able to run dumpbin (and all the other command line tools) from there.

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

Create view with primary key?

You cannot create a primary key on a view. In SQL Server you can create an index on a view but that is different to creating a primary key.

If you give us more information as to why you want a key on your view, perhaps we can help with that.

Editing hosts file to redirect url?

Apply this trick.

First you need IP address of url you want to redirect to. Lets say you want to redirect to stackoverflow.com To find it, use the ping command in a Command Prompt. Type in:

ping stackoverflow.com

into the command prompt window and you’ll see stackoverflow's numerical IP address. Now use that IP into your host file

104.16.36.249 google.com

yay now google is serving stackoverflow :)

Aliases in Windows command prompt

If you're just going for some simple commands, you could follow these steps:

  1. Create a folder called C:\Aliases
  2. Add C:\Aliases to your path (so any files in it will be found every time)
  3. Create a .bat file in C:\Aliases for each of the aliases you want

Maybe overkill, but unlike the (otherwise excellent) answer from @Argyll, this solves the problem of this loading every time.

For instance, I have a file called dig2.bat with the following in it:

@echo off
echo.
dig +noall +answer %1

Your np file would just have the following:

@echo off
echo.
notepad++.exe %1

Then just add the C:\Aliases folder to your PATH environment variable. If you have CMD or PowerShell already opened you will need to restart it.

FWIW, I have about 20 aliases (separate .bat files) in my C:\Aliases directory - I just create new ones as necessary. Maybe not the neatest, but it works fine.

UPDATE: Per an excellent suggestion from user @Mav, it's even better to use %* rather than %1, so you can pass multiple files to the command, e.g.:

@echo off
echo.
notepad++.exe %*

That way, you could do this:

np c:\temp\abc.txt c:\temp\def.txt c:\temp\ghi.txt

and it will open all 3 files.

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.

Global approach

Configure Git line endings handling on Linux or OS X:

git config --global core.autocrlf input

Configure Git line endings handling on Windows:

git config --global core.autocrlf true

Per-repo approach:

In the root of your repo, create a .gitattributes file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings where line-ending-settings is one of the following:

  • text
  • binary (files that Git should not modify line endings for - as this can cause some image types such as PNGs not to render in a browser)

The text value can be configured further to instruct Git on how to handle line endings for matching files:

  • text - Changes line endings to OS native line endings.
  • text eol=crlf - Converts line endings to CRLF on checkout.
  • text eol=lf - Converts line endings to LF on checkout.
  • text=auto - Sensible default that leaves line handle up to Git's discretion.

Here is the content of a sample .gitattributes file:

# Set the default behavior for all files.
* text=auto

# Normalized and converts to 
# native line endings on checkout.
*.c text
*.h text

# Convert to CRLF line endings on checkout.
*.sln text eol=crlf

# Convert to LF line endings on checkout.
*.sh text eol=lf

# Binary files.
*.png binary
*.jpg binary

More on how to refresh your repo after changing line endings settings here. Tldr:

backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.

git add . -u

git commit -m "Saving files before refreshing line endings"

Remove the index and force Git to rescan the working directory.

rm .git/index

Rewrite the Git index to pick up all the new line endings.

git reset

Show the rewritten, normalized files.

In some cases, this is all that needs to be done. Others may need to complete the following additional steps:

git status

Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.

git add -u

It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."

Rewrite the .gitattributes file.

git add .gitattributes

Commit the changes to your repository.

git commit -m "Normalize all the line endings"

How do I make an attributed string using Swift?

I created an online tool that is going to solve your problem! You can write your string and apply styles graphically and the tool gives you objective-c and swift code to generate that string.

Also is open source so feel free to extend it and send PRs.

Transformer Tool

Github

enter image description here

Can I add a custom attribute to an HTML tag?

You can add custom attributes to your elements at will. But that will make your document invalid.

In HTML 5 you will have the opportunity to use custom data attributes prefixed with data-.

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

Only using @JsonIgnore during serialization, but not deserialization

In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore instead of org.codehaus.jackson.annotate.JsonIgnore, as otherwise, it simply did nothing.

How can I insert new line/carriage returns into an element.textContent?

Change the h1.textContent to h1.innerHTML and use <br> to go to the new line.

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The book seems to indicate that those commands yield the same effect:

The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:

$ git checkout --track origin/serverfix 
Branch serverfix set up to track remote branch serverfix from origin. 
Switched to a new branch 'serverfix' 

To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:

$ git checkout -b sf origin/serverfix

That's particularly handy when your bash or oh-my-zsh git completions are able to pull the origin/serverfix name for you - just append --track (or -t) and you are on your way.

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

Sorry, but I think the accepted answer is an overkill. All you need to do is this:

public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
    public void OnException (ExceptionContext context)
    {
        // Log only handled exceptions, because all other will be caught by ELMAH anyway.
        if (context.ExceptionHandled)
            ErrorSignal.FromCurrentContext().Raise(context.Exception);
    }
}

and then register it (order is important) in Global.asax.cs:

public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
    filters.Add(new ElmahHandledErrorLoggerFilter());
    filters.Add(new HandleErrorAttribute());
}

submitting a form when a checkbox is checked

You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:

    onchange="this.form.submit()"

Example:

<form>
      <div>
           <input type="checkbox">
      </div>
</form>

Is div inside list allowed?

If I recall correctly, a div inside a li used to be invalid.

@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.

"Default Activity Not Found" on Android Studio upgrade

This solution should work for you:

  1. Go to Edit Configuration.

  2. Select Activity select nothing and apply.

What is a Python equivalent of PHP's var_dump()?

PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()

"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"

How do I exit a foreach loop in C#?

Look at this code, it can help you to get out of the loop fast!

foreach (var name in parent.names)
{
   if (name.lastname == null)
   {
      Violated = true;
      this.message = "lastname reqd";
      break;
   }
   else if (name.firstname == null)
   {
      Violated = true;
      this.message = "firstname reqd";
      break;
   }
}

How to use Javascript to read local text file and read line by line?

Without jQuery:

document.getElementById('file').onchange = function(){

  var file = this.files[0];

  var reader = new FileReader();
  reader.onload = function(progressEvent){
    // Entire file
    console.log(this.result);

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){
      console.log(lines[line]);
    }
  };
  reader.readAsText(file);
};

HTML:

<input type="file" name="file" id="file">

Remember to put your javascript code after the file field is rendered.

Can't connect to MySQL server on 'localhost' (10061) after Installation

Turn off firewall and restart mysql server. then turn on firewall. It's the easy way! just try it

Trying to start a service on boot on Android

In fact,I get into this trouble not long ago,and it's really really easy to fix,you actually do nothing wrong if you setup the "android.intent.action.BOOT_COMPLETED" permission and intent-filter.

Be attention that if you On Android 4.X,you have to run the broadcast listener before you start service on boot,that means,you have to add an activity first,once your broadcast receiver running,your app should function as you expected,however,on Android 4.X,I haven't found a way to start the service on boot without any activity,I think google did that for security reasons.

Pip install - Python 2.7 - Windows 7

I've seen this issue before with 2.7.14. Fixed it by :

  1. Re-install python 2.7.14
  2. During the installation, select default path and put a check mark in the installation options to add python to windows path i.e. environmental variables.
  3. After installation is complete, go to System from the Control Panel, select Advanced system settings, and clicking Environment Variables.
  4. Verify that the system variable "path" has "C:\Python\;C:\Python\Scripts;" added to the list.
  5. In cmd, run "where python" and then "where pip". Which will show for example:

    ? where python
    C:\Python\python.exe
    
    ? where pip
    C:\Python\Scripts\pip.exe
    
  6. Run pip, then it should show different pip run command options.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

Difference between attr_accessor and attr_accessible

Many people on this thread and on google explain very well that attr_accessible specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time) This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.

This is explained here on the official Rails doc : Mass Assignment

attr_accessor is a ruby code to (quickly) create setter and getter methods in a Class. That's all.

Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor in your model to create setters and getters in order to be able to modify your table's records.

This is because your model inherits all methods from the ActiveRecord::Base Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you. This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")

Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :

SQL instructions :

CREATE TABLE users (
  firstname string,
  lastname string
  role string
);

I assumed that you set the option config.active_record.whitelist_attributes = true in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment

Your Rails model will perfectly work with the Model here below :

class User < ActiveRecord::Base

end

However you will need to update each attribute of user separately in your controller for your form's View to work :

def update
    @user = User.find_by_id(params[:id])
    @user.firstname = params[:user][:firstname]
    @user.lastname = params[:user][:lastname]

    if @user.save
        # Use of I18 internationalization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

Now to ease your life, you don't want to make a complicated controller for your User model. So you will use the attr_accessible special method in your Class model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname

end

So you can use the "highway" (mass assignment) to update :

def update
    @user = User.find_by_id(params[:id])

    if @user.update_attributes(params[:user])
        # Use of I18 internationlization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

You didn't add the "role" attributes to the attr_accessible list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.

Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible is to protect your application from that.

You can still modify your user.role attribute on its own like below, but not with all attributes together.

@user.role = DEFAULT_ROLE

Why the hell would you use the attr_accessor?

Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.

For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field. You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.

To be able to make use of this info you need to store it temporarily somewhere. What more easy than recover it in a user.peekaboo attribute ?

So you add this field to your model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname
  attr_accessor :peekaboo

end

So you will be able to make an educated use of the user.peekaboo attribute somewhere in your controller to send an e-mail or do whatever you want.

ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save because she don't see any column matching this name in her model.

Making a Windows shortcut start relative to where the folder is?

I like leoj3n's solution. It can also be used to set a relative "start in" directory, which is what I needed by using start's /D parameter. Without /c or /k in as an argument to cmd, the subsequent start command doesn't run. /c will close the shell immediately after running the command and /k will keep it open (even after the command is done). So if whatever you're running spits to standard out and you need to see it, use /k.

Unfortunately, according to the lnk file specification, the icon is not saved in the shortcut, but rather "encoded using environment variables, which makes it possible to find the icon across machines where the locations vary but are expressed using environment variables." So it's likely that if paths are changing and you're trying to take the icon from the executable you're pointing to, it won't transfer correctly.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

CSS to stop text wrapping under image

Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:

This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.

The span element is an inline element, you can't change its width in CSS.

You can add the following CSS to your span so you will be able to change its width.

display: block;

Another way, which usually makes more sense, is to use a <p> element as a parent for your <span>.

<li id="CN2787">
  <img class="fav_star" src="images/fav.png">
  <p>
     <span>Text, text and more text</span>
  </p>
</li>

Since <p> is a block element, you can set its width using CSS, without having to change anything.

But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.

li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}

P.S. Instead of float:left on the image, you can also put float:right on li p but in that case, you will also need text-align:left to realign the text correctly.

P.S.S. If you went ahead with the first solution of not adding a <p> element, your CSS should look like so:

li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}

How to convert .crt to .pem

I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.

openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

If you understand the difference between scope and session then it will be very easy to understand these methods.

A very nice blog post by Adam Anderson describes this difference:

Session means the current connection that's executing the command.

Scope means the immediate context of a command. Every stored procedure call executes in its own scope, and nested calls execute in a nested scope within the calling procedure's scope. Likewise, a SQL command executed from an application or SSMS executes in its own scope, and if that command fires any triggers, each trigger executes within its own nested scope.

Thus the differences between the three identity retrieval methods are as follows:

@@identity returns the last identity value generated in this session but any scope.

scope_identity() returns the last identity value generated in this session and this scope.

ident_current() returns the last identity value generated for a particular table in any session and any scope.

convert a JavaScript string variable to decimal/money

You can also use the Number constructor/function (no need for a radix and usable for both integers and floats):

Number('09'); /=> 9
Number('09.0987'); /=> 9.0987

Alternatively like Andy E said in the comments you can use + for conversion

+'09'; /=> 9
+'09.0987'; /=> 9.0987

Using intents to pass data between activities

Main Activity

public class MainActivity extends Activity {

    EditText user, password;
    Button login;

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

        user = (EditText) findViewById(R.id.username_edit);
        password = (EditText) findViewById(R.id.edit_password);
        login = (Button) findViewById(R.id.btnSubmit);
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Second.class);

                String uservalue = user.getText().toString();
                String name_value = password.getText().toString();
                String password_value = password.getText().toString();

                intent.putExtra("username", uservalue);
                intent.putExtra("password", password_value);
                startActivity(intent);
            }
        });
    }
}

Second Activity in which you want to receive Data

public class Second extends Activity{

    EditText name, pass;
    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        name = (EditText) findViewById(R.id.editText1);
        pass = (EditText) findViewById(R.id.editText2);

        String value = getIntent().getStringExtra("username");
        String pass_val = getIntent().getStringExtra("password");
        name.setText(value);
        pass.setText(pass_val);
    }
}

Use and meaning of "in" in an if statement?

Using a in b is simply translates to b.__contains__(a), which should return if b includes a or not.

But, your example looks a little weird, it takes an input from user and assigns its integer value to how_much variable if the input contains "0" or "1".

How to draw polygons on an HTML5 canvas?

You can use the lineTo() method same as: var objctx = canvas.getContext('2d');

        objctx.beginPath();
        objctx.moveTo(75, 50);
        objctx.lineTo(175, 50);
        objctx.lineTo(200, 75);
        objctx.lineTo(175, 100);
        objctx.lineTo(75, 100);
        objctx.lineTo(50, 75);
        objctx.closePath();
        objctx.fillStyle = "rgb(200,0,0)";
        objctx.fill();

if you not want to fill the polygon use the stroke() method in the place of fill()

You can also check the following: http://www.authorcode.com/draw-and-fill-a-polygon-and-triangle-in-html5/

thanks

How to set a default value for an existing column

cannot use alter column for that, use add instead

ALTER TABLE Employee 
ADD DEFAULT('SANDNES') FOR CityBorn

Strip first and last character from C string

To "remove" the 1st character point to the second character:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */

To remove the last character replace it with a '\0'.

p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */

How to create batch file in Windows using "start" with a path and command with spaces

Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.

How to SSH into Docker?

Notice: this answer promotes a tool I've written.

The selected answer here suggests to install an SSH server into every image. Conceptually this is not the right approach (https://docs.docker.com/articles/dockerfile_best-practices/).

I've created a containerized SSH server that you can 'stick' to any running container. This way you can create compositions with every container. The only requirement is that the container has bash.

The following example would start an SSH server exposed on port 2222 of the local machine.

$ docker run -d -p 2222:22 \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -e CONTAINER=my-container -e AUTH_MECHANISM=noAuth \
  jeroenpeeters/docker-ssh

$ ssh -p 2222 localhost

For more pointers and documentation see: https://github.com/jeroenpeeters/docker-ssh

Not only does this defeat the idea of one process per container, it is also a cumbersome approach when using images from the Docker Hub since they often don't (and shouldn't) contain an SSH server.

Excel 2007 - Compare 2 columns, find matching values

You could fill the C Column with variations on the following formula:

=IF(ISERROR(MATCH(A1,$B:$B,0)),"",A1)

Then C would only contain values that were in A and C.

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

How to set back button text in Swift

You can do it from interface builder as follows:

click on the navigation item of previous view controller

enter image description here

from the attributes inspector set the back button text to whatever you want. Thats it!!

enter image description here

Create folder with batch but only if it doesn't already exist

set myDIR=LOG
IF not exist %myDIR% (mkdir %myDIR%)

Modulo operator in Python

When you have the expression:

a % b = c

It really means there exists an integer n that makes c as small as possible, but non-negative.

a - n*b = c

By hand, you can just subtract 2 (or add 2 if your number is negative) over and over until the end result is the smallest positive number possible:

  3.14 % 2
= 3.14 - 1 * 2
= 1.14

Also, 3.14 % 2 * pi is interpreted as (3.14 % 2) * pi. I'm not sure if you meant to write 3.14 % (2 * pi) (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

Prevent jQuery UI dialog from setting focus to first textbox

My workaround:

open: function(){
  jQuery('input:first').blur();
  jQuery('#ui-datepicker-div').hide();
},  

Converting Stream to String and back...what are we missing?

a UTF8 MemoryStream to String conversion:

var res = Encoding.UTF8.GetString(stream.GetBuffer(), 0 , (int)stream.Length)

Eclipse: How do you change the highlight color of the currently selected method/expression?

1 - right click the highlight whose color you want to change

2 - select "Properties" in the popup menu

3 - choose the new color (as coobird suggested)

This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.

Find commit by hash SHA in Git

Just use the following command

git show a2c25061

or (the exact equivalent):

git log -p -1 a2c25061

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

do { ... } while (0) — what is it good for?

It is a way to simplify error checking and avoid deep nested if's. For example:

do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);

Accessing @attribute from SimpleXML

Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that

 $xml->tagName['attribute']

was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.

The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.

Njoy for what its worth (did I mention unique build?).

How do I enable TODO/FIXME/XXX task tags in Eclipse?

For me, such tags are enabled by default. You can configure which task tags should be used in the workspace options: Java > Compiler > Task tags

alt text

Check if they are enabled in this location, and that should be enough to have them appear in the Task list (or the Markers view).

Extra note: reinstalling Eclipse won't change anything most of the time if you work on the same workspace. Most settings used by Eclipse are stored in the .metadata folder, in your workspace folder.

How to build splash screen in windows forms application?

First you should create a form with or without Border (border-less is preferred for these things)

public class SplashForm : Form
{
    Form _Parent;
    BackgroundWorker worker;
    public SplashForm(Form parent)
    {
         InitializeComponent();
         BackgroundWorker worker = new BackgroundWorker();
         this.worker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.worker _DoWork);
         backgroundWorker1.RunWorkerAsync();
         _Parent = parent;
    }
    private void worker _DoWork(object sender, DoWorkEventArgs e)
    {
         Thread.sleep(500);
         this.hide();
         _Parent.show();
    }     
}

At Main you should use that

   static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new SplashForm());
            }
        }

'uint32_t' identifier not found error

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

In this case uint32_t is UINT32 or just UINT.

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

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:

SELECT Id, dateCreated FROM products INTO iId, dCreate

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Body set to overflow-y:hidden but page is still scrollable in Chrome

Another solution I found to work is to set a mousewheel handler on the inside container and make sure it doesn't propagate by setting its last parameter to false and stopping the event bubble.

document.getElementById('content').addEventListener('mousewheel',function(evt){evt.cancelBubble=true;   if (evt.stopPropagation) evt.stopPropagation},false);

Scroll works fine in the inner container, but the event doesn't propagate to the body and so it does not scroll. This is in addition to setting the body properties overflow:hidden and height:100%.

Collections.emptyList() vs. new instance

Be carefully though. If you return Collections.emptyList() and then try to do some changes with it like add() or smth like that, u will have an UnsupportedOperationException() because Collections.emptyList() returns an immutable object.

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

How to break out of a loop from inside a switch?

A neatish way to do this would be to put this into a function:

int yourfunc() {

    while(true) {

        switch(msg->state) {
        case MSGTYPE: // ... 
            break;
        // ... more stuff ...
        case DONE:
            return; 
        }

    }
}

Optionally (but 'bad practices'): as already suggested you could use a goto, or throw an exception inside the switch.

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

updating table rows in postgres using subquery

update json_source_tabcol as d
set isnullable = a.is_Nullable
from information_schema.columns as a 
where a.table_name =d.table_name 
and a.table_schema = d.table_schema 
and a.column_name = d.column_name;

ASP.Net MVC Redirect To A Different View

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is:

return RedirectToAction("Index", model);

Then in your Index method, return the view you want.

How do I install the ext-curl extension with PHP 7?

If "sudo apt-get install php-curl" command doesnt work and display error We should run this code before install curl.

  • step1 - sudo add-apt-repository ppa:ondrej/php
  • step2 - sudo apt-get update
  • step3 - sudo apt-get install php-curl
  • step4 - sudo service apache2 restart

How to show grep result with complete path or file name

Use:

grep somethingtosearch *.log

and the filenames will be printed out along with the matches.

Getting the Username from the HKEY_USERS values

In the HKEY_USERS\oneyouwanttoknow\ you can look at \Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders and it will reveal their profile paths. c:\users\whothisis\Desktop, etc.

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

How to load a resource from WEB-INF directory of a web archive

The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".

The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).

Hope this helps someone.

How to change the style of alert box?

The alert box is a system object, and not subject to CSS. To do this style of thing you would need to create an HTML element and mimic the alert() functionality. The jQuery UI Dialogue does a lot of the work for you, working basically as I have described: Link.

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css">_x000D_
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
  <script>_x000D_
  $( function() {_x000D_
    $( "#dialog" ).dialog();_x000D_
  } );_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<div id="dialog" title="Basic dialog">_x000D_
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
</div>_x000D_
 _x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to Join to first row

I know this question was answered a while ago, but when dealing with large data sets, nested queries can be costly. Here is a different solution where the nested query will only be ran once, instead of for each row returned.

SELECT 
  Orders.OrderNumber,
  LineItems.Quantity, 
  LineItems.Description
FROM 
  Orders
  INNER JOIN (
    SELECT
      Orders.OrderNumber,
      Max(LineItem.LineItemID) AS LineItemID
    FROM
      Orders INNER JOIN LineItems
      ON Orders.OrderNumber = LineItems.OrderNumber
    GROUP BY Orders.OrderNumber
  ) AS Items ON Orders.OrderNumber = Items.OrderNumber
  INNER JOIN LineItems 
  ON Items.LineItemID = LineItems.LineItemID

Print page numbers on pages when printing html

This is what you want:

@page {
   @bottom-right {
    content: counter(page) " of " counter(pages);
   }
}

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

How to access the local Django webserver from outside world

I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)

ALLOWED_HOSTS = ['*']

then ran the server with:

python manage.py runserver 0.0.0.0:9595

Also ensure that the firewall allows connections to that port

Converting HTML element to string in JavaScript / JQuery

you can just wrap it into another element and call html after that:

$('<div><iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe></div>').html();

note that outerHTML doesn't exist on older browsers but innerHTML still does (it doesn't exist for example in ff < 11 while it's still used on many older computers)

How do you set the startup page for debugging in an ASP.NET MVC application?

Selecting a specific page from Project properties does not solve my problem.

In MVC 4 open App_Start/RouteConfig.cs

For example, if you want to change startup page to Login:

routes.MapRoute(
        "Default", // Route name
        "",        // URL with parameters
        new { controller = "Account", action = "Login"}  // Parameter defaults
    );

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I am using the following construct, although you might want to avoid shell=True. This gives you the output and error message for any command, and the error code as well:

process = subprocess.Popen(cmd, shell=True,
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode

How to horizontally center an unordered list of unknown width?

Try wrapping the list in a div and give that div the inline property instead of your list.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

What does ellipsize mean in android?

Text:

 This is my first android application and
 I am trying to make a funny game,
 It seems android is really very easy to play.

Suppose above is your text and if you are using ellipsize's start attribute it will seen like this

This is my first android application and
...t seems android is really very easy to play.

with end attribute

 This is my first android application and
 I am trying to make a funny game,...

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

An additional note. If you check uncompressed javascript file, you will find the condition:

if(window.Tether === undefined) {
     throw new Error('Bootstrap tooltips require Tether (http://github.hubspot.com/tether)')
}

So the error message contains the required information.

You can download the archive from that link.

Uncompressed version:

https://rawgit.com/HubSpot/tether/master/src/js/tether.js https://rawgit.com/HubSpot/tether/master/dist/css/tether.css

Android: Changing Background-Color of the Activity (Main View)

First Method

 View someView = findViewById(R.id.randomViewInMainLayout);// get Any child View

  // Find the root view
  View root = someView.getRootView()

  // Set the color
  root.setBackgroundColor(getResources().getColor(android.R.color.red));

Second Method

Add this single line after setContentView(...);

getWindow().getDecorView().setBackgroundColor(Color.WHITE);

Third Method

set background color to the rootView

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

Important Thing

rootView.setBackgroundColor(0xFF00FF00); //after 0x the other four pairs are alpha,red,green,blue color. 

Vim delete blank lines

  1. how to remove all the blanks lines

    :%s,\n\n,^M,g
    

    (do this multiple times util all the empty lines went gone)

  2. how to remove all the blanks lines leaving SINGLE empty line

    :%s,\n\n\n,^M^M,g
    

    (do this multiple times)

  3. how to remove all the blanks lines leaving TWO empty lines AT MAXIMUM,

    :%s,\n\n\n\n,^M^M^M,g
    

    (do this multiple times)

in order to input ^M, I have to control-Q and control-M in windows

How to get thread id from a thread pool?

Using Thread.currentThread():

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}

Set Background color programmatically

This must work:

you must use getResources().getColor(R.color.WHITE) to get the color resource, which you must add in the colors.xml resource file

View someView = findViewById(R.id.screen);

someView.setBackgroundColor(getResources().getColor(R.color.WHITE));

How can I add a class to a DOM element in JavaScript?

Use the .classList.add() method:

_x000D_
_x000D_
const element = document.querySelector('div.foo');_x000D_
element.classList.add('bar');_x000D_
console.log(element.className);
_x000D_
<div class="foo"></div>
_x000D_
_x000D_
_x000D_

This method is better than overwriting the className property, because it doesn't remove other classes and doesn't add the class if the element already has it.

You can also toggle or remove classes using element.classList (see the MDN documentation).

getaddrinfo: nodename nor servname provided, or not known

I fixed this problem simply by closing and reopening the Terminal.

Creating JSON on the fly with JObject

Sooner or later you will have property with special character. You can either use index or combination of index and property.

dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use

How to disable HTML links

you cannot disable a link, if you want that click event should not fire then simply Remove the action from that link.

$(td).find('a').attr('href', '');

For More Info :- Elements that can be Disabled

How to insert TIMESTAMP into my MySQL table?

You can try wiht TIMESTAMP(curdate(), curtime()) for use the current time.

How does a ArrayList's contains() method evaluate objects?

I think that right implementations should be

public class Thing
{
    public int value;  

    public Thing (int x)
    {
        this.value = x;
    }

    @Override
    public boolean equals(Object object)
    {
        boolean sameSame = false;

        if (object != null && object instanceof Thing)
        {
            sameSame = this.value == ((Thing) object).value;
        }

        return sameSame;
    }
}

how to have two headings on the same line in html

You should only need to do one of:

  • Make them both inline (or inline-block)
  • Set them to float left or right

You should be able to adjust the height, padding, or margin properties of the smaller heading to compensate for its positioning. I recommend setting both headings to have the same height.

See this live jsFiddle for an example.

(code of the jsFiddle):

CSS

h2 {
  font-size: 50px;
}

h3 {
  font-size: 30px;
}

h2, h3 {
  width: 50%;
  height: 60px;
  margin: 0;
  padding: 0;
  display: inline;
}?

HTML

<h2>Big Heading</h2>
<h3>Small(er) Heading</h3>
<hr />?

How to stop PHP code execution?

Please see the following information from user Pekka ?

According to the manual, destructors are executed even if the script gets terminated using die() or exit():

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this PHP: destructor vs register_shutdown_function, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).

The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)

The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different

It does not get executed on parse errors (because the whole script won't be interpreted)

The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.

Referenced in this question Are there any instances when the destructor in PHP is NOT called?

How to get the first non-null value in Java?

This situation calls for some preprocessor. Because if you write a function (static method) which picks the first not null value, it evaluates all items. It is problem if some items are method calls (may be time expensive method calls). And this methods are called even if any item before them is not null.

Some function like this

public static <T> T coalesce(T ...items) …

should be used but before compiling into byte code there should be a preprocessor which find usages of this „coalesce function“ and replaces it with construction like

a != null ? a : (b != null ? b : c)

Update 2014-09-02:

Thanks to Java 8 and Lambdas there is possibility to have true coalesce in Java! Including the crucial feature: particular expressions are evaluated only when needed – if earlier one is not null, then following ones are not evaluated (methods are not called, computation or disk/network operations are not done).

I wrote an article about it Java 8: coalesce – hledáme neNULLové hodnoty – (written in Czech, but I hope that code examples are understandable for everyone).

How do I get the AM/PM value from a DateTime?

If you want to add time to LongDateString Date, you can format it this way:

    DateTime date = DateTime.Now;
    string formattedDate = date.ToLongDateString(); 
    string formattedTime = date.ToShortTimeString();
    Label1.Text = "New Formatted Date: " + formattedDate + " " + formattedTime;

Output:

New Formatted Date: Monday, January 1, 1900 8:53 PM 

How to turn on/off MySQL strict mode in localhost (xampp)?

To Change it permanently in ubuntu do the following

in the ubuntu command line

sudo nano /etc/mysql/my.cnf

Then add the following

[mysqld]
sql_mode=

What is the 'dynamic' type in C# 4.0 used for?

The best use case of 'dynamic' type variables for me was when, recently, I was writing a data access layer in ADO.NET (using SQLDataReader) and the code was invoking the already written legacy stored procedures. There are hundreds of those legacy stored procedures containing bulk of the business logic. My data access layer needed to return some sort of structured data to the business logic layer, C# based, to do some manipulations (although there are almost none). Every stored procedures returns different set of data (table columns). So instead of creating dozens of classes or structs to hold the returned data and pass it to the BLL, I wrote the below code which looks quite elegant and neat.

public static dynamic GetSomeData(ParameterDTO dto)
        {
            dynamic result = null;
            string SPName = "a_legacy_stored_procedure";
            using (SqlConnection connection = new SqlConnection(DataConnection.ConnectionString))
            {
                SqlCommand command = new SqlCommand(SPName, connection);
                command.CommandType = System.Data.CommandType.StoredProcedure;                
                command.Parameters.Add(new SqlParameter("@empid", dto.EmpID));
                command.Parameters.Add(new SqlParameter("@deptid", dto.DeptID));
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        dynamic row = new ExpandoObject();
                        row.EmpName = reader["EmpFullName"].ToString();
                        row.DeptName = reader["DeptName"].ToString();
                        row.AnotherColumn = reader["AnotherColumn"].ToString();                        
                        result = row;
                    }
                }
            }
            return result;
        }

Can you 'exit' a loop in PHP?

As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.

For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.

$person = "Rasmus Lerdorf";
$found = false;

foreach($organization as $oKey=>$department)
{
   foreach($department as $dKey=>$group)
   {
      foreach($group as $gKey=>$employee)
      {
         if ($employee['fullname'] == $person)
         {
            $found = true;
            break 3;
         }
      } // group
   } // department
} // organization

Get local IP address in Node.js

Based on a comment, here's what's working for the current version of Node.js:

var os = require('os');
var _ = require('lodash');

var ip = _.chain(os.networkInterfaces())
  .values()
  .flatten()
  .filter(function(val) {
    return (val.family == 'IPv4' && val.internal == false)
  })
  .pluck('address')
  .first()
  .value();

The comment on one of the answers above was missing the call to values(). It looks like os.networkInterfaces() now returns an object instead of an array.

Is SQL syntax case sensitive?

I found this blog post to be very helpful (I am not the author). Summarizing (please read, though):

...delimited identifiers are case sensitive ("table_name" != "Table_Name"), while non quoted identifiers are not, and are transformed to upper case (table_name => TABLE_NAME).

He found DB2, Oracle and Interbase/Firebird are 100% compliant:

PostgreSQL ... lowercases every unquoted identifier, instead of uppercasing it. MySQL ... file system dependent. SQLite and SQL Server ... case of the table and field names are preserved on creation, but they are completely ignored afterwards.

How to clear memory to prevent "out of memory error" in excel vba?

The best way to help memory to be freed is to nullify large objects:

Sub Whatever()
    Dim someLargeObject as SomeObject

    'expensive computation

    Set someLargeObject = Nothing
End Sub

Also note that global variables remain allocated from one call to another, so if you don't need persistence you should either not use global variables or nullify them when you don't need them any longer.

However this won't help if:

  • you need the object after the procedure (obviously)
  • your object does not fit in memory

Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).

AngularJS : Why ng-bind is better than {{}} in angular?

You can refer to this site it will give you a explanation which one is better as i know {{}} this is slower than ng-bind.

http://corpus.hubwiz.com/2/angularjs/16125872.html refer this site.

How do you read from stdin?

There's a few ways to do it.

  • sys.stdin is a file-like object on which you can call functions read or readlines if you want to read everything or you want to read everything and split it by newline automatically. (You need to import sys for this to work.)

  • If you want to prompt the user for input, you can use raw_input in Python 2.X, and just input in Python 3.

  • If you actually just want to read command-line options, you can access them via the sys.argv list.

You will probably find this Wikibook article on I/O in Python to be a useful reference as well.

adding onclick event to dynamically added button?

Try
but.addEventListener('click', yourFunction) Note the absence of parantheses () after the function name. This is because you are assigning the function, not calling it.

jQuery get textarea text

Normally, it's the value property

testArea.value

Or is there something I'm missing in what you need?

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Finally, I got a solution!

My Context is:- I want disconnect socket connection when activity destroyed, I tried to finish() activity but it didn't work me, its keep connection live somewhere.

so I use android.os.Process.killProcess(android.os.Process.myPid()); its kill my activity and i used android:excludeFromRecents="true" for remove from recent activity .

How to fetch all Git branches

Have tried many ways, only this one is simple and works for me.

for branch in $(git ls-remote -h git@<your_repository>.git | awk '{print $2}' | sed 's:refs/heads/::')
do
  git checkout "$branch"
  git pull
done

Seeing the console's output in Visual Studio 2010?

Press Ctrl + F5 to run the program instead of F5.

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

Copy map values to vector in STL

One way is to use functor:

 template <class T1, class T2>
    class CopyMapToVec
    {
    public: 
        CopyMapToVec(std::vector<T2>& aVec): mVec(aVec){}

        bool operator () (const std::pair<T1,T2>& mapVal) const
        {
            mVec.push_back(mapVal.second);
            return true;
        }
    private:
        std::vector<T2>& mVec;
    };


int main()
{
    std::map<std::string, int> myMap;
    myMap["test1"] = 1;
    myMap["test2"] = 2;

    std::vector<int>  myVector;

    //reserve the memory for vector
    myVector.reserve(myMap.size());
    //create the functor
    CopyMapToVec<std::string, int> aConverter(myVector);

    //call the functor
    std::for_each(myMap.begin(), myMap.end(), aConverter);
}

How can I show and hide elements based on selected option with jQuery?

To show the div while selecting one value and hide while selecting another value from dropdown box: -

 $('#yourselectorid').bind('change', function(event) {

           var i= $('#yourselectorid').val();

            if(i=="sometext") // equal to a selection option
             {
                 $('#divid').show();
             }
           elseif(i=="othertext")
             {
               $('#divid').hide(); // hide the first one
               $('#divid2').show(); // show the other one

              }
});

Set min-width in HTML table's <td>

<table style="min-width:50px; max-width:150px;">
    <tr>
        <td style="min-width:50px">one</td>
        <td style="min-width:100px">two</td>
    </tr>
</table>

This works for me using an email script.

SQL: How to properly check if a record exists

You can use:

SELECT COUNT(1) FROM MyTable WHERE ... 

or

WHERE [NOT] EXISTS 
( SELECT 1 FROM MyTable WHERE ... )

This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

There's also a subtle difference between COUNT(*) and COUNT(column name):

  • COUNT(*) will count all rows, including nulls
  • COUNT(column name) will only count non null occurrences of column name

JavaScript pattern for multiple constructors

export default class Order {

    static fromCart(cart) {
        var newOrder = new Order();
        newOrder.items = cart.items;
        newOrder.sum = cart.sum;

        return newOrder;
    }

    static fromOrder(id, order) {
        var newOrder = new Order();
        newOrder.id = id;
        newOrder.items = order.items;
        newOrder.sum = order.sum;

        return newOrder;
    }
}

Useges:

  var newOrder = Order.fromCart(cart)
  var newOrder = Order.fromOrder(id, oldOrder)

How to host material icons offline?

As of 2020, my approach is to use the material-icons-font package. It simplifies the usage of Google's material-design-icons package and the community based material-design-icons-iconfont.

  1. Install the package. npm install material-icons-font --save

  2. Add the path of the package's CSS file to the style property of your project's angular.json file.

    ... "styles": [ "./node_modules/material-icons-font/material-icons-font.css" ], ...

  3. If using SCSS, copy content below to the top of your styles.scss file.

    @import '~material-icons-font/sass/variables'; @import '~material-icons-font/sass/mixins'; $MaterialIcons_FontPath: "~material-icons-font/fonts"; @import '~material-icons-font/sass/main'; @import '~material-icons-font/sass/Regular';

  4. Use the icons in the HTML file of your project.

    // Using icon tag
    <i class="material-icons">face</i>
    <i class="material-icons md-48">face</i>
    <i class="material-icons md-light md-inactive">face</i>
    
    // Using Angular Material's <mat-icon> tag
    <mat-icon>face</mat-icon>
    <mat-icon>add_circle</mat-icon>
    <mat-icon>add_circle_outline</mat-icon>
    

Icons from @angular/material tend to break when developing offline. Adding material-icons-font package in conjunction with @angular/material allows you to use the tag while developing offline.

Android Failed to install HelloWorld.apk on device (null) Error

1) remove the apk from this directory project/build/outputs/apk

2) If you using genymotion emulator restart the genymotion

3) make project & rebuild the project

4) Run Again

How to get the current user's Active Directory details in C#

Add reference to COM "Active DS Type Library"


            Int32 nameTypeNT4               = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
            Int32 nameTypeDN                = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
            Int32 nameTypeUserPrincipalName = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;

            ActiveDs.NameTranslate nameTranslate = new ActiveDs.NameTranslate();

            // Convert NT name DOMAIN\User into AD distinguished name 
            // "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com"
            nameTranslate.Set(nameTypeNT4, ntUser);

            String distinguishedName = nameTranslate.Get(nameTypeDN);

            Console.WriteLine(distinguishedName);

            // Convert AD distinguished name "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com" 
            // into NT name DOMAIN\User
            ntUser = String.Empty;
            nameTranslate.Set(nameTypeDN, distinguishedName);
            ntUser = nameTranslate.Get(nameTypeNT4);
            Console.WriteLine(ntUser);

            // Convert NT name DOMAIN\User into AD UserPrincipalName [email protected]
            nameTranslate.Set(nameTypeNT4, ntUser);
            String userPrincipalName = nameTranslate.Get(nameTypeUserPrincipalName);

            Console.WriteLine(userPrincipalName);

How to getElementByClass instead of GetElementById with JavaScript?

Append IDs at the class declaration

.aclass, #hashone, #hashtwo{ ...codes... }
document.getElementById( "hashone" ).style.visibility = "hidden";

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

Here's one I only found out about recently...

interface IFoo
{
   string Message {get;}
}
...
IFoo obj = new IFoo("abc");
Console.WriteLine(obj.Message);

The above looks crazy at first glance, but is actually legal.No, really (although I've missed out a key part, but it isn't anything hacky like "add a class called IFoo" or "add a using alias to point IFoo at a class").

See if you can figure out why, then: Who says you can’t instantiate an interface?

How to make a 3D scatter plot in Python?

You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.

from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random


fig = pyplot.figure()
ax = Axes3D(fig)

sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))

random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)

ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()

The code above generates a figure like:

matplotlib 3D image

Debug JavaScript in Eclipse

I don't believe Eclipse has a JavaScript debugger - those breakpoints are for Java code (I'm guessing you are editing a JSP file?)

Use Firebug to debug Javascript code, it's an excellent add-on that all web developers should have in their toolbox.

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

int to string in MySQL

select t2.* 
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar)  + '%/more' 
where t1.id > 9000

Using concat like suggested is even better though

C++ Convert string (or char*) to wstring (or wchar_t*)

Here is my super basic solution that might not work for everyone. But would work for a lot of people.

It requires usage of the Guideline Support Library. Which is a pretty official C++ library that was designed by many C++ committee authors:

    std::string to_string(std::wstring const & wStr)
    {
        std::string temp = {};

        for (wchar_t const & wCh : wStr)
        {
            // If the string can't be converted gsl::narrow will throw
            temp.push_back(gsl::narrow<char>(wCh));
        }

        return temp;
    }

All my function does is allow the conversion if possible. Otherwise throw an exception.

Via the usage of gsl::narrow (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es49-if-you-must-use-a-cast-use-a-named-cast)

Install tkinter for Python

For Arch Linux users, it goes a bit like

sudo pacman -S tk

Check if element is in the list (contains)

std::list does not provide a search method. You can iterate over the list and check if the element exists or use std::find. But I think for your situation std::set is more preferable. The former will take O(n) time but later will take O(lg(n)) time to search.

You can simply use:

int my_var = 3;
std::set<int> mySet {1, 2, 3, 4};
if(mySet.find(myVar) != mySet.end()){
      //do whatever
}

how to use ng-option to set default value of select element

The angular documentation for select* does not answer this question explicitly, but it is there. If you look at the script.js, you will see this:

function MyCntrl($scope) {
  $scope.colors = [
    {name:'black', shade:'dark'},
    {name:'white', shade:'light'},
    {name:'red', shade:'dark'},
    {name:'blue', shade:'dark'},
    {name:'yellow', shade:'light'}
  ];
  $scope.color = $scope.colors[2]; // Default the color to red
}

This is the html:

<select ng-model="color" ng-options="c.name for c in colors"></select>

This seems to be a more obvious way of defaulting a selected value on an <select> with ng-options. Also it will work if you have different label/values.

* This is from Angular 1.2.7

opening a window form from another form programmatically

This might also help:

void ButtQuitClick(object sender, EventArgs e)
{
    QuitWin form = new QuitWin();
    form.Show();
}

Change ButtQuit to your button name and also change QuitWin to the name of the form that you made.

When the button is clicked it will open another window, you will need to make another form and a button on your main form for it to work.

Best way to read a large file into a byte array in C#?

Depending on the frequency of operations, the size of the files, and the number of files you're looking at, there are other performance issues to take into consideration. One thing to remember, is that each of your byte arrays will be released at the mercy of the garbage collector. If you're not caching any of that data, you could end up creating a lot of garbage and be losing most of your performance to % Time in GC. If the chunks are larger than 85K, you'll be allocating to the Large Object Heap(LOH) which will require a collection of all generations to free up (this is very expensive, and on a server will stop all execution while it's going on). Additionally, if you have a ton of objects on the LOH, you can end up with LOH fragmentation (the LOH is never compacted) which leads to poor performance and out of memory exceptions. You can recycle the process once you hit a certain point, but I don't know if that's a best practice.

The point is, you should consider the full life cycle of your app before necessarily just reading all the bytes into memory the fastest way possible or you might be trading short term performance for overall performance.

'JSON' is undefined error in JavaScript in Internet Explorer

Change the content type to 'application/x-www-form-urlencoded'

What's the difference between interface and @interface in java?

interface:

In general, an interface exposes a contract without exposing the underlying implementation details. In Object Oriented Programming, interfaces define abstract types that expose behavior, but contain no logic. Implementation is defined by the class or type that implements the interface.

@interface : (Annotation type)

Take the below example, which has a lot of comments:

public class Generation3List extends Generation2List {

   // Author: John Doe
   // Date: 3/17/2002
   // Current revision: 6
   // Last modified: 4/12/2004
   // By: Jane Doe
   // Reviewers: Alice, Bill, Cindy

   // class code goes here

}

Instead of this, you can declare an annotation type

 @interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

which can then annotate a class as follows:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

PS: Many annotations replace comments in code.

Reference: http://docs.oracle.com/javase/tutorial/java/annotations/declaring.html

How can I convert spaces to tabs in Vim or Linux?

:%s/\(^\s*\)\@<=    /\t/g

Translation: Search for every instance of 4 consecutive spaces (after the = character), but only if the entire line up to that point is whitespace (this uses the zero-width look-behind assertion, \@<=). Replace each found instance with a tab character.

How to compare timestamp dates with date-only parameter in MySQL?

When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way:

SELECT *
FROM table
where timestamp = to_timestamp('21.08.2017 09:31:57', 'dd-mm-yyyy hh24:mi:ss');

Function stoi not declared

stoi is available "since C++11". Make sure your compiler is up to date.

You can try atoi(hours0.c_str()) instead.

MySQL Fire Trigger for both Insert and Update

You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Could not load file or assembly 'Microsoft.ReportViewer.Webforms' or

Could not load file or assembly 'Microsoft.ReportViewer.Common'

This issue occured for me in Visual studio 2015.

Reason:

the reference for Microsoft.ReportViewer.Webforms dll is missing.

Possible Fix

Step1:

To add "Microsoft.ReportViewer.Webforms.dll" to the solution.

Navigate to Nuget Package Manager Console as

"Tools-->NugetPackageManager-->Package Manager Console".

Then enter the following command in console as below

PM>Install-Package Microsoft.ReportViewer.Runtime.WebForms

Then it will install the Reportviewer.webforms dll in "..\packages\Microsoft.ReportViewer.Runtime.WebForms.12.0.2402.15\lib" (Your project folder path)

and ReportViewer.Runtime.Common dll in "..\packages\Microsoft.ReportViewer.Runtime.Common.12.0.2402.15\lib". (Your project folder path)

Step2:-

Remove the existing reference of "Microsoft.ReportViewer.WebForms". we need to refer these dll files in our Solution as "Right click Solution >References-->Add reference-->browse ". Add both the dll files from the above paths.

Step3:

Change the web.Config File to point out to Visual Studio 2015. comment out both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common version 11.0.0.0 and Uncomment both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common Version=12.0.0.0. as attached in screenshot.

Microsoft.ReportViewer.Webforms/Microsoft.ReportViewer.Common

Also refer the link below.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

Selenium WebDriver How to Resolve Stale Element Reference Exception?

After deep investigation of the problem I found that error occurs selecting DIV elements that were added for Bootstrap only. Chrome browser removes such DIVS and the error occurs. It is enough to step down and select real element for fixing an error. For example, my modal dialog has structure:

<div class="modal-content" uib-modal-transclude="">
    <div class="modal-header">
        ...
    </div>
    <div class="modal-body">
        <form class="form-horizontal ...">
            ...
        </form>
    <div>
<div>

Selecting div class="modal-body" generates an error, selecting form ... works as it would.

How to get row count in an Excel file using POI library?

Sheet.getPhysicalNumberOfRows() does not involve some empty rows. If you want to loop for all rows, do not use this to know the loop size.

JavaScript: get code to run every minute

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Timer Interval 1000 != 1 second?

The proper interval to get one second is 1000. The Interval property is the time between ticks in milliseconds:

MSDN: Timer.Interval Property

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick event multiple times.

How to remove line breaks (no characters!) from the string?

Something a bit more functional (easy to use anywhere):

function strip_carriage_returns($string)
{
    return str_replace(array("\n\r", "\n", "\r"), '', $string);
}

Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You can certainly do something like

SQL> ed
Wrote file afiedt.buf

  1  begin
  2    for d in (select * from dept)
  3    loop
  4      for e in (select * from emp where deptno=d.deptno)
  5      loop
  6        dbms_output.put_line( 'Employee ' || e.ename ||
  7                              ' in department ' || d.dname );
  8      end loop;
  9    end loop;
 10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

Or something equivalent using explicit cursors.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    cursor dept_cur
  3        is select *
  4             from dept;
  5    d dept_cur%rowtype;
  6    cursor emp_cur( p_deptno IN dept.deptno%type )
  7        is select *
  8             from emp
  9            where deptno = p_deptno;
 10    e emp_cur%rowtype;
 11  begin
 12    open dept_cur;
 13    loop
 14      fetch dept_cur into d;
 15      exit when dept_cur%notfound;
 16      open emp_cur( d.deptno );
 17      loop
 18        fetch emp_cur into e;
 19        exit when emp_cur%notfound;
 20        dbms_output.put_line( 'Employee ' || e.ename ||
 21                              ' in department ' || d.dname );
 22      end loop;
 23      close emp_cur;
 24    end loop;
 25    close dept_cur;
 26* end;
 27  /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of

FOR x IN (SELECT *
            FROM all_users,
                 org
           WHERE length(all_users.username) = 3
             AND all_users.username = org.username )
LOOP
  <<do something>>
END LOOP;

Can we add div inside table above every <tr>?

You could use display: table-row-group for your div.

<table>
  <div style="display: table-row-group">
    <tr><td></td></tr>
  </div>
  <div style="display: table-row-group">
    <tr><td></td></tr>
  </div>
</table>

grep from tar.gz without extracting [faster one]

I know this question is 4 years old, but I have a couple different options:

Option 1: Using tar --to-command grep

The following line will look in example.tgz for PATTERN. This is similar to @Jester's example, but I couldn't get his pattern matching to work.

tar xzf example.tgz --to-command 'grep --label="$TAR_FILENAME" -H PATTERN ; true'

Option 2: Using tar -tzf

The second option is using tar -tzf to list the files, then go through them with grep. You can create a function to use it over and over:

targrep () {
    for i in $(tar -tzf "$1"); do
        results=$(tar -Oxzf "$1" "$i" | grep --label="$i" -H "$2")
        echo "$results"
    done
}

Usage:

targrep example.tar.gz "pattern"

Java optional parameters

In JDK>1.5 you can use it like this;

public class NewClass1 {

    public static void main(String[] args) {

        try {
            someMethod(18); // Age : 18
            someMethod(18, "John Doe"); // Age & Name : 18 & John Doe
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static void someMethod(int age, String... names) {

        if (names.length > 0) {
            if (names[0] != null) {
                System.out.println("Age & Name : " + age + " & " + names[0]);
            }
        } else {
            System.out.println("Age : " + age);
        }
    }
}

How to use opencv in using Gradle?

I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android

You can include it on your project only adding two lines into build.gradle file thanks to jitpack.io service.

Why is this program erroneously rejected by three C++ compilers?

The first problem is, that you are trying to return an incorrect value at the end of the main function. C++ standard dictates that the return type of main() is int, but instead you are trying to return the empty set.

The other problem is - at least with g++ - that the compiler deduces the language used from the file suffix. From g++(1):

For any given input file, the file name suffix determines what kind of compilation is done:

file.cc file.cp file.cxx file.cpp file.CPP file.c++ file.C

C ++ source code which must be preprocessed. Note that in .cxx, the last two letters must both be literally x. Likewise, .C refers to a literal capital C.

Fixing these should leave you with a fully working Hello World application, as can be seen from the demo here.

Simple way to find if two different lists contain exactly the same elements?

If you care about order, then just use the equals method:

list1.equals(list2)

From the javadoc:

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:

public static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
    return new HashSet<>(list1).equals(new HashSet<>(list2));
}

A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if list1 was ["A", "B", "A"] and list2 was ["A", "B", "B"] the Set approach would consider them to be equal.

If you need to be insensitive to order but sensitive to the frequency of duplicates you can either:

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

How can I determine whether a specific file is open in Windows?

In OpenedFilesView, under the Options menu, there is a menu item named "Show Network Files". Perhaps with that enabled, the aforementioned utility is of some use.

JWT (JSON Web Token) library for Java

By referring to https://jwt.io/ you can find jwt implementations in many languages including java. Also the site provide some comparison between these implementation (the algorithms they support and ....).

For java these are mentioned libraries:

$(document).on("click"... not working?

An old post, but I love to share as I have the same case but I finally knew the problem :

Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.

Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.

But please inspect this sample that did not heed the above case :

<div class="btn-list" id="selected-country"></div>

Dynamically appended :

<button class="btn-map" data-country="'+country+'">'+ country+' </button>

This function is working good by clicking the button :

$(document).ready(function() {    
        $('#selected-country').on('click','.btn-map', function(){ 
        var datacountry = $(this).data('country'); console.log(datacountry);
    });
})

or you can use body like :

$('body').on('click','.btn-map', function(){ 
            var datacountry = $(this).data('country'); console.log(datacountry);
        });

compare to this that not working :

$(document).ready(function() {     
$('.btn-map').on("click", function() { 
        var datacountry = $(this).data('country'); alert(datacountry);
    });
});

hope it will help

Difference in days between two dates in Java?

You should use Joda Time library because Java Util Date returns wrong values sometimes.

Joda vs Java Util Date

For example days between yesterday (dd-mm-yyyy, 12-07-2016) and first day of year in 1957 (dd-mm-yyyy, 01-01-1957):

public class Main {

public static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Date date = null;
    try {
        date = format.parse("12-07-2016");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    //Try with Joda - prints 21742
    System.out.println("This is correct: " + getDaysBetweenDatesWithJodaFromYear1957(date));
    //Try with Java util - prints 21741
    System.out.println("This is not correct: " + getDaysBetweenDatesWithJavaUtilFromYear1957(date));    
}


private static int getDaysBetweenDatesWithJodaFromYear1957(Date date) {
    DateTime jodaDateTime = new DateTime(date);
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
    DateTime y1957 = formatter.parseDateTime("01-01-1957");

    return Days.daysBetween(y1957 , jodaDateTime).getDays();
}

private static long getDaysBetweenDatesWithJavaUtilFromYear1957(Date date) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Date y1957 = null;
    try {
        y1957 = format.parse("01-01-1957");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return TimeUnit.DAYS.convert(date.getTime() - y1957.getTime(), TimeUnit.MILLISECONDS);
}

So I really advice you to use Joda Time library.

Correct way to detach from a container without stopping it

Try CTRL+P,CTRL+Q to turn interactive mode to daemon.

If this does not work and you attached through docker attach, you can detach by killing the docker attach process.

Better way is to use sig-proxy parameter to avoid passing the CTRL+C to your container :

docker attach --sig-proxy=false [container-name]

Same option is available for docker run command.

Oracle date function for the previous month

I believe this would also work:

select count(distinct switch_id)   
  from [email protected]  
 where 
   dealer_name =  'XXXX'    
   and (creation_date BETWEEN add_months(trunc(sysdate,'mm'),-1) and  trunc(sysdate, 'mm'))

It has the advantage of using BETWEEN which is the way the OP used his date selection criteria.

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

<root>
    <level value="ALL" />
    <appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />
</logger>

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Intro: There are the (probably) best solutions. But you have to know it and remember it and sometimes you have to hope that your Python version isn't too old or whatever the issue could be.

Then there are the most 'hacky' solutions. They are great and short but sometimes are hard to understand, to read and to remember.

There is, though, an alternative which is to to try to reinvent the wheel. - Why reinventing the wheel? - Generally because it's a really good way to learn (and sometimes just because the already-existing tool doesn't do exactly what you would like and/or the way you would like it) and the easiest way if you don't know or don't remember the perfect tool for your problem.

So, I propose to reinvent the wheel of the Counter class from the collections module (partially at least):

class MyDict(dict):
    def __add__(self, oth):
        r = self.copy()

        try:
            for key, val in oth.items():
                if key in r:
                    r[key] += val  # You can custom it here
                else:
                    r[key] = val
        except AttributeError:  # In case oth isn't a dict
            return NotImplemented  # The convention when a case isn't handled

        return r

a = MyDict({'a':1, 'b':2, 'c':3})
b = MyDict({'b':3, 'c':4, 'd':5})

print(a+b)  # Output {'a':1, 'b': 5, 'c': 7, 'd': 5}

There would probably others way to implement that and there are already tools to do that but it's always nice to visualize how things would basically works.

Passing string parameter in JavaScript function

document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)

Better to use `` than "". This is a more dynamic answer.

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How does Python manage int and long?

Just to continue to all the answers that were given here, especially @James Lanes

the size of the integer type can be expressed by this formula:

total range = (2 ^ bit system)

lower limit = -(2 ^ bit system)*0.5 upper limit = ((2 ^ bit system)*0.5) - 1

How do I return the response from an asynchronous call?

Here is an example that works:

const validateName = async userName => {
  const url = "abc/xyz";
  try {
    const response = await axios.get(url);
    return response.data
  } catch (err) {
    return false;
  }
};

validateName("user")
 .then(data => console.log(data))
 .catch(reason => console.log(reason.message))

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I make a little update on this issue, as I just had the same error today on an application which is linking against a static lib, after I migrated the old Visual 6 project to Visual Studio 2012.

In my case the error was that I mistakenly compiled the Release version of the static lib with /MDd instead of /MD, whereas the application is /MD in release. Setting the correct /MD in the static lib project solved the issue.

This is done in Project properties

  • Select Configuration Properties / C C++ / Code Generation in the tree
  • and the option Runtime Library set to the same on all your dependencies projects and application.

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

I defined two functions in Site.Master:

    <script type="text/javascript">
    var spinnerVisible = false;
    function showProgress() {
        if (!spinnerVisible) {
            $("div#spinner").fadeIn("fast");
            spinnerVisible = true;
        }
    };
    function hideProgress() {
        if (spinnerVisible) {
            var spinner = $("div#spinner");
            spinner.stop();
            spinner.fadeOut("fast");
            spinnerVisible = false;
        }
    };
</script>

And special section:

    <div id="spinner">
        Loading...
    </div>

Visual style is defined in CSS:

div#spinner
{
    display: none;
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
    background:url(spinner.gif) no-repeat center #fff;
    text-align:center;
    padding:10px;
    font:normal 16px Tahoma, Geneva, sans-serif;
    border:1px solid #666;
    margin-left: -50px;
    margin-top: -50px;
    z-index:2;
    overflow: auto;
}

Groovy String to Date

Date#parse is deprecated . The alternative is :

java.text.DateFormat#parse 

thereFore :

 new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)

Note that SimpleDateFormat is an implementation of DateFormat

How to get the name of the current Windows user in JavaScript

I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

How to get the directory of the currently running file?

if you use this way :

dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
    log.Fatal(err)
}
fmt.Println(dir)

you will get the /tmp path when you are running program using some IDE like GoLang because the executable will save and run from /tmp

i think the best way for getting the currentWorking Directory or '.' is :

import(
  "os" 
  "fmt"
  "log"
)

func main() {
  dir, err := os.Getwd()
    if err != nil {
        log.Fatal(err)
    }
  fmt.Println(dir)
}

the os.Getwd() function will return the current working directory. and its all without using of any external library :D

Pad with leading zeros

An integer value is a mathematical representation of a number and is ignorant of leading zeroes.

You can get a string with leading zeroes like this:

someNumber.ToString("00000000")

Parsing JSON using C

NXJSON is full-featured yet very small (~400 lines of code) JSON parser, which has easy to use API:

const nx_json* json=nx_json_parse_utf8(code);
printf("hello=%s\n", nx_json_get(json, "hello")->text_value);
const nx_json* arr=nx_json_get(json, "my-array");
int i;
for (i=0; i<arr->length; i++) {
  const nx_json* item=nx_json_item(arr, i);
  printf("arr[%d]=(%d) %ld\n", i, (int)item->type, item->int_value);
}
nx_json_free(json);

How to get method parameter names?

Take a look at the inspect module - this will do the inspection of the various code object properties for you.

>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)

The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.

>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))

Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a ValueError if you use inspect.getfullargspec() on a built-in function.

Since Python 3.3, you can use inspect.signature() to see the call signature of a callable object:

>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>

Java reflection: how to get field value from an object, not knowing its class

Assuming a simple case, where your field is public:

List list; // from your method
for(Object x : list) {
    Class<?> clazz = x.getClass();
    Field field = clazz.getField("fieldName"); //Note, this can throw an exception if the field doesn't exist.
    Object fieldValue = field.get(x);
}

But this is pretty ugly, and I left out all of the try-catches, and makes a number of assumptions (public field, reflection available, nice security manager).

If you can change your method to return a List<Foo>, this becomes very easy because the iterator then can give you type information:

List<Foo> list; //From your method
for(Foo foo:list) {
    Object fieldValue = foo.fieldName;
}

Or if you're consuming a Java 1.4 interface where generics aren't available, but you know the type of the objects that should be in the list...

List list;
for(Object x: list) {
   if( x instanceof Foo) {
      Object fieldValue = ((Foo)x).fieldName;
   }
}

No reflection needed :)

laravel collection to array

Try collect function in array like:

$comments_collection = collect($post->comments()->get()->toArray());

this methods can help you

toArray() with collect()

How to check if image exists with given url?

Use Case

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API :

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

Note : rm means here risk managment .


Another Use Case :

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • 'http://example/1.png' : if not exist 'http://example/2.png'

  • 'http://example/2.png' : if not exist 'http://example/3.png'

Close application and launch home screen on Android

You can also specify noHistory = "true" in the tag for first activity or finish the first activity as soon as you start the second one(as David said).

AFAIK, "force close" kills the process which hosts the JVM in which your application runs and System.exit() terminates the JVM running your application instance. Both are form of abrupt terminations and not advisable for normal application flow.

Just as catching exceptions to cover logic flows that a program might undertake, is not advisable.