Programs & Examples On #Virus

A computer virus is a computer program that can replicate itself and spread from one computer to another. The term "virus" is also commonly, but erroneously, used to refer to other types of malware, including but not limited to adware and spyware programs that do not have a reproductive ability.

Multiple Errors Installing Visual Studio 2015 Community Edition

As described from other answers, but with steps:

1- go to control panel -> uninstall programs -> uninstall all Microsoft C++ ((year)) Redistributable

2- delete those files if they still exist manually:

  • c:\windows\System32\vcruntime140.dll
  • c:\windows\SysWOW64\vcruntime140.dll

3- download and install: https://www.microsoft.com/en-us/download/details.aspx?id=48145

after that rerun the installation of Visual Studio, and hope that error won't show again.

SQL Developer with JDK (64 bit) cannot find JVM

For Windows Users: If anyone downloaded a non-jre version and faced issue, then later trying with the JRE version and still facing the issue, you need to delete SQLDeveloper folder inside "%AppData%\sqldeveloper". After deleting try opening sqldeveloper.exe again.

Android Studio gradle takes too long to build

I had a similar issue on my computer. Windows Defender was blocking some part of Gradle Building. I've disabled it, worked fine after that.

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

wget/curl large file from google drive

No answer proposes what works for me as of december 2016 (source):

curl -L https://drive.google.com/uc?id={FileID}

provided the Google Drive file has been shared with those having the link and {FileID} is the string behind ?id= in the shared URL.

Although I did not check with huge files, I believe it might be useful to know.

Visual Studio breakpoints not being hit

In Visual Studio 2017 you need to make sure you're not in release configuration mode.

  1. Open the build menu ddl
  2. Click configuration manager
  3. Change from 'release' to 'debug'

configuration manager debug

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.

If you're using GoDaddy Plesk Hosting, use the following SMTP details.

Host = relay-hosting.secureserver.net
Port = 25 

Direct download from Google Drive using Google Drive API

https://github.com/google/skicka

I used this command line tool to download files from Google Drive. Just follow the instructions in Getting Started section and you should download files from Google Drive in minutes.

Android Studio: Unable to start the daemon process

Error:Unable to start the daemon process.

This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized JVM option is used.

Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

I know this is late to the game, but I wanted to share in case it helps someone.

Your exact situation may not apply, however I had a similar situation and setting the File attribute helped.

Try to set the File attribute to Normal:

var path = Server.MapPath("~/App_Data/file.txt");
File.SetAttributes(path, FileAttributes.Normal);
System.IO.File.WriteAllText(path, "Hello World");

I hope this helps someone.

How to read xml file contents in jQuery and display in html elements?

responseText is what you are looking for. Example:

    $.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});

Where xml is your file. Remember this will be your xml in the form form of a string. You can parse it using xmlparse as some of them mentioned.

The remote server returned an error: (403) Forbidden

We should access the website using the name given in the certificate.enter image description here

Cannot access wamp server on local network

Wamp server share in local network

Reference Link: http://forum.aminfocraft.com/blog/view/141/wamp-server-share-in-local-netword

Edit your Apache httpd.conf:

Options FollowSymLinks
AllowOverride None
Order deny,allow
Allow from all
#Deny from all

and

#onlineoffline tag - don't remove
Order Deny,Allow
Allow from all
#Deny from all

to share mysql server:

edit wamp/alias/phpmyadmin.conf

<Directory "E:/wamp/apps/phpmyadmin3.2.0.1/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order Deny,Allow
    #Deny from all
    Allow from all


Windows batch script to unhide files hidden by virus

Try this.

Does not require any options to change.

Does not require any command line activity.

Just run software and you will done the job.

www.vhghorecha.in/unhide-all-files-folders-virus/

Happy Knowledge Sharing

Install apps silently, with granted INSTALL_PACKAGES permission

Its possible to do silent install on Android 6 and above. Using the function supplied in the answer by Boris Treukhov, ignore everything else in the post, root is not required either.

Install your app as device admin, you can have full kiosk mode with silent install of updates in the background.

Git Bash is extremely slow on Windows 7 x64

I've encountered the same problem running Git for Windows (msysgit) on Windows 7 x64 as a limited user account for quite some time.

From what I've read here and other places, the common theme seems to be the lack of administrative privileges and/or UAC. Since UAC is off on my system, the explanation that it is trying to write/delete something in the program files directory makes the most sense to me.

In any case, I've resolved my problem by installing the portable version of Git 1.8 with zipinstaller. Note that I had to unpack the .7z distribution file and repack it as a ZIP file in order for zipinstaller to work. I also had to manually add that directory to my system path.

The performance is fine now. Even though it is installed in the Program Files (x86) directory, which I don't have permissions for as a limited user, it doesn't seem to suffer from the same problem.

I ascribe this either to the fact that the portable version is a bit more conservative in where it writes/deletes files, which is probably the case, or to the upgrade from 1.7 to 1.8. I'm not going to try to pin down which one is the reason, suffice to say it works much better now, including Bash.

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

In a loop it's harmless, but in an assignment statement it can lead to unexpected results:

var x = 5;
var y = x++; // y is now 5 and x is 6
var z = ++x; // z is now 7 and x is 7

Whitespace between the variable and the operator can lead to unexpected results as well:

a = b = c = 1; a ++ ; b -- ; c; console.log('a:', a, 'b:', b, 'c:', c)

In a closure, unexpected results can be an issue as well:

var foobar = function(i){var count = count || i; return function(){return count++;}}

baz = foobar(1);
baz(); //1
baz(); //2


var alphabeta = function(i){var count = count || i; return function(){return ++count;}}

omega = alphabeta(1);
omega(); //2
omega(); //3

And it triggers automatic semicolon insertion after a newline:

var foo = 1, bar = 2, baz = 3, alpha = 4, beta = 5, delta = alpha
++beta; //delta is 4, alpha is 4, beta is 6

preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose. Fortunately, they are also complete unnecessary. There are better ways to add 1 to a variable.

References

Firefox "ssl_error_no_cypher_overlap" error

The first thing I would check is the config for mod_nss. It is the odd one out, for it is yours and there is none in the world like it :-) Whereas if there was some huge bug in Firefox or mod_nss itself, I guess you'd have found out about it by now in your google quest. The fact that you've fiddled with the config (e.g. disabling SSL3, and various other random tweaks), is also suspicious.

I'd back track to a very vanilla mod_nss config and see if that works. Then change things systematically towards your current config until you can reproduce the problem. By the sound of it the source of the error is somewhere in the cipher spec config of mod_nss and the related protocol negotiation stuff. So maybe you inadvertently changed something there when trying to turn off SSLv3 (incidentally, why disable SSL3? Normally people disable V2?).

One other thing to check is that you're on the latest mod_nss and it's not a known bug in that. The fact that it manages to start the session and then fails later is interesting - it suggests that maybe it is trying to renegotiate the session and failing to negotiate ciphers at that point. So it might be the symmetric ciphers. Or it could simply be an implementation bug in your version of mod_nss that somehow garbles the protocol.

One other idea, and this is a wild guess, is the browser is trying to resume a session which was negotiated with SSLv3 before you disabled it, and something breaks when trying to resume that session when V3 is turned off, or maybe mod_nss just doesn't implement it right.

The java/tomcat stuff seems like a red herring as unless I've misunderstood your description, none of that is involved in the SSL handshake/protocol.

Good tool for testing socket connections?

I would go with netcat too , but since you can't use it , here is an alternative : netcat :). You can find netcat implemented in three languages ( python/ruby/perl ) . All you need to do is install the interpreters for the language you choose . Surely , that won't be viewed as a hacking tool .

Here are the links :

Perl implementation

Python implementation

Ruby Implementation

RegEx to parse or validate Base64 data

Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com line. In Perl, say, something like

my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;

say decode_base64($sanitized_str);

might be what you want. It produces

This is simple ASCII Base64 for StackOverflow exmaple.

How to improve Netbeans performance?

deactivate Git, Subversion, Local History, Spell checker and other unused plugins

How to install Laravel's Artisan?

in laravel, artisan is a file under root/protected page

for example,

c:\xampp\htdocs\my_project\protected\artisan

you can view the content of "artisan" file with any text editor, it's a php command syntax

so when we type

php artisan

we tell php to run php script in "artisan" file

for example:

php artisan change

will show the change of current laravel version

to see the other option, just type

php artisan

Spring Boot application as a Service

Create a script with name your-app.service (rest-app.service). We should place this script in /etc/systemd/system directory. Here is the sample content of the script

[Unit]
Description=Spring Boot REST Application
After=syslog.target

[Service]
User=javadevjournal
ExecStart=/var/rest-app/restdemo.jar
SuccessExitStatus=200

[Install]
WantedBy=multi-user.target

Next:

 service rest-app start

References

enter link description here

openssl s_client using a proxy

Even with openssl v1.1.0 I had some problems passing our proxy, e.g. s_client: HTTP CONNECT failed: 400 Bad Request That forced me to write a minimal Java-class to show the SSL-Handshake

    public static void main(String[] args) throws IOException, URISyntaxException {
    HttpHost proxy = new HttpHost("proxy.my.company", 8080);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRoutePlanner(routePlanner)
            .build();
    URI uri = new URIBuilder()
            .setScheme("https")
            .setHost("www.myhost.com")
            .build();
    HttpGet httpget = new HttpGet(uri);
    httpclient.execute(httpget);
}

With following dependency:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
        <type>jar</type>
    </dependency>

you can run it with Java SSL Logging turned on

This should produce nice output like

trustStore provider is :
init truststore
adding as trusted cert:
  Subject: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Issuer:  CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Algorithm: RSA; Serial number: 0xc3517
  Valid from Mon Jun 21 06:00:00 CEST 1999 until Mon Jun 22 06:00:00 CEST 2020

adding as trusted cert:
  Subject: CN=SecureTrust CA, O=SecureTrust Corporation, C=US
  Issuer:  CN=SecureTrust CA, O=SecureTrust Corporation, C=US
(....)

How to change the port number for Asp.Net core app?

We can use this command to run our host project via Windows Powershell without IIS and visual studio on a separate port. Default of krestel web server is 5001

$env:ASPNETCORE_URLS="http://localhost:22742" ; dotnet run

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

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

wksht.Unprotect()

and re-protect it after you're done:

wksht.Protect()

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

What is the most elegant way to check if all values in a boolean array are true?

You can check all value items are true or false by compare your array with the other boolean array via Arrays.equal method like below example :

private boolean isCheckedAnswer(List<Answer> array) {
    boolean[] isSelectedChecks = new boolean[array.size()];
    for (int i = 0; i < array.size(); i++) {
        isSelectedChecks[i] = array.get(i).isChecked();
    }

    boolean[] isAllFalse = new boolean[array.size()];
    for (int i = 0; i < array.size(); i++) {
        isAllFalse[i] = false;
    }

    return !Arrays.equals(isSelectedChecks, isAllFalse);
}

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

I am using Windows 10 and korean version of Visual studio. I wanted to change from korean to english. I downloaded the english language pack but the error message appeared as "compatibility mode is on..." the only solution to this issue is to rename the Language pack setup file name with its original name, that is to say vs_langpack.exe . And boom the issue is solved.

Hope it is helpful.

Thanks.

SQLException : String or binary data would be truncated

It could also be because you're trying to put in a null value back into the database. So one of your transactions could have nulls in them.

Send auto email programmatically

It might be an easiest way-

    String recipientList = mEditTextTo.getText().toString();
    String[] recipients = recipientList.split(",");

    String subject = mEditTextSubject.getText().toString();
    String message = mEditTextMessage.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);

    intent.setType("message/rfc822");
    startActivity(Intent.createChooser(intent, "Choose an email client"));

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

How to access model hasMany Relation with where condition?

//lower for v4 some version

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}

//v5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}

How to supply value to an annotation from a Constant java

You're not supplying it with an array in your example. The following compiles fine:

public @interface SampleAnnotation {
    String[] sampleValues();
}

public class Values {
    public static final String val0 = "A";
    public static final String val1 = "B";

    @SampleAnnotation(sampleValues={ val0, val1 })
    public void foo() {
    }
}

Toggle input disabled attribute using jQuery

I guess to get full browser comparability disabled should set by the value disabled or get removed!
Here is a small plugin that I've just made:

(function($) {
    $.fn.toggleDisabled = function() {
        return this.each(function() {
            var $this = $(this);
            if ($this.attr('disabled')) $this.removeAttr('disabled');
            else $this.attr('disabled', 'disabled');
        });
    };
})(jQuery);

Example link.

EDIT: updated the example link/code to maintaining chainability!
EDIT 2:
Based on @lonesomeday comment, here's an enhanced version:

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

Error CS1705: "which has a higher version than referenced assembly"

3 ideas for you to try:

  1. Make sure that all your dlls are compiled against the same version of Common.
  2. Check that you have project references in your solution instead of file references.
  3. Use binding redirections in your web.config. (Originally linked version at wayback machine)

send Content-Type: application/json post with node.js

As the official documentation says:

body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.

When sending JSON you just have to put it in body of the option.

var options = {
    uri: 'https://myurl.com',
    method: 'POST',
    json: true,
    body: {'my_date' : 'json'}
}
request(options, myCallback)

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

As mentioned, you can use:

=Format(Fields!Price.Value, "C")

A digit after the "C" will specify precision:

=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")

You can also use Excel-style masks like this:

=Format(Fields!Price.Value, "#,##0.00")

Haven't tested the last one, but there's the idea. Also works with dates:

=Format(Fields!Date.Value, "yyyy-MM-dd")

Scrolling a div with jQuery

jCarousel is a Jquery Plugin , it have same functionality already implemented , which might want to archive. it's nice and easy. here is the link

and complete documentation can be found here

Get checkbox values using checkbox name using jquery

$('[name="CheckboxName"]:checked').each(function () {
    // do stuff
});

How to change status bar color in Flutter?

This is everything you need to know:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    systemNavigationBarColor: Colors.amber, // navigation bar color
    statusBarColor: Colors.white, // status bar color
    statusBarIconBrightness: Brightness.dark, // status bar icon color
    systemNavigationBarIconBrightness: Brightness.dark, // color of navigation controls
  ));
  runApp(MyApp());
}

Styling mat-select in Angular Material

Put your class name on the mat-form-field element. This works for all inputs.

Creating .pem file for APNS?

Launch the Terminal application and enter the following command after the prompt

  openssl pkcs12 -in CertificateName.p12 -out CertificateName.pem -nodes

Base64 encoding in SQL Server 2005 T-SQL

The simplest and shortest way I could find for SQL Server 2012 and above is BINARY BASE64 :

SELECT CAST('string' as varbinary(max)) FOR XML PATH(''), BINARY BASE64

For Base64 to string

SELECT CAST( CAST( 'c3RyaW5n' as XML ).value('.','varbinary(max)') AS varchar(max) )

( or nvarchar(max) for Unicode strings )

Reading CSV file and storing values into an array

Here's a special case where one of data field has semicolon (";") as part of it's data in that case most of answers above will fail.

Solution it that case will be

string[] csvRows = System.IO.File.ReadAllLines(FullyQaulifiedFileName);
string[] fields = null;
List<string> lstFields;
string field;
bool quoteStarted = false;
foreach (string csvRow in csvRows)
{
    lstFields = new List<string>();
    field = "";
    for (int i = 0; i < csvRow.Length; i++)
    {
        string tmp = csvRow.ElementAt(i).ToString();
        if(String.Compare(tmp,"\"")==0)
        {
            quoteStarted = !quoteStarted;
        }
        if (String.Compare(tmp, ";") == 0 && !quoteStarted)
        {
            lstFields.Add(field);
            field = "";
        }
        else if (String.Compare(tmp, "\"") != 0)
        {
            field += tmp;
        }
    }
    if(!string.IsNullOrEmpty(field))
    {
        lstFields.Add(field);
        field = "";
    }
// This will hold values for each column for current row under processing
    fields = lstFields.ToArray(); 
}

python replace single backslash with double backslash

Given the source string, manipulation with os.path might make more sense, but here's a string solution;

>>> s=r"C:\Users\Josh\Desktop\\20130216"
>>> '\\\\'.join(filter(bool, s.split('\\')))
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'

Note that split treats the \\ in the source string as a delimited empty string. Using filter gets rid of those empty strings so join won't double the already doubled backslashes. Unfortunately, if you have 3 or more, they get reduced to doubled backslashes, but I don't think that hurts you in a windows path expression.

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

What are the differences between type() and isinstance()?

For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

From above abc.__instancecheck__, after using test below:

# file tree
# /test/__init__.py
# /test/aaa/__init__.py
# /test/aaa/aa.py
class b():
pass

# /test/aaa/a.py
import sys
sys.path.append('/test')

from aaa.aa import b
from aa import b as c

d = b()

print(b, c, d.__class__)
for i in [b, c, object]:
    print(i, '__subclasses__',  i.__subclasses__())
    print(i, '__mro__', i.__mro__)
    print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
    print(i, '__subclasshook__', i.__subclasshook__(type(d)))
print(isinstance(d, b))
print(isinstance(d, c))

<class 'aaa.aa.b'> <class 'aa.b'> <class 'aaa.aa.b'>
<class 'aaa.aa.b'> __subclasses__ []
<class 'aaa.aa.b'> __mro__ (<class 'aaa.aa.b'>, <class 'object'>)
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasses__ []
<class 'aa.b'> __mro__ (<class 'aa.b'>, <class 'object'>)
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'object'> __subclasses__ [..., <class 'aaa.aa.b'>, <class 'aa.b'>]
<class 'object'> __mro__ (<class 'object'>,)
<class 'object'> __subclasshook__ NotImplemented
<class 'object'> __subclasshook__ NotImplemented
True
False

I get this conclusion, For type:

# according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
type(INSTANCE) ~= INSTANCE.__class__
type(CLASS) ~= CLASS.__class__

For isinstance:

# guess from `abc.__instancecheck__`
return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})

BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

In My Case, Im trying to pass messages from Salesforce Marketing Cloud Custom Activity(Domain 1) to Heroku(Domain 2) on load.

The Error Appeared in console, when I loaded my original html page from where message is being passed.

Issue I noticed after reading many blogs is that, the receiver page is not loaded yet. i.e

I need to debug from my receiver page not from sender page.

Simple but glad if it helps anyone.

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

versionCode vs versionName in Android Manifest

The answer from Tanoh could use some clarification. VersionCode is the equivalent of a build number. So typically an app will go through many iterations before release. Some of these iterations may make it to the Google Play store in the form of alpha, beta, and actual releases. Each successive iteration must have an incremented versionCode. However, typically you only increase the versionName when between public releases. Both numbers are significant. Your users need to know if the version they have on their phone is the latest or not (versionName) and the Play Store and CI systems such as bitrise rely on and/or update the build number (versionCode)

Using CSS td width absolute, position

This may not be what you want to hear, but display: table-cell does not respect width and will be collapsed based on the width of the entire table. You can get around this easily just by having a display: block element inside of the table cell itself whose width you specify, e.g

<td><div style="width: 300px;">wide</div></td>

This shouldn't make much of a difference if the <table> itself is position: fixed or absolute because the position of the cells are all static relative to the table.

http://jsfiddle.net/ExplosionPIlls/Mkq8L/4/

EDIT: I can't take credit, but as the comments say you can just use min-width instead of width on the table cell instead.

How to query all the GraphQL type fields without writing a long query?

GraphQL query format was designed in order to allow:

  1. Both query and result shape be exactly the same.
  2. The server knows exactly the requested fields, thus the client downloads only essential data.

However, according to GraphQL documentation, you may create fragments in order to make selection sets more reusable:

# Only most used selection properties

fragment UserDetails on User {
    id,
    username
} 

Then you could query all user details by:

FetchUsers {
    users() {
        ...UserDetails
    }
}

You can also add additional fields alongside your fragment:

FetchUserById($id: ID!) {
    users(id: $id) {
        ...UserDetails
        count
    }
}

Correct way to initialize HashMap and can HashMap hold different value types?

Eclipse is suggesting you to define generic type so that you can have type safety. You can write

Map m = new HashMap();

which does not ensure type safety but following will ensure type safety

Map<Object,Object> = new HashMap<Object,Object>();

The Object can be any type such as String, Integer etc.

How to send a pdf file directly to the printer using JavaScript?

a function to house the print trigger...

function printTrigger(elementId) {
    var getMyFrame = document.getElementById(elementId);
    getMyFrame.focus();
    getMyFrame.contentWindow.print();
}

an button to give the user access...

(an onClick on an a or button or input or whatever you wish)

<input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
an iframe pointing to your PDF...

<iframe id="iFramePdf" src="myPdfUrl.pdf" style="dispaly:none;"></iframe>

More : http://www.fpdf.org/en/script/script36.php

How to split one text file into multiple *.txt files?

John's answer won't produce .txt files as the OP wants. Use:

split -b=1M -d  file.txt file --additional-suffix=.txt

How can I install pip on Windows?

If you even have other problems with the pip version, you can try this:

pip install --trusted-host pypi.python.org --upgrade pip

set environment variable in python script

There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote() to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).

shell=False is always the default where you pass an argument array.

Now the safe solutions...

Method #1

Change your own process's environment - the new environment will apply to python itself and all subprocesses.

os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Method #2

Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.

myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)

Method #3

Unix only: Execute env to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.

command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Of course if var1 contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True you must compose a command array that contain the splitted string:

command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

When adding 22.5 million records into an array with array_push I kept getting "memory exhausted" fatal errors at around 20M records using 4G as the memory limit in file php.ini. To fix this, I added the statement

$old = ini_set('memory_limit', '8192M');

at the top of the file. Now everything is working fine. I do not know if PHP has a memory leak. That is not my job, nor do I care. I just have to get my job done, and this worked.

The program is very simple:

$fh = fopen($myfile);
while (!feof($fh)) {
    array_push($file, stripslashes(fgets($fh)));
}
fclose($fh);

The fatal error points to line 3 until I boosted the memory limit, which eliminated the error.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

In the %run magic documentation you can find:

-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.

Therefore, supplying -i does the trick:

%run -i 'script.py'

The "correct" way to do it

Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don't know how a more pythonic way would look like.
The solution above is a little hacky, and makes the code in the other file confusing (Where does this x variable come from? and what is the f function?).

I'd like to show you how to do it without actually having to execute the other file over and over again.
Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
If you're constantly editing the other file, then autoreload comes to your help.

Your example would look like this:
script.py

import matplotlib.pyplot as plt

def myplot(f, x):
    """
    :param f: function to plot
    :type f: callable
    :param x: values for x
    :type x: list or ndarray

    Plots the function f(x).
    """
    # yes, you can pass functions around as if
    # they were ordinary variables (they are)
    plt.plot(x, f(x))
    plt.xlabel("Eje $x$",fontsize=16)
    plt.ylabel("$f(x)$",fontsize=16)
    plt.title("Funcion $f(x)$")

Jupyter console

In [1]: import numpy as np

In [2]: %load_ext autoreload

In [3]: %autoreload 1

In [4]: %aimport script

In [5]: def f(x):
      :     return np.exp(-x ** 2)
      :
      :

In [6]: x = np.linspace(-1, 3, 100)

In [7]: script.myplot(f, x)

In [8]: ?script.myplot
Signature: script.myplot(f, x)
Docstring:
:param f: function to plot
:type f: callable
:param x: x values
:type x: list or ndarray
File:      [...]\script.py
Type:      function

Call a React component method from outside

There are two ways to access an inner function. One, instance-level, like you want, another, static level.

Instance

You need to call the function on the return from React.render. See below.

Static

Take a look at ReactJS Statics. Note, however, that a static function cannot access instance-level data, so this would be undefined.

var onButtonClick = function () {
    //call alertMessage method from the reference of a React Element! 
    HelloRendered.alertMessage();
    //call static alertMessage method from the reference of a React Class! 
    Hello.alertMessage();
    console.log("clicked!");
}

var Hello = React.createClass({
    displayName: 'Hello',
    statics: {
        alertMessage: function () {
            alert('static message');
        }
    },
    alertMessage: function () {
        alert(this.props.name);
    },

    render: function () {
        return React.createElement("div", null, "Hello ", this.props.name);
    }
});

var HelloElement = React.createElement(Hello, {
    name: "World"
});

var HelloRendered = React.render(HelloElement, document.getElementById('container'));

Then do HelloRendered.alertMessage().

Converting unix timestamp string to readable date

You can use easy_date to make it easy:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

web-api POST body object always null

None of the above was my solution: in my case the issue is that [ApiController] was not added to the controller so it is giving Null value

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController] // This was my problem, make sure that it is there!
public class OrderController : Controller

...

Converting 'ArrayList<String> to 'String[]' in Java

Generics solution to covert any List<Type> to String []:

public static  <T> String[] listToArray(List<T> list) {
    String [] array = new String[list.size()];
    for (int i = 0; i < array.length; i++)
        array[i] = list.get(i).toString();
    return array;
}

Note You must override toString() method.

class Car {
  private String name;
  public Car(String name) {
    this.name = name;
  }
  public String toString() {
    return name;
  }
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Please check the following file

%SystemRoot%\system32\drivers\etc\host

The line which bind the host name with ip is probably missing a line which bind them togather

127.0.0.1  localhost

If the given line is missing. Add the line in the file


Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.

else & elif statements not working in Python

 if guess == number:
     print ("Good")
 elif guess == 2:
     print ("Bad")
 else:
     print ("Also bad")

Make sure you have your identation right. The syntax is ok.

\r\n, \r and \n what is the difference between them?

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

django - get() returned more than one topic

I had same problem and solution was obj = ClassName.objects.filter()

"Specified argument was out of the range of valid values"

I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Saving the PuTTY session logging

I always have to check my cheatsheet :-)

Step 1: right-click on the top of putty window and select 'Change settings'.

Step 2: type the name of the session and save.

That's it!. Enjoy!

From an array of objects, extract value of a property as array

If you want multiple values in ES6+ the following will work

objArray = [ { foo: 1, bar: 2, baz: 9}, { foo: 3, bar: 4, baz: 10}, { foo: 5, bar: 6, baz: 20} ];

let result = objArray.map(({ foo, baz }) => ({ foo, baz }))

This works as {foo, baz} on the left is using object destructoring and on the right side of the arrow is equivalent to {foo: foo, baz: baz} due to ES6's enhanced object literals.

Angular2 module has no exported member

I had the component name wrong(it is case sensitive) in either app.rounting.ts or app.module.ts.

Jasmine JavaScript Testing - toBe vs toEqual

toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.

I would say use toBe() when comparing values, and toEqual() when comparing objects.

When comparing primitive types, toEqual() and toBe() will yield the same result. When comparing objects, toBe() is a stricter comparison, and if it is not the exact same object in memory this will return false. So unless you want to make sure it's the exact same object in memory, use toEqual() for comparing objects.

Check this link out for more info : http://evanhahn.com/how-do-i-jasmine/

Now when looking at the difference between toBe() and toEqual() when it comes to numbers, there shouldn't be any difference so long as your comparison is correct. 5 will always be equivalent to 5.

A nice place to play around with this to see different outcomes is here

Update

An easy way to look at toBe() and toEqual() is to understand what exactly they do in JavaScript. According to Jasmine API, found here:

toEqual() works for simple literals and variables, and should work for objects

toBe() compares with ===

Essentially what that is saying is toEqual() and toBe() are similar Javascripts === operator except toBe() is also checking to make sure it is the exact same object, in that for the example below objectOne === objectTwo //returns false as well. However, toEqual() will return true in that situation.

Now, you can at least understand why when given:

var objectOne = {
    propertyOne: str,
    propertyTwo: num    
}

var objectTwo = {
    propertyOne: str,
    propertyTwo: num    
}

expect(objectOne).toBe(objectTwo); //returns false

That is because, as stated in this answer to a different, but similar question, the === operator actually means that both operands reference the same object, or in case of value types, have the same value.

413 Request Entity Too Large - File Upload Issue

I add the changes directly to my virtualhost instead the global config of nginx, like this:

   server {
     client_max_body_size 100M;
     ...
   }

And then I change the params in php.ini, like the comments above:

   max_input_time = 24000
   max_execution_time = 24000
   upload_max_filesize = 12000M
   post_max_size = 24000M
   memory_limit = 12000M

and what you can not forget is to restart nginx and php-fpm, in centos 7 is like this:

  systemctl restart nginx
  systemctl restart php-fpm

SQL Server replace, remove all after certain character

For situations when I need to replace or match(find) something against string I prefer using regular expressions.

Since, the regular expressions are not fully supported in T-SQL you can implement them using CLR functions. Furthermore, you do not need any C# or CLR knowledge at all as all you need is already available in the MSDN String Utility Functions Sample.

In your case, the solution using regular expressions is:

SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]

But implementing such function in your database is going to help you solving more complex issues at all.


The example below shows how to deploy only the [dbo].[RegexReplace] function, but I will recommend to you to deploy the whole String Utility class.

  1. Enabling CLR Integration. Execute the following Transact-SQL commands:

    sp_configure 'clr enabled', 1
    GO
    RECONFIGURE
    GO  
    
  2. Bulding the code (or creating the .dll). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.

    • create new class library project:

      enter image description here

    • copy and paste the following code in the Class1.cs file:

      using System;
      using System.IO;
      using System.Data.SqlTypes;
      using System.Text.RegularExpressions;
      using Microsoft.SqlServer.Server;
      
      public sealed class RegularExpression
      {
          public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
          {
              string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
              string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
              string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
              return Regex.Replace(input, pattern, replacement);
          }
      }
      
    • build the solution and get the path to the created .dll file:

      enter image description here

    • replace the path to the .dll file in the following T-SQL statements and execute them:

      IF OBJECT_ID(N'RegexReplace', N'FS') is not null
      DROP Function RegexReplace;
      GO
      
      IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
      DROP ASSEMBLY StringUtils;
      GO
      
      DECLARE @SamplePath nvarchar(1024)
      -- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
      Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
      CREATE ASSEMBLY [StringUtils] 
      FROM @SamplePath + 'StringUtils.dll'
      WITH permission_set = Safe;
      GO
      
      
      CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
      RETURNS nvarchar(max)
      AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
      GO
      
    • That's it. Test your function:

      declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
      insert into @MyTable ([id], MyText)
      select 1, 'some text; some more text'
      union all select 2, 'text again; even more text'
      union all select 3, 'text without a semicolon'
      union all select 4, null -- test NULLs
      union all select 5, '' -- test empty string
      union all select 6, 'test 3 semicolons; second part; third part'
      union all select 7, ';' -- test semicolon by itself    
      
      SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
      FROM @MyTable
      
      select * from @MyTable
      

Java finished with non-zero exit value 2 - Android Gradle

I didn't know (by then) that "compile fileTree(dir: 'libs', include: ['*.jar'])" compile all that has jar extension on libs folder, so i just comment (or delete) this lines:

//compile 'com.squareup.retrofit:retrofit:1.9.0'
//compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
//compile 'com.squareup.okhttp:okhttp:2.2.0'

//compile files('libs/spotify-web-api-android-master-0.1.0.jar')
//compile files('libs/okio-1.3.0.jar')

and it works fine. Thanks anyway! My bad.

Simplest way to detect a pinch

Think about what a pinch event is: two fingers on an element, moving toward or away from each other. Gesture events are, to my knowledge, a fairly new standard, so probably the safest way to go about this is to use touch events like so:

(ontouchstart event)

if (e.touches.length === 2) {
    scaling = true;
    pinchStart(e);
}

(ontouchmove event)

if (scaling) {
    pinchMove(e);
}

(ontouchend event)

if (scaling) {
    pinchEnd(e);
    scaling = false;
}

To get the distance between the two fingers, use the hypot function:

var dist = Math.hypot(
    e.touches[0].pageX - e.touches[1].pageX,
    e.touches[0].pageY - e.touches[1].pageY);

How to list all AWS S3 objects in a bucket using Java

I am processing a large collection of objects generated by our system; we changed the format of the stored data and needed to check each file, determine which ones were in the old format, and convert them. There are other ways to do this, but this one relates to your question.

    ObjectListing list = amazonS3Client.listObjects(contentBucketName, contentKeyPrefix);

    do {                

        List<S3ObjectSummary> summaries = list.getObjectSummaries();

        for (S3ObjectSummary summary : summaries) {

            String summaryKey = summary.getKey();               

            /* Retrieve object */

            /* Process it */

        }

        list = amazonS3Client.listNextBatchOfObjects(list);

    }while (list.isTruncated());

XAMPP on Windows - Apache not starting

I encountered the same issue after XAMPP v3.2.1 installation. I do not have Skype as most people would believe, however as a Software Developer I assumed port 80 is already in use by my other apps. So I changed it by simply using the XAMPP Control Panel: enter image description here

Click on the 'Config' button corresponding to the APACHE service and choose the first option 'Apache (httpd.conf)'. In the document that opens (using any text editor - except MS Word!), locate the text:

Listen 12.34.56.78:80

Listen 80

And change this to:

Listen 12.34.56.78:83

Listen 83

This can be any non-used port number. Thanks.

difference between variables inside and outside of __init__()

class foo(object):
    mStatic = 12

    def __init__(self):
        self.x = "OBj"

Considering that foo has no access to x at all (FACT)

the conflict now is in accessing mStatic by an instance or directly by the class .

think of it in the terms of Python's memory management :

12 value is on the memory and the name mStatic (which accessible from the class)

points to it .

c1, c2 = foo(), foo() 

this line makes two instances , which includes the name mStatic that points to the value 12 (till now) .

foo.mStatic = 99 

this makes mStatic name pointing to a new place in the memory which has the value 99 inside it .

and because the (babies) c1 , c2 are still following (daddy) foo , they has the same name (c1.mStatic & c2.mStatic ) pointing to the same new value .

but once each baby decides to walk alone , things differs :

c1.mStatic ="c1 Control"
c2.mStatic ="c2 Control"

from now and later , each one in that family (c1,c2,foo) has its mStatica pointing to different value .

[Please, try use id() function for all of(c1,c2,foo) in different sates that we talked about , i think it will make things better ]

and this is how our real life goes . sons inherit some beliefs from their father and these beliefs still identical to father's ones until sons decide to change it .

HOPE IT WILL HELP

How to select rows for a specific date, ignoring time in SQL Server

select 
  * 
from sales 
where 
  dateadd(dd, datediff(dd, 0, salesDate), 0) = '11/11/2010'

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You should use the Chartjs API function toBase64Image() instead and call it after the animation is complete. Therefore:

var pieChart, URI;

var options = {
    animation : {
        onComplete : function(){    
            URI = pieChart.toBase64Image();
        }
    }
};

var content = {
    type: 'pie', //whatever, not relevant for this example
    data: {
        datasets: dataset //whatever, not relevant for this example
    },
    options: options        
};    

pieChart = new Chart(pieChart, content);

Example

You can check this example and run it

_x000D_
_x000D_
var chart = new Chart(ctx, {_x000D_
   type: 'bar',_x000D_
   data: {_x000D_
      labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart_x000D_
      // create 12 datasets, since we have 12 items_x000D_
      // data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')_x000D_
      // put 0, if there is no data for the particular bar_x000D_
      datasets: [{_x000D_
         label: 'Washing and cleaning',_x000D_
         data: [0, 8],_x000D_
         backgroundColor: '#22aa99'_x000D_
      }, {_x000D_
         label: 'Traffic tickets',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#994499'_x000D_
      }, {_x000D_
         label: 'Tolls',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#316395'_x000D_
      }, {_x000D_
         label: 'Parking',_x000D_
         data: [5, 2],_x000D_
         backgroundColor: '#b82e2e'_x000D_
      }, {_x000D_
         label: 'Car tax',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#66aa00'_x000D_
      }, {_x000D_
         label: 'Repairs and improvements',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#dd4477'_x000D_
      }, {_x000D_
         label: 'Maintenance',_x000D_
         data: [6, 1],_x000D_
         backgroundColor: '#0099c6'_x000D_
      }, {_x000D_
         label: 'Inspection',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#990099'_x000D_
      }, {_x000D_
         label: 'Loan interest',_x000D_
         data: [0, 3],_x000D_
         backgroundColor: '#109618'_x000D_
      }, {_x000D_
         label: 'Depreciation of the vehicle',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#109618'_x000D_
      }, {_x000D_
         label: 'Fuel',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#dc3912'_x000D_
      }, {_x000D_
         label: 'Insurance and Breakdown cover',_x000D_
         data: [4, 0],_x000D_
         backgroundColor: '#3366cc'_x000D_
      }]_x000D_
   },_x000D_
   options: {_x000D_
      responsive: false,_x000D_
      legend: {_x000D_
         position: 'right' // place legend on the right side of chart_x000D_
      },_x000D_
      scales: {_x000D_
         xAxes: [{_x000D_
            stacked: true // this should be set to make the bars stacked_x000D_
         }],_x000D_
         yAxes: [{_x000D_
            stacked: true // this also.._x000D_
         }]_x000D_
      },_x000D_
      animation : {_x000D_
         onComplete : done_x000D_
      }      _x000D_
   }_x000D_
});_x000D_
_x000D_
function done(){_x000D_
    alert(chart.toBase64Image());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>_x000D_
<canvas id="ctx" width="700"></canvas>
_x000D_
_x000D_
_x000D_

Compare two dates in Java

java.time

In Java 8 there is no need to use Joda-Time as it comes with a similar new API in the java.time package. Use the LocalDate class.

LocalDate date = LocalDate.of(2014, 3, 18);
LocalDate today = LocalDate.now();

Boolean isToday = date.isEqual( today );

You can ask for the span of time between the dates with Period class.

Period difference = Period.between(date, today);

LocalDate is comparable using equals and compareTo as it holds no information about Time and Timezone.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Can I have multiple Xcode versions installed?

Whatever advice path you go down, make a copy of your project folder, and rename the external most one to reflect what XCode version it is being opened in. Your choice on whether you want it to update syntax or not, but the main reason for all this bovver is your storyboard will be altered just by looking. It may be resolved by the time a new reader coming across this in the future, or

How can I mock requests and the response?

I used requests-mock for writing tests for separate module:

# module.py
import requests

class A():

    def get_response(self, url):
        response = requests.get(url)
        return response.text

And the tests:

# tests.py
import requests_mock
import unittest

from module import A


class TestAPI(unittest.TestCase):

    @requests_mock.mock()
    def test_get_response(self, m):
        a = A()
        m.get('http://aurl.com', text='a response')
        self.assertEqual(a.get_response('http://aurl.com'), 'a response')
        m.get('http://burl.com', text='b response')
        self.assertEqual(a.get_response('http://burl.com'), 'b response')
        m.get('http://curl.com', text='c response')
        self.assertEqual(a.get_response('http://curl.com'), 'c response')

if __name__ == '__main__':
    unittest.main()

Extracting the last n characters from a string in R

I used the following code to get the last character of a string.

    substr(output, nchar(stringOfInterest), nchar(stringOfInterest))

You can play with the nchar(stringOfInterest) to figure out how to get last few characters.

What is the purpose of the var keyword and when should I use it (or omit it)?

Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.

React / JSX Dynamic Component Name

<MyComponent /> compiles to React.createElement(MyComponent, {}), which expects a string (HTML tag) or a function (ReactClass) as first parameter.

You could just store your component class in a variable with a name that starts with an uppercase letter. See HTML tags vs React Components.

var MyComponent = Components[type + "Component"];
return <MyComponent />;

compiles to

var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});

Print the stack trace of an exception

Apache commons provides utility to convert the stack trace from throwable to string.

Usage:

ExceptionUtils.getStackTrace(e)

For complete documentation refer to https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

Difference between webdriver.get() and webdriver.navigate()

CASE-1

In the below code I navigated to 3 different URLs and when the execution comes to navigate command, it navigated back to facebook home page.

public class FirefoxInvoke {
                @Test
                public static void browserInvoke()
                {
                    System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
                WebDriver driver=new FirefoxDriver();
                System.out.println("Before"+driver.getTitle());
                driver.get("http://www.google.com");
                driver.get("http://www.facebook.com");
                driver.get("http://www.india.com");
                driver.navigate().back();
                driver.quit();
                }

                public static void main(String[] args) {
                    // TODO Auto-generated method stub
            browserInvoke();
                }

            }

CASE-2:

In below code, I have used navigate() instead of get(), but both the snippets(Case-1 and Case-2) are working exactly the same, just the case-2 execution time is less than of case-1

public class FirefoxInvoke {
                @Test
                public static void browserInvoke()
                {
                    System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
                WebDriver driver=new FirefoxDriver();
                System.out.println("Before"+driver.getTitle());
                driver.navigate().to("http://www.google.com");
                driver.navigate().to("http://www.facebook.com");
                driver.navigate().to("http://www.india.com");
                driver.navigate().back();
                driver.quit();
                }

                public static void main(String[] args) {
                    // TODO Auto-generated method stub
            browserInvoke();
                }

            }
  • So the main difference between get() and navigate() is, both are performing the same task but with the use of navigate() you can move back() or forward() in your session's history.
  • navigate() is faster than get() because navigate() does not wait for the page to load fully or completely.

Case objects vs Enumerations in Scala

I have a nice simple lib here that allows you to use sealed traits/classes as enum values without having to maintain your own list of values. It relies on a simple macro that is not dependent on the buggy knownDirectSubclasses.

https://github.com/lloydmeta/enumeratum

Comprehensive methods of viewing memory usage on Solaris

"top" is usually available on Solaris.

If not then revert to "vmstat" which is available on most UNIX system.

It should look something like this (from an AIX box)

vmstat

System configuration: lcpu=4 mem=12288MB ent=2.00

kthr    memory              page              faults              cpu
----- ----------- ------------------------ ------------ -----------------------
 r  b   avm   fre  re  pi  po  fr   sr  cy  in   sy  cs us sy id wa    pc    ec
 2  1 1614644 585722   0   0   1  22  104   0 808 29047 2767 12  8 77  3  0.45  22.3

the colums "avm" and "fre" tell you the total memory and free memery.

a "man vmstat" should get you the gory details.

declaring a priority_queue in c++ with a custom comparator

You should declare a class Compare and overload operator() for it like this:

class Foo
{

};

class Compare
{
public:
    bool operator() (Foo, Foo)
    {
        return true;
    }
};

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
    return 0;
}

Or, if you for some reasons can't make it as class, you could use std::function for it:

class Foo
{

};

bool Compare(Foo, Foo)
{
    return true;
}

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);
    return 0;
}

Difference between clustered and nonclustered index

faster to read than non cluster as data is physically storted in index order we can create only one per table.(cluster index)

quicker for insert and update operation than a cluster index. we can create n number of non cluster index.

Hash table runtime complexity (insert, search and delete)

Some hash tables (cuckoo hashing) have guaranteed O(1) lookup

Get current location of user in Android without using GPS or internet

boolean gps_enabled = false;
boolean network_enabled = false;

LocationManager lm = (LocationManager) mCtx
                .getSystemService(Context.LOCATION_SERVICE);

gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location net_loc = null, gps_loc = null, finalLoc = null;

if (gps_enabled)
    gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
    net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (gps_loc != null && net_loc != null) {

    //smaller the number more accurate result will
    if (gps_loc.getAccuracy() > net_loc.getAccuracy()) 
        finalLoc = net_loc;
    else
        finalLoc = gps_loc;

        // I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)

} else {

    if (gps_loc != null) {
        finalLoc = gps_loc;
    } else if (net_loc != null) {
        finalLoc = net_loc;
    }
}

How do you print in a Go test using the "testing" package?

t.Log() will not show up until after the test is complete, so if you're trying to debug a test that is hanging or performing badly it seems you need to use fmt.

Yes: that was the case up to Go 1.13 (August 2019) included.

And that was followed in golang.org issue 24929

Consider the following (silly) automated tests:

func TestFoo(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(3 * time.Second)
    }
}

func TestBar(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(2 * time.Second)
    }
}

func TestBaz(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(1 * time.Second)
    }
}

If I run go test -v, I get no log output until all of TestFoo is done, then no output until all of TestBar is done, and again no more output until all of TestBaz is done.
This is fine if the tests are working, but if there is some sort of bug, there are a few cases where buffering log output is problematic:

  • When iterating locally, I want to be able to make a change, run my tests, see what's happening in the logs immediately to understand what's going on, hit CTRL+C to shut the test down early if necessary, make another change, re-run the tests, and so on.
    If TestFoo is slow (e.g., it's an integration test), I get no log output until the very end of the test. This significantly slows down iteration.
  • If TestFoo has a bug that causes it to hang and never complete, I'd get no log output whatsoever. In these cases, t.Log and t.Logf are of no use at all.
    This makes debugging very difficult.
  • Moreover, not only do I get no log output, but if the test hangs too long, either the Go test timeout kills the test after 10 minutes, or if I increase that timeout, many CI servers will also kill off tests if there is no log output after a certain amount of time (e.g., 10 minutes in CircleCI).
    So now my tests are killed and I have nothing in the logs to tell me what happened.

But for (possibly) Go 1.14 (Q1 2020): CL 127120

testing: stream log output in verbose mode

The output now is:

=== RUN   TestFoo
=== PAUSE TestFoo
=== RUN   TestBar
=== PAUSE TestBar
=== RUN   TestGaz
=== PAUSE TestGaz
=== CONT  TestFoo
    TestFoo: main_test.go:14: hello from foo
=== CONT  TestGaz
=== CONT  TestBar
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
--- PASS: TestFoo (1.00s)
--- PASS: TestGaz (1.00s)
--- PASS: TestBar (1.00s)
PASS
ok      dummy/streaming-test    1.022s

It is indeed in Go 1.14, as Dave Cheney attests in "go test -v streaming output":

In Go 1.14, go test -v will stream t.Log output as it happens, rather than hoarding it til the end of the test run.

Under Go 1.14 the fmt.Println and t.Log lines are interleaved, rather than waiting for the test to complete, demonstrating that test output is streamed when go test -v is used.

Advantage, according to Dave:

This is a great quality of life improvement for integration style tests that often retry for long periods when the test is failing.
Streaming t.Log output will help Gophers debug those test failures without having to wait until the entire test times out to receive their output.

Function names in C++: Capitalize or not?

There isn't so much a 'correct' way for the language. It's more personal preference or what the standard is for your team. I usually use the myFunction() when I'm doing my own code. Also, a style you didn't mention that you will often see in C++ is my_function() - no caps, underscores instead of spaces.

Really it is just dictated by the code your working in. Or, if it's your own project, your own personal preference then.

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

Here is the actual implementation of both methods ( decompiled using dotPeek)

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool IsNullOrEmpty(string value)
    {
      if (value != null)
        return value.Length == 0;
      else
        return true;
    }

    /// <summary>
    /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
    /// </summary>
    /// 
    /// <returns>
    /// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
    /// </returns>
    /// <param name="value">The string to test.</param>
    public static bool IsNullOrWhiteSpace(string value)
    {
      if (value == null)
        return true;
      for (int index = 0; index < value.Length; ++index)
      {
        if (!char.IsWhiteSpace(value[index]))
          return false;
      }
      return true;
    }

How do I access named capturing groups in a .NET Regex?

You specify the named capture group string by passing it to the indexer of the Groups property of a resulting Match object.

Here is a small example:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        String sample = "hello-world-";
        Regex regex = new Regex("-(?<test>[^-]*)-");

        Match match = regex.Match(sample);

        if (match.Success)
        {
            Console.WriteLine(match.Groups["test"].Value);
        }
    }
}

Better techniques for trimming leading zeros in SQL Server?

Why don't you just cast the value to INTEGER and then back to VARCHAR?

SELECT  CAST(CAST('000000000' AS INTEGER) AS VARCHAR)

--------
       0

PHP Redirect to another page after form submit

If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.

See header for more info.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Otherwise, you can use Javascript to redirect the user.

Just use

window.location = "http://www.google.com/"

Fixed positioning in Mobile Safari

it worked for me:

function changeFooterPosition() {   
  $('.footer-menu').css('top', window.innerHeight + window.scrollY - 44 + "px");
}

$(document).bind('scroll', function() {
  changeFooterPosition();
});

(44 is the height of my bar)

Although the bar only moves at the end of the scroll...

php codeigniter count rows

This is what is did that solved the same problem. I solved it by creating a function that returns the query result thus:

function getUsers(){
$query = $this->db->get('users');
return $query->result();
}

//The above code can go in the user_model or whatever your model is.

This allows me to use one function for the result and number of returned rows.

Use this code below in your contoller where you need the count as well as the result array().

//This gives you the user count using the count function which returns and integer of the exact rows returned from the query.
$this->data['user_count'] = count($this->user_model->getUsers());

//This gives you the returned result array.
$this->data['users'] = $this->user_model->getUsers();

I hope this helps.

Trim spaces from end of a NSString

In Swift

To trim space & newline from both side of the String:

var url: String = "\n   http://example.com/xyz.mp4   "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

Hash function for a string

Java's String implements hashCode like this:

public int hashCode()

Returns a hash code for this string. The hash code for a String object is computed as

     s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) 

So something like this:

int HashTable::hash (string word) {
    int result = 0;
    for(size_t i = 0; i < word.length(); ++i) {
        result += word[i] * pow(31, i);
    }
    return result;
}

Replacing NULL with 0 in a SQL server query

If you are using Presto, AWS Athena etc, there is no ISNULL() function. Instead, use:

SELECT COALESCE(myColumn, 0 ) FROM myTable

Loading basic HTML in Node.js

It's just really simple if you use pipe. The following is the server.js code snippet.

_x000D_
_x000D_
var http = require('http');_x000D_
var fs = require('fs');_x000D_
_x000D_
function onRequest(req, res){_x000D_
_x000D_
    console.log("USER MADE A REQUEST. " +req.url);_x000D_
    res.writeHead(200, {'Content-Type': 'text/html'});_x000D_
    var readStream = fs.createReadStream(__dirname + '/index.html','utf8'); _x000D_
    _x000D_
/*include your html file and directory name instead of <<__dirname + '/index.html'>>*/_x000D_
_x000D_
    readStream.pipe(res);_x000D_
_x000D_
}_x000D_
_x000D_
http.createServer(onRequest).listen(7000);_x000D_
console.log('Web Server is running...');
_x000D_
_x000D_
_x000D_

How to permanently add a private key with ssh-add on Ubuntu?

Adding the following lines in "~/.bashrc" solved the issue for me. I'm using Ubuntu 14.04 desktop.

eval `gnome-keyring-daemon --start`
USERNAME="reynold"
export SSH_AUTH_SOCK="$(ls /run/user/$(id -u $USERNAME)/keyring*/ssh|head -1)"
export SSH_AGENT_PID="$(pgrep gnome-keyring)"

How to change the color of an image on hover

Ok, try this:

Get the image with the transparent circle - http://i39.tinypic.com/15s97vd.png Put that image in a html element and change that element's background color via css. This way you get the logo with the circle in the color defined in the stylesheet.

The html

<div class="badassColorChangingLogo">
    <img src="http://i39.tinypic.com/15s97vd.png" /> 
    Or download the image and change the path to the downloaded image in your machine
</div>

The css

div.badassColorChangingLogo{
    background-color:white;
}
div.badassColorChangingLogo:hover{
    background-color:blue;
}

Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.

Change a Django form field to a hidden field

an option that worked for me, define the field in the original form as:

forms.CharField(widget = forms.HiddenInput(), required = False)

then when you override it in the new Class it will keep it's place.

Make iframe automatically adjust height according to the contents without using scrollbar?

Avoid inline JavaScript; you can use a class:

<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>

And reference it with jQuery:

$('.iframe-full-height').on('load', function(){
    this.style.height=this.contentDocument.body.scrollHeight +'px';
});

Custom CSS for <audio> tag?

I discovered quite by accident (I was working with images at the time) that the box-shadow, border-radius and transitions work quite well with the bog-standard audio tag player. I have this working in Chrome, FF and Opera.

audio:hover, audio:focus, audio:active
{
-webkit-box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
-moz-box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
-webkit-transform: scale(1.05);
-moz-transform: scale(1.05);
transform: scale(1.05);
}

with:-

audio
{
-webkit-transition:all 0.5s linear;
-moz-transition:all 0.5s linear;
-o-transition:all 0.5s linear;
transition:all 0.5s linear;
-moz-box-shadow: 2px 2px 4px 0px #006773;
-webkit-box-shadow:  2px 2px 4px 0px #006773;
box-shadow: 2px 2px 4px 0px #006773;
-moz-border-radius:7px 7px 7px 7px ;
-webkit-border-radius:7px 7px 7px 7px ;
border-radius:7px 7px 7px 7px ;
}

I grant you it only "tarts it up a bit", but it makes them a sight more exciting than what's already there, and without doing MAJOR fannying about in JS.

NOT available in IE, unfortunately (not yet supporting the transition bit), but it seems to degrade nicely.

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

better way to drop nan rows in pandas

bool_series=pd.notnull(dat["x"])
dat=dat[bool_series]

Transparent background on winforms?

Should it have anything to do with "opacity" of the form / its background ? Did you try opacity = 0

Also see if this CP article helps:

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

$resource("../rest/api"}).get();

returns an object.

$resource("../rest/api").query();

returns an array.

You must use :

return $resource('../rest/api.php?method=getTask&q=*').query();

Restarting cron after changing crontab file?

I had a similar issue on 16.04 VPS Digital Ocean. If you are changing crontabs, make sure to run

sudo service cron restart 

Using jQuery To Get Size of Viewport

function showViewPortSize(display) {
    if (display) {
        var height = window.innerHeight;
        var width = window.innerWidth;
        jQuery('body')
            .prepend('<div id="viewportsize" style="z-index:9999;position:fixed;bottom:0px;left:0px;color:#fff;background:#000;padding:10px">Height: ' + height + '<br>Width: ' + width + '</div>');
        jQuery(window)
            .resize(function() {
                height = window.innerHeight;
                width = window.innerWidth;
                jQuery('#viewportsize')
                    .html('Height: ' + height + '<br>Width: ' + width);
            });
    }
}
$(document)
    .ready(function() {
        showViewPortSize(true);
    });

Is there a way to 'uniq' by column?

awk -F"," '!_[$1]++' file
  • -F sets the field separator.
  • $1 is the first field.
  • _[val] looks up val in the hash _(a regular variable).
  • ++ increment, and return old value.
  • ! returns logical not.
  • there is an implicit print at the end.

How can I build XML in C#?

I think this resource should suffice for a moderate XML save/load: Read/Write XML using C#.

My task was to store musical notation. I choose XML, because I guess .NET has matured enough to allow easy solution for the task. I was right :)

This is my song file prototype:

<music judul="Kupu-Kupu yang Lucu" pengarang="Ibu Sud" tempo="120" birama="4/4" nadadasar="1=F" biramapembilang="4" biramapenyebut="4">
    <not angka="1" oktaf="0" naikturun="" nilai="1"/>
    <not angka="2" oktaf="0" naikturun="" nilai="0.5"/>
    <not angka="5" oktaf="1" naikturun="/" nilai="0.25"/>
    <not angka="2" oktaf="0" naikturun="\" nilai="0.125"/>
    <not angka="1" oktaf="0" naikturun="" nilai="0.0625"/>
</music>

That can be solved quite easily:

For Save to File:

 private void saveToolStripMenuItem_Click(object sender, EventArgs e)
 {
     saveFileDialog1.Title = "Save Song File";
     saveFileDialog1.Filter = "Song Files|*.xsong";
     if (saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
         XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);
         w.WriteStartDocument();
         w.WriteStartElement("music");
         w.WriteAttributeString("judul", Program.music.getTitle());
         w.WriteAttributeString("pengarang", Program.music.getAuthor());
         w.WriteAttributeString("tempo", Program.music.getTempo()+"");
         w.WriteAttributeString("birama", Program.music.getBirama());
         w.WriteAttributeString("nadadasar", Program.music.getNadaDasar());
         w.WriteAttributeString("biramapembilang", Program.music.getBiramaPembilang()+"");
         w.WriteAttributeString("biramapenyebut", Program.music.getBiramaPenyebut()+"");

         for (int i = 0; i < listNotasi.Count; i++)
         {
             CNot not = listNotasi[i];
             w.WriteStartElement("not");
             w.WriteAttributeString("angka", not.getNot() + "");
             w.WriteAttributeString("oktaf", not.getOktaf() + "");
             String naikturun="";
             if(not.isTurunSetengah())naikturun="\\";
             else if(not.isNaikSetengah())naikturun="/";
             w.WriteAttributeString("naikturun",naikturun);
             w.WriteAttributeString("nilai", not.getNilaiNot()+"");
             w.WriteEndElement();
         }
         w.WriteEndElement();

         w.Flush();
         fs.Close();
     }

 }

For load file:

openFileDialog1.Title = "Open Song File";
openFileDialog1.Filter = "Song Files|*.xsong";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
    XmlTextReader r = new XmlTextReader(fs);

    while (r.Read())
    {
        if (r.NodeType == XmlNodeType.Element)
        {
            if (r.Name.ToLower().Equals("music"))
            {
                Program.music = new CMusic(r.GetAttribute("judul"),
                    r.GetAttribute("pengarang"),
                    r.GetAttribute("birama"),
                    Convert.ToInt32(r.GetAttribute("tempo")),
                    r.GetAttribute("nadadasar"),
                    Convert.ToInt32(r.GetAttribute("biramapembilang")),
                    Convert.ToInt32(r.GetAttribute("biramapenyebut")));
            }
            else
                if (r.Name.ToLower().Equals("not"))
                {
                    CNot not = new CNot(Convert.ToInt32(r.GetAttribute("angka")), Convert.ToInt32(r.GetAttribute("oktaf")));
                    if (r.GetAttribute("naikturun").Equals("/"))
                    {
                        not.setNaikSetengah();
                    }
                    else if (r.GetAttribute("naikturun").Equals("\\"))
                    {
                        not.setTurunSetengah();
                    }
                    not.setNilaiNot(Convert.ToSingle(r.GetAttribute("nilai")));
                    listNotasi.Add(not);
                }
        }
        else
            if (r.NodeType == XmlNodeType.Text)
            {
                Console.WriteLine("\tVALUE: " + r.Value);
            }
    }
}

}
}

JS: iterating over result of getElementsByClassName using Array.forEach

This is the safer way:

var elements = document.getElementsByClassName("myclass");
for (var i = 0; i < elements.length; i++) myFunction(elements[i]);

Finding a substring within a list in Python

Use a simple for loop:

seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'

for text in seq:
    if sub in text:
        print(text)

yields

abc123

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

C++ Vector of pointers

As far as I understand, you create a Movie class:

class Movie
{
private:
  std::string _title;
  std::string _director;
  int         _year;
  int         _rating;
  std::vector<std::string> actors;
};

and having such class, you create a vector instance:

std::vector<Movie*> movies;

so, you can add any movie to your movies collection. Since you are creating a vector of pointers to movies, do not forget to free the resources allocated by your movie instances OR you could use some smart pointer to deallocate the movies automatically:

std::vector<shared_ptr<Movie>> movies;

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

Adding multiple class using ng-class

To apply different classes when different expressions evaluate to true:

<div ng-class="{class1 : expression1, class2 : expression2}">
    Hello World!
</div>

To apply multiple classes when an expression holds true:

<!-- notice expression1 used twice -->
<div ng-class="{class1 : expression1, class2 : expression1}">
    Hello World!
</div>

or quite simply:

<div ng-class="{'class1 class2' : expression1}">
    Hello World!
</div>

Notice the single quotes surrounding css classes.

How to throw RuntimeException ("cannot find symbol")

you will have to instantiate it before you throw it

throw new RuntimeException(arg0) 

PS: Intrestingly enough the Netbeans IDE should have already pointed out that compile time error

Java Multithreading concept and join() method

You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances.

However, you can use join() to wait for a thread to complete its work.

For example, in your case

ob1.t.join();

This statement will not return until thread t has finished running.

Try this,

class Demo {
   Thread t = new Thread(
                 new Runnable() {
                     public void run () {
                         //do something
                     }
                  }
    );
    Thread t1 = new Thread(
                 new Runnable() {
                     public void run () {
                         //do something
                     }
                  }
    );
    t.start(); // Line 15
    t.join();  // Line 16
    t1.start();
}

In the above example, your main thread is executing. When it encounters line 15, thread t is available at thread scheduler. As soon as main thread comes to line 16, it will wait for thread t to finish.

NOTE that t.join did not do anything to thread t or to thread t1. It only affected the thread that called it (i.e., the main() thread).

Edited:

t.join(); needs to be inside the try block because it throws the InterruptedException exception, otherwise you will get an error at compile time. So, it should be:

try{
    t.join();
}catch(InterruptedException e){
    // ...
}

What's HTML character code 8203?

If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.

See my article on mitigating fingerprinting if you're interested in learning more.

Boolean Field in Oracle

A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number type):

ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))
);

This creates a new column in my_table_name called my_new_boolean_column with default values of 0. The column will not accept NULL values and restricts the accepted values to either 0 or 1.

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Get the data received in a Flask request

@app.route('/addData', methods=['POST'])
def add_data():
     data_in = mongo.db.Data
     id = request.values.get("id")
     name = request.values.get("name")
     newuser = {'id' : id, 'name' : name}
     if voter.find({'id' : id, 'name' : name}).count() > 0:
            return "Data Exists"
     else:
            data_in.insert(newuser)
            return "Data Added"

How to create a density plot in matplotlib?

Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top!

Today, a much easier way to do this is to use seaborn, a package that provides many convenient plotting functions and good style management.

import numpy as np
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.set_style('whitegrid')
sns.kdeplot(np.array(data), bw=0.5)

enter image description here

How to Code Double Quotes via HTML Codes

Google recommend that you don't use any of them, source.

There is no need to use entity references like &mdash, &rdquo, or &#x263a, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.

Is there a reason you can't simply use "?

What is "with (nolock)" in SQL Server?

The question is what is worse:

  • a deadlock, or
  • a wrong value?

For financial databases, deadlocks are far worse than wrong values. I know that sounds backwards, but hear me out. The traditional example of DB transactions is you update two rows, subtracting from one and adding to another. That is wrong.

In a financial database you use business transactions. That means adding one row to each account. It is of utmost importance that these transactions complete and the rows are successfully written.

Getting the account balance temporarily wrong isn't a big deal, that is what the end of day reconciliation is for. And an overdraft from an account is far more likely to occur because two ATMs are being used at once than because of a uncommitted read from a database.

That said, SQL Server 2005 fixed most of the bugs that made NOLOCK necessary. So unless you are using SQL Server 2000 or earlier, you shouldn't need it.

Further Reading
Row-Level Versioning

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

Simple Deadlock Examples

One of the simple deadlock example I have come across.

public class SimpleDeadLock {
   public static Object l1 = new Object();
   public static Object l2 = new Object();
   private int index;
   public static void main(String[] a) {
      Thread t1 = new Thread1();
      Thread t2 = new Thread2();
      t1.start();
      t2.start();
   }
   private static class Thread1 extends Thread {
      public void run() {
         synchronized (l1) {
            System.out.println("Thread 1: Holding lock 1...");
            try { Thread.sleep(10); }
            catch (InterruptedException e) {}
            System.out.println("Thread 1: Waiting for lock 2...");
            synchronized (l2) {
               System.out.println("Thread 2: Holding lock 1 & 2...");
            }
         }
      }
   }
   private static class Thread2 extends Thread {
      public void run() {
         synchronized (l2) {
            System.out.println("Thread 2: Holding lock 2...");
            try { Thread.sleep(10); }
            catch (InterruptedException e) {}
            System.out.println("Thread 2: Waiting for lock 1...");
            synchronized (l1) {
               System.out.println("Thread 2: Holding lock 2 & 1...");
            }
         }
      }
   }
}

How to detect escape key press with pure JS or jQuery?

pure JS (no JQuery)

document.addEventListener('keydown', function(e) {
    if(e.keyCode == 27){
      //add your code here
    }
});

How can I center text (horizontally and vertically) inside a div block?

_x000D_
_x000D_
div {_x000D_
  height: 90px;_x000D_
  line-height: 90px;_x000D_
  text-align: center;_x000D_
  border: 2px dashed #f69c55;_x000D_
}
_x000D_
<div>_x000D_
  Hello, World!!_x000D_
</div>
_x000D_
_x000D_
_x000D_

Open directory dialog

I'd suggest, to add in the nugget package:

  Install-Package OpenDialog

Then the way to used it is:

    Gat.Controls.OpenDialogView openDialog = new Gat.Controls.OpenDialogView();
    Gat.Controls.OpenDialogViewModel vm = (Gat.Controls.OpenDialogViewModel)openDialog.DataContext;
    vm.IsDirectoryChooser = true;
    vm.Show();

    WPFLabel.Text = vm.SelectedFilePath.ToString();

Here's the documentation: http://opendialog.codeplex.com/documentation

Works for Files, files with filter, folders, etc

Mergesort with Python

here is another solution

class MergeSort(object):
    def _merge(self,left, right):
        nl = len(left)
        nr = len(right)
        result = [0]*(nl+nr)
        i=0
        j=0
        for k in range(len(result)):
            if nl>i and nr>j:
                if left[i] <= right[j]:
                    result[k]=left[i]
                    i+=1
                else:
                    result[k]=right[j]
                    j+=1
            elif nl==i:
                result[k] = right[j]
                j+=1
            else: #nr>j:
                result[k] = left[i]
                i+=1
        return result

    def sort(self,arr):
        n = len(arr)
        if n<=1:
            return arr 
        left = self.sort(arr[:n/2])
        right = self.sort(arr[n/2:] )
        return self._merge(left, right)
def main():
    import random
    a= range(100000)
    random.shuffle(a)
    mr_clss = MergeSort()
    result = mr_clss.sort(a)
    #print result

if __name__ == '__main__':
    main()

and here is run time for list with 100000 elements:

real    0m1.073s
user    0m1.053s
sys         0m0.017s

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(
                                REPLACE(
                                    REPLACE(
                                        REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                    REPLACE(
                                                        REPLACE(
                                                            REPLACE(
                                                                REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                    REPLACE(
                                                                                                        REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

I do not want to inherit the child opacity from the parent in CSS

The question didn't defined if the background is a color or an image but since @Blowski have already answered for coloured backgrounds, there's a hack for images below:

background: linear-gradient(rgba(0,0,0,.6), rgba(0,0,0,.6)), url('image.jpg');

This way you can manipulate the color of your opacity and even add nice gradient effects.

_x000D_
_x000D_
.wrapper {_x000D_
  width: 630px;_x000D_
  height: 420px;_x000D_
  display: table;_x000D_
  background: linear-gradient(_x000D_
    rgba(0,0,0,.8), _x000D_
    rgba(0,0,0,.8)), _x000D_
    url('http://cdn.moviestillsdb.com/sm/35bc3c6a2b791425de6caf8b9391026e/rambo-iii.jpg');_x000D_
 }_x000D_
_x000D_
h1 {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  text-align: center;_x000D_
  color: #fff;_x000D_
  }
_x000D_
<div class="wrapper">_x000D_
<h1>Question 5770341</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Move UIView up when the keyboard appears in iOS

Based on Daniel Krom's solution. This is version in swift 3.0. Works great with AutoLayout, and moves whole view when keyboard appears.

extension UIView {

    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func unbindFromKeyboard(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc
    func keyboardWillChange(notification: NSNotification) {

        guard let userInfo = notification.userInfo else { return }

        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        })
    }  
}

How to use it: Add bindToKeyboard function in viewDidLoad like:

override func viewDidLoad() {
    super.viewDidLoad()

    view.bindToKeyboard()
}

And add unbindFromKeyboard function in deinit:

deinit {
    view.unbindFromKeyboard()
}

How to access the value of a promise?

Maybe this small Typescript code example will help.

private getAccount(id: Id) : Account {
    let account = Account.empty();
    this.repository.get(id)
        .then(res => account = res)
        .catch(e => Notices.results(e));
    return account;
}

Here the repository.get(id) returns a Promise<Account>. I assign it to the variable account within the then statement.

Selenium Webdriver: Entering text into text field

Use this code.

driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");

How to check whether a string is a valid HTTP URL?

After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s).

Selenium IDE - Command to wait for 5 seconds

Use the pause command and enter the number of milliseconds in the Target field.

Set speed to fastest (Actions --> Fastest), otherwise it won't work.

Vector of structs initialization

Create vector, push_back element, then modify it as so:

struct subject {
    string name;
    int marks;
    int credits;
};


int main() {
    vector<subject> sub;

    //Push back new subject created with default constructor.
    sub.push_back(subject());

    //Vector now has 1 element @ index 0, so modify it.
    sub[0].name = "english";

    //Add a new element if you want another:
    sub.push_back(subject());

    //Modify its name and marks.
    sub[1].name = "math";
    sub[1].marks = 90;
}

You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

How can I delete a service in Windows?

Here is a vbs script that was passed down to me:

Set servicelist = GetObject("winmgmts:").InstancesOf ("Win32_Service")

for each service in servicelist
    sname = lcase(service.name)
    If sname = "NameOfMyService" Then 
        msgbox(sname)
        service.delete ' the internal name of your service
    end if
next

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

$('.myDropdown').chosen({
    //Here you can change the value of the maximum allowed options
    max_selected_options: 1
});

Using multiple delimiters in awk

For a field separator of any number 2 through 5 or letter a or # or a space, where the separating character must be repeated at least 2 times and not more than 6 times, for example:

awk -F'[2-5a# ]{2,6}' ...

I am sure variations of this exist using ( ) and parameters

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.

When to use RDLC over RDL reports?

if you want to use report in asp.net then use .rdl if you want to use /view in report builder / report server then use .rdlc just by converting format manually it works

Adding elements to an xml file in C#

I've used XDocument.Root.Add to add elements. Root returns XElement which has an Add function for additional XElements

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Insted of

drawer.setDrawerListener(toggle);

You can use

drawer.addDrawerListener(toggle);

When to use AtomicReference in Java?

Here's a very simple use case and has nothing to do with thread safety.

To share an object between lambda invocations, the AtomicReference is an option:

public void doSomethingUsingLambdas() {

    AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();

    soSomethingThatTakesALambda(() -> {
        yourObjectRef.set(youObject);
    });

    soSomethingElseThatTakesALambda(() -> {
        YourObject yourObject = yourObjectRef.get();
    });
}

I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference is an option.

In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.

How can I indent multiple lines in Xcode?

In Xcode 4.2 auto-indenting is pretty good. You can now indent a selection of code by pressing the Tab key. I find that Xcode generally formats code really well automatically, and you rarely have to move things around yourself. I find it faster to select a piece of code, right-click and choose Structure -> Re-indent if some code looks messy.

ng-change get new value and original value

With an angular {{expression}} you can add the old user or user.id value to the ng-change attribute as a literal string:

<select ng-change="updateValue(user, '{{user.id}}')" 
        ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>

On ngChange, the 1st argument to updateValue will be the new user value, the 2nd argument will be the literal that was formed when the select-tag was last updated by angular, with the old user.id value.

What is the difference between `new Object()` and object literal notation?

I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().

> [1, 2, 3].map(v => {n: v});
[ undefined, undefined, undefined ]
> [1, 2, 3].map(v => new Object({n: v}));
[ { n: 1 }, { n: 2 }, { n: 3 } ]

This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.

If you add another property to the object it will finally throw an error.

$ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
[1, 2, 3].map(v => {n: v, m: v+1});
                           ^

SyntaxError: Unexpected token :

Reading in a JSON File Using Swift

Swift 4 using Decodable

struct ResponseData: Decodable {
    var person: [Person]
}
struct Person : Decodable {
    var name: String
    var age: String
    var employed: String
}

func loadJson(filename fileName: String) -> [Person]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(ResponseData.self, from: data)
            return jsonData.person
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

Swift 3

func loadJson(filename fileName: String) -> [String: AnyObject]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            if let dictionary = object as? [String: AnyObject] {
                return dictionary
            }
        } catch {
            print("Error!! Unable to parse  \(fileName).json")
        }
    }
    return nil
}

Python, how to check if a result set is empty?

if you're connecting to a postgres database, the following works:

result = cursor.execute(query)

if result.returns_rows:
    # we got rows!
    return [{k:v for k,v in zip(result.keys(), r)} for r in result.rows]
else:
    return None

Remove background drawable programmatically in Android

This work for me:

yourview.setBackground(null);

What is the difference between mocking and spying when using Mockito?

Spy can be useful when you want to create unit tests for legacy code.

I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.

If you have something like this code:

public void transfer(  DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService, 
             double amount, String fromAccount, String toAccount){
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some, legacy code, dependency is in the code like this:

    public void transfer(String fromAccount, String toAccount, double amount){

        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }

Then you can use the spy the inject the dependency like this:

DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target).proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target).proxyWithdrawMoneyServiceCreator();

More detail in the link above.

TypeScript - Append HTML to container element in Angular 2

When working with Angular the recent update to Angular 8 introduced that a static property inside @ViewChild() is required as stated here and here. Then your code would require this small change:

@ViewChild('one') d1:ElementRef;

into

// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;

OR

// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

Laravel form html with PUT method for PUT routes

in your view blade change to

{{ Form::open(['action' => 'postcontroller@edit', 'method' => 'PUT', 'class' = 'your class here']) }}

<div>
{{ Form::textarea('textareanamehere', 'default value here', ['placeholder' => 'your place holder here', 'class' => 'your class here']) }}
</div>

<div>
{{ Form::submit('Update', ['class' => 'btn class here'])}}
</div>

{{ Form::close() }}

actually you can use raw form like your question. but i dont recomended it. dan itulah salah satu alasan agan belajar framework, simple, dan cepat. so kenapa pake raw form kalo ada yang lebih mudah. hehe. proud to be indonesian.

reference: Laravel Blade Form

Escape double quotes in a string

One solution, is to add support to the csharp language so that "" isn't the only scheme used for strings.

For another string terminator to the C# language - I'm a fan of backtick in ES6.

string test = `He said to me, "Hello World". How are you?`;

But also, the doubling idea in Markdown might be better:

string test = ""He said to me, "Hello World". How are you?"";

The code does not work at the date of this post. This post is a solution where the visitors to this Q&A jump onto this csharplank ticket for C# and upvote it - https://github.com/dotnet/csharplang/discussions/3917

MySQL DISTINCT on a GROUP_CONCAT()

SELECT
  GROUP_CONCAT(DISTINCT (category))
FROM (
  SELECT
    SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
  FROM
    numbers INNER JOIN tableName
    ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
  ) s;   

This will return distinct values like: test1,test2,test4,test3

"Comparison method violates its general contract!"

In my case, it was an infinite sort. That is, at first the line moved up according to the condition, and then the same line moved down to the same place. I added one more condition at the end that unambiguously established the order of the lines.

Create Git branch with current changes

To add new changes to a new branch and push to remote:

git branch branch/name
git checkout branch/name
git push origin branch/name

Often times I forget to add the origin part to push and get confused why I don't see the new branch/commit in bitbucket

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

Call Javascript function from URL/address bar

you can execute javascript from url via events Ex: www.something.com/home/save?id=12<body onload="alert(1)"></body>

does work if params in url are there.

How to delete the first row of a dataframe in R?

dat <- dat[-1, ] worked but it killed my dataframe, changing it into another type. Had to instead use dat <- data.frame(dat[-1, ]) but this is possibly a special case as this dataframe initially had only one column.

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Add URL link in CSS Background Image?

You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:

<a href="whatever.html"><li id="header"></li></a>

SQL Server 2008 can't login with newly created user

If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start->Programs->Microsoft SQL Server -> Configuration tools -> SQL Server configuration manager -> Restart Server.

It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

This is just off the top of my head, but you could do an onClick event for each radio button, give them all different IDs, and then make a for loop in the event to go through each radio button in the group and find which is was checked by looking at the 'checked' attribute. The id of the checked one would be stored as a variable, but you might want to use a temp variable first to make sure that the value of that variable changed, since the click event would fire whether or not a new radio button was checked.

Java : Cannot format given Object as a Date

public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.

Numpy Resize/Rescale Image

import cv2
import numpy as np

image_read = cv2.imread('filename.jpg',0) 
original_image = np.asarray(image_read)
width , height = 452,452
resize_image = np.zeros(shape=(width,height))

for W in range(width):
    for H in range(height):
        new_width = int( W * original_image.shape[0] / width )
        new_height = int( H * original_image.shape[1] / height )
        resize_image[W][H] = original_image[new_width][new_height]

print("Resized image size : " , resize_image.shape)

cv2.imshow(resize_image)
cv2.waitKey(0)

Script to get the HTTP status code of a list of urls?

I found a tool "webchk” written in Python. Returns a status code for a list of urls. https://pypi.org/project/webchk/

Output looks like this:

? webchk -i ./dxieu.txt | grep '200'
http://salesforce-case-status.dxi.eu/login ... 200 OK (0.108)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.389)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.401)

Hope that helps!

Returning multiple objects in an R function

You could use for() with assign() to create many objects. See the example from assign():

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
    nam <- paste("r", i, sep = ".")
    assign(nam, 1:i)

Looking the new objects

ls(pattern = "^r..$")

Check if image exists on server using JavaScript?

You can do this with your axios by setting relative path to the corresponding images folder. I have done this for getting a json file. You can try the same method for an image file, you may refer these examples

If you have already set an axios instance with baseurl as a server in different domain, you will have to use the full path of the static file server where you deploy the web application.

  axios.get('http://localhost:3000/assets/samplepic.png').then((response) => {
            console.log(response)
        }).catch((error) => {
            console.log(error)
        })

If the image is found the response will be 200 and if not, it will be 404.

Also, if the image file is present in assets folder inside src, you can do a require, get the path and do the above call with that path.

var SampleImagePath = require('./assets/samplepic.png');
axios.get(SampleImagePath).then(...)

Find and replace specific text characters across a document with JS

ECMAScript 2015+ approach

Pitfalls when solving this task

This seems like an easy task, but you have to take care of several things:

  • Simply replacing the entire HTML kills all DOM functionality, like event listeners
  • Replacing the HTML may also replace <script> or <style> contents, or HTML tags or attributes, which is not always desired
  • Changing the HTML may result in an attack
  • You may want to replace attributes like title and alt (in a controlled manner) as well

Guarding against attacks generally can’t be solved by using the approaches below. E.g. if a fetch call reads a URL from somewhere on the page, then sends a request to that URL, the functions below won’t stop that, since this scenario is inherently unsafe.

Replacing the text contents of all elements

This basically selects all elements that contain normal text, goes through their child nodes — among those are also text nodes —, seeks those text nodes out and replaces their contents.

You can optionally specify a different root target, e.g. replaceOnDocument(/€/g, "$", { target: someElement });; by default, the <body> is chosen.

const replaceOnDocument = (pattern, string, {target = document.body} = {}) => {
  // Handle `string` — see the last section
  [
    target,
    ...target.querySelectorAll("*:not(script):not(noscript):not(style)")
  ].forEach(({childNodes: [...nodes]}) => nodes
    .filter(({nodeType}) => nodeType === document.TEXT_NODE)
    .forEach((textNode) => textNode.textContent = textNode.textContent.replace(pattern, string)));
};

replaceOnDocument(/€/g, "$");

Replacing text nodes, element attributes and properties

Now, this is a little more complex: you need to check three cases: whether a node is a text node, whether it’s an element and its attribute should be replaced, or whether it’s an element and its property should be replaced. A replacer object provides methods for text nodes and for elements.

Before replacing attributes and properties, the replacer needs to check whether the element has a matching attribute; otherwise new attributes get created, undesirably. It also needs to check whether the targeted property is a string, since only strings can be replaced, or whether the matching property to the targeted attribute is not a function, since this may lead to an attack.

In the example below, you can see how to use the extended features: in the optional third argument, you may add an attrs property and a props property, which is an iterable (e.g. an array) each, for the attributes to be replaced and the properties to be replaced, respectively.

You’ll also notice that this snippet uses flatMap. If that’s not supported, use a polyfill or replace it by the reduceconcat, or mapreduceconcat construct, as seen in the linked documentation.

const replaceOnDocument = (() => {
    const replacer = {
      [document.TEXT_NODE](node, pattern, string){
        node.textContent = node.textContent.replace(pattern, string);
      },
      [document.ELEMENT_NODE](node, pattern, string, {attrs, props} = {}){
        attrs.forEach((attr) => {
          if(typeof node[attr] !== "function" && node.hasAttribute(attr)){
            node.setAttribute(attr, node.getAttribute(attr).replace(pattern, string));
          }
        });
        props.forEach((prop) => {
          if(typeof node[prop] === "string" && node.hasAttribute(prop)){
            node[prop] = node[prop].replace(pattern, string);
          }
        });
      }
    };

    return (pattern, string, {target = document.body, attrs: [...attrs] = [], props: [...props] = []} = {}) => {
      // Handle `string` — see the last section
      [
        target,
        ...[
          target,
          ...target.querySelectorAll("*:not(script):not(noscript):not(style)")
        ].flatMap(({childNodes: [...nodes]}) => nodes)
      ].filter(({nodeType}) => replacer.hasOwnProperty(nodeType))
        .forEach((node) => replacer[node.nodeType](node, pattern, string, {
          attrs,
          props
        }));
    };
})();

replaceOnDocument(/€/g, "$", {
  attrs: [
    "title",
    "alt",
    "onerror" // This will be ignored
  ],
  props: [
    "value" // Changing an `<input>`’s `value` attribute won’t change its current value, so the property needs to be accessed here
  ]
});

Replacing with HTML entities

If you need to make it work with HTML entities like &shy;, the above approaches will just literally produce the string &shy;, since that’s an HTML entity and will only work when assigning .innerHTML or using related methods.

So let’s solve it by passing the input string to something that accepts an HTML string: a new, temporary HTMLDocument. This is created by the DOMParser’s parseFromString method; in the end we read its documentElement’s textContent:

string = new DOMParser().parseFromString(string, "text/html").documentElement.textContent;

If you want to use this, choose one of the approaches above, depending on whether or not you want to replace HTML attributes and DOM properties in addition to text; then simply replace the comment // Handle `string` — see the last section by the above line.

Now you can use replaceOnDocument(/Güterzug/g, "G&uuml;ter&shy;zug");.

NB: If you don’t use the string handling code, you may also remove the { } around the arrow function body.

Note that this parses HTML entities but still disallows inserting actual HTML tags, since we’re reading only the textContent. This is also safe against most cases of : since we’re using parseFromString and the page’s document isn’t affected, no <script> gets downloaded and no onerror handler gets executed.

You should also consider using \xAD instead of &shy; directly in your JavaScript string, if it turns out to be simpler.

How to use conditional breakpoint in Eclipse?

1. Create a class

public class Test {

 public static void main(String[] args) {
    // TODO Auto-generated method stub
     String s[] = {"app","amm","abb","akk","all"};
     doForAllTabs(s);

 }
 public static void doForAllTabs(String[] tablist){
     for(int i = 0; i<tablist.length;i++){
         System.out.println(tablist[i]);
    }
  }
}

2. Right click on left side of System.out.println(tablist[i]); in Eclipse --> select Toggle Breakpoint

3. Right click on toggle point --> select Breakpoint properties

4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK

5. Right click on class --> Debug As --> Java Application

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

Using atan2 to find angle between two vectors

angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2)))

+pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb))

+sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya)))

-sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))

xb,yb and xa,ya are the coordinates of the two vectors

How to use the CancellationToken property?

You can use ThrowIfCancellationRequested without handling the exception!

The use of ThrowIfCancellationRequested is meant to be used from within a Task (not a Thread). When used within a Task, you do not have to handle the exception yourself (and get the Unhandled Exception error). It will result in leaving the Task, and the Task.IsCancelled property will be True. No exception handling needed.

In your specific case, change the Thread to a Task.

Task t = null;
try
{
    t = Task.Run(() => Work(cancelSource.Token), cancelSource.Token);
}

if (t.IsCancelled)
{
    Console.WriteLine("Canceled!");
}

PHP: Return all dates between two dates in an array

function createDateRangeArray($start, $end) {
// Modified by JJ Geewax

$range = array();

if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);

if ($start > $end) return createDateRangeArray($end, $start);

do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start < $end);

return $range;
} 

Source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

Rails get index of "each" loop

<% @images.each_with_index do |page, index| %>

<% end %>

How do you check in python whether a string contains only numbers?

You can use try catch block here:

s="1234"
try:
    num=int(s)
    print "S contains only digits"
except:
    print "S doesn't contain digits ONLY"

Always pass weak reference of self into block in ARC?

You don't have to always use a weak reference. If your block is not retained, but executed and then discarded, you can capture self strongly, as it will not create a retain cycle. In some cases, you even want the block to hold the self until the completion of the block so it does not deallocate prematurely. If, however, you capture the block strongly, and inside capture self, it will create a retain cycle.

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

I had to write this in the Immediate window :3

(((exception as System.Data.Entity.Validation.DbEntityValidationException).EntityValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbEntityValidationResult>)[0].ValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbValidationError>)[0]

in order to get deep into the exact error !

SQL update fields of one table from fields of another one

Try Following

Update A a, B b, SET a.column1=b.column1 where b.id=1

EDITED:- Update more than one column

Update A a, B b, SET a.column1=b.column1, a.column2=b.column2 where b.id=1

Resize image in PHP

This resource(broken link) is also worth considering - some very tidy code that uses GD. However, I modified their final code snippet to create this function which meets the OPs requirements...

function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
    
    $target_dir = "your-uploaded-images-folder/";
    $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
    
    $image = new SimpleImage();
    $image->load($_FILES[$html_element_name]['tmp_name']);
    $image->resize($new_img_width, $new_img_height);
    $image->save($target_file);
    return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
    
}

You will also need to include this PHP file...

<?php
 
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
 
class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      
 
}
?>

CodeIgniter 500 Internal Server Error

Whenever I run CodeIgniter in a sub directory I set the RewriteBase to it. Try setting it as /myproj/ instead of /.

How to create an exit message

I got here searching for a way to execute some code whenever the program ends.
Found this:

Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call

Called multiple times will register multiple handlers.

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Adjusting HttpWebRequest Connection Timeout in C#

Something I found later which helped, is the .ReadWriteTimeout property. This, in addition to the .Timeout property seemed to finally cut down on the time threads would spend trying to download from a problematic server. The default time for .ReadWriteTimeout is 5 minutes, which for my application was far too long.

So, it seems to me:

.Timeout = time spent trying to establish a connection (not including lookup time) .ReadWriteTimeout = time spent trying to read or write data after connection established

More info: HttpWebRequest.ReadWriteTimeout Property

Edit:

Per @KyleM's comment, the Timeout property is for the entire connection attempt, and reading up on it at MSDN shows:

Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned within the time-out period, the request throws a WebException with the Status property set to WebExceptionStatus.Timeout.

(Emphasis mine.)

What is the difference between function and procedure in PL/SQL?

A procedure does not have a return value, whereas a function has.

Example:

CREATE OR REPLACE PROCEDURE my_proc
   (p_name IN VARCHAR2 := 'John') as begin ... end

CREATE OR REPLACE FUNCTION my_func
   (p_name IN VARCHAR2 := 'John') return varchar2 as begin ... end

Notice how the function has a return clause between the parameter list and the "as" keyword. This means that it is expected to have the last statement inside the body of the function read something like:

return(my_varchar2_local_variable);

Where my_varchar2_local_variable is some varchar2 that should be returned by that function.

How to import multiple csv files in a single load?

Note that you can use other tricks like :

-- One or more wildcard:
       .../Downloads20*/*.csv
--  braces and brackets   
       .../Downloads201[1-5]/book.csv
       .../Downloads201{11,15,19,99}/book.csv

socket programming multiple client to one server

See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.

Pay attention that accept() is not thread safe, so the call is wrapped within synchronized.

64: synchronized(servSock) {
65:     clientSocket = servSock.accept();
66: }

Get month and year from a datetime in SQL Server 2005

select 
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)

Is there a bash command which counts files?

Here's what I always do:

ls log* | awk 'END{print NR}'

How do I load an HTML page in a <div> using JavaScript?

You can use the jQuery load function:

<div id="topBar">
    <a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">        
</div>

<script>
$(document).ready( function() {
    $("#load_home").on("click", function() {
        $("#content").load("content.html");
    });
});
</script>

Sorry. Edited for the on click instead of on load.

What is an alternative to execfile in Python 3?

Note that the above pattern will fail if you're using PEP-263 encoding declarations that aren't ascii or utf-8. You need to find the encoding of the data, and encode it correctly before handing it to exec().

class python3Execfile(object):
    def _get_file_encoding(self, filename):
        with open(filename, 'rb') as fp:
            try:
                return tokenize.detect_encoding(fp.readline)[0]
            except SyntaxError:
                return "utf-8"

    def my_execfile(filename):
        globals['__file__'] = filename
        with open(filename, 'r', encoding=self._get_file_encoding(filename)) as fp:
            contents = fp.read()
        if not contents.endswith("\n"):
            # http://bugs.python.org/issue10204
            contents += "\n"
        exec(contents, globals, globals)

Write values in app.config file

//if you want change
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings[key].Value = value;

//if you want add
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add("key", value);

Convert timedelta to total seconds

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()