Programs & Examples On #Hornetq

HornetQ is an open source asynchronous messaging project from JBoss.

Enable Hibernate logging

Spring Boot, v2.3.0.RELEASE

Recommended (In application.properties):

logging.level.org.hibernate.SQL=DEBUG //logs all SQL DML statements
logging.level.org.hibernate.type=TRACE //logs all JDBC parameters 

parameters

Note:
The above will not give you a pretty-print though.
You can add it as a configuration:

properties.put("hibernate.format_sql", "true");

or as per below.

Works but NOT recommended

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Reason: It's better to let the logging framework manage/optimize the output for you + it doesn't give you the prepared statement parameters.

Cheers

Clearing content of text file using C#

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

Size of Matrix OpenCV

Note that apart from rows and columns there is a number of channels and type. When it is clear what type is, the channels can act as an extra dimension as in CV_8UC3 so you would address a matrix as

uchar a = M.at<Vec3b>(y, x)[i];

So the size in terms of elements of elementary type is M.rows * M.cols * M.cn

To find the max element one can use

Mat src;
double minVal, maxVal;
minMaxLoc(src, &minVal, &maxVal);

Gridview get Checkbox.Checked value

If you want a method other than findcontrol try the following:

 GridViewRow row = Gridview1.SelectedRow;
 int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
 CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this

What is the purpose of "&&" in a shell command?

See the example:

mkdir test && echo "Something" > test/file

Shell will try to create directory test and then, only if it was successfull will try create file inside it.

So you may interrupt a sequence of steps if one of them failed.

cannot load such file -- bundler/setup (LoadError)

Bundler Version maybe cause the issue.

Please install bundler with other version number.

For example,

gem install bundler -v 1.0.10

Why does DEBUG=False setting make my django Static Files Access fail?

Johnny's answer is great, but still didn't work for me just by adding those lines described there. Based on that answer, the steps that actually worked for me where:

  1. Install WhiteNoise as described:

    pip install WhiteNoise
    
  2. Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py:

    #settings.py
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
    ]
    
    #...
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
    
  3. Then, modify your wsgi.py file as explained in Johnny's answer:

    #wsgi.py
    from django.core.wsgi import get_wsgi_application
    from whitenoise.django import DjangoWhiteNoise
    
    application = get_wsgi_application()
    application = DjangoWhiteNoise(application)
    
  4. After that, deploy your changes to your server (with git or whatever you use).

  5. Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before:

    $ python manage.py collectstatic
    

    You will now see a new folder named staticfiles that contains such elements.

After following these steps you can now run your server and will be able to see your static files while in Production mode.

Update: In case you had version < 4 the changelog indicates that it's no longer necessary to declare the WSGI_APPLICATION = 'projectName.wsgi.application' on your settings.py file.

PHP: Count a stdClass object

Just use this

$i=0;
foreach ($object as $key =>$value)
{
$i++;
}

the variable $i is number of keys.

Unsupported method: BaseConfig.getApplicationIdSuffix()

First, open your application module build.gradle file.

Check the classpath according to your project dependency. If not change the version of this classpath.

from:

classpath 'com.android.tools.build:gradle:1.0.0'

To:

classpath 'com.android.tools.build:gradle:2.3.2'

or higher version according to your gradle of android studio.

If its still problem, then change buildToolsVersion:

From:

buildToolsVersion '21.0.0'

To:

buildToolsVersion '25.0.0'

then hit 'Try again' and gradle will automatically sync. This will solve it.

Simplest way to restart service on a remote computer

  1. open service control manager database using openscmanager
  2. get dependent service using EnumDependService()
  3. Stop all dependent services using ChangeConfig() sending STOP signal to this function if they are started
  4. stop actual service
  5. Get all Services dependencies of a service
  6. Start all services dependencies using StartService() if they are stopped
  7. Start actual service

Thus your service is restarted taking care all dependencies.

How to SELECT by MAX(date)?

Did this on a blog engine to get the latest blog. I adapted it to your table structure.

SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS)

Bootstrap carousel resizing image

replace your image tag with

<img src="http://localhost:6054/wp-content/themes/BLANK-Theme/images/material/images.jpg" alt="the-buzz-img3"  style="width:640px;height:360px" />

use style attribute and make sure there is no css class for image which set image height and width

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

BackgroundTint works as color filter.

FEFBDE as tint

37AEE4 as background

Try seeing the difference by comment tint/background and check the output when both are set.

FirstOrDefault returns NullReferenceException if no match is found

i assume you are working with nullable datatypes, you can do something like this:

var t = things.Where(x => x!=null && x.Value.ID == long.Parse(options.ID)).FirstOrDefault();
var res = t == null ? "" : t.Value;

Why does viewWillAppear not get called when an app comes back from the background?

Swift

Short answer

Use a NotificationCenter observer rather than viewWillAppear.

override func viewDidLoad() {
    super.viewDidLoad()

    // set observer for UIApplication.willEnterForegroundNotification
    NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

}

// my selector that was defined above
@objc func willEnterForeground() {
    // do stuff
}

Long answer

To find out when an app comes back from the background, use a NotificationCenter observer rather than viewWillAppear. Here is a sample project that shows which events happen when. (This is an adaptation of this Objective-C answer.)

import UIKit
class ViewController: UIViewController {

    // MARK: - Overrides

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view did load")

        // add notification observers
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

    }

    override func viewWillAppear(_ animated: Bool) {
        print("view will appear")
    }

    override func viewDidAppear(_ animated: Bool) {
        print("view did appear")
    }

    // MARK: - Notification oberserver methods

    @objc func didBecomeActive() {
        print("did become active")
    }

    @objc func willEnterForeground() {
        print("will enter foreground")
    }

}

On first starting the app, the output order is:

view did load
view will appear
did become active
view did appear

After pushing the home button and then bringing the app back to the foreground, the output order is:

will enter foreground
did become active 

So if you were originally trying to use viewWillAppear then UIApplication.willEnterForegroundNotification is probably what you want.

Note

As of iOS 9 and later, you don't need to remove the observer. The documentation states:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

"The system cannot find the file specified" when running C++ program

I came across this problem and none of these solution worked 100%

In addition to ReturnVoid's answer which suggested the change

Project Properties -> Linker -> Output file -> $(OutDir)$(TargetName)$(TargetExt)

I needed to changed

Project Properties -> C/C++ -> Debug Information Format -> /Zi

This field was blank for me, changing the contents to /Zi (or /Z7 or /ZI if those are the formats you want to use) allowed me to debug

Convert List into Comma-Separated String

If you have a collection of ints:

List<int> customerIds= new List<int>() { 1,2,3,3,4,5,6,7,8,9 };  

You can use string.Join to get a string:

var result = String.Join(",", customerIds);

Enjoy!

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
  tab3.desc = "XYZ" and
  tab4.ss = tab3.ss

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

Assert that a WebElement is not present using Selenium WebDriver with java

For node.js I've found the following to be effective way to wait for an element to no longer be present:

// variable to hold loop limit
    var limit = 5;
// variable to hold the loop count
    var tries = 0;
        var retry = driver.findElements(By.xpath(selector));
            while(retry.size > 0 && tries < limit){
                driver.sleep(timeout / 10)
                tries++;
                retry = driver.findElements(By.xpath(selector))
            }

How to list all `env` properties within jenkins pipeline job?

if you really want to loop over the env list just do:

def envs = sh(returnStdout: true, script: 'env').split('\n')
envs.each { name  ->
    println "Name: $name"
}

How can I add a .npmrc file?

Assuming you are using VSTS run vsts-npm-auth -config .npmrc to generate new .npmrc file with the auth token

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

How do I escape double quotes in attributes in an XML String in T-SQL?

Cannot comment anymore but voted it up and wanted to let folks know that &quot; works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src=&quot;(.*)&quot;.*" using the escaped version instead of double-quotes.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

__init__() got an unexpected keyword argument 'user'

LivingRoom.objects.create() calls LivingRoom.__init__() - as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the default keyword as explained in the FineManual.

List of all users that can connect via SSH

Read man sshd_config for more details, but you can use the AllowUsers directive in /etc/ssh/sshd_config to limit the set of users who can login.

e.g.

AllowUsers boris

would mean that only the boris user could login via ssh.

What is class="mb-0" in Bootstrap 4?

m - sets margin

p - sets padding

t - sets margin-top or padding-top

b - sets margin-bottom or padding-bottom

l - sets margin-left or padding-left

r - sets margin-right or padding-right

x - sets both padding-left and padding-right or margin-left and margin-right

y - sets both padding-top and padding-bottom or margin-top and margin-bottom

blank - sets a margin or padding on all 4 sides of the element

0 - sets margin or padding to 0

1 - sets margin or padding to .25rem (4px if font-size is 16px)

2 - sets margin or padding to .5rem (8px if font-size is 16px)

3 - sets margin or padding to 1rem (16px if font-size is 16px)

4 - sets margin or padding to 1.5rem (24px if font-size is 16px)

5 - sets margin or padding to 3rem (48px if font-size is 16px)

auto - sets margin to auto

How to put a link on a button with bootstrap?

Another trick to get the link color working correctly inside the <button> markup

<button type="button" class="btn btn-outline-success and-all-other-classes"> 
  <a href="#" style="color:inherit"> Button text with correct colors </a>
</button>

Please keep in mind that in bs4 beta e.g. btn-primary-outline changed to btn-outline-primary

How does setTimeout work in Node.JS?

The semantics of setTimeout are roughly the same as in a web browser: the timeout arg is a minimum number of ms to wait before executing, not a guarantee. Furthermore, passing 0, a non-number, or a negative number, will cause it to wait a minimum number of ms. In Node, this is 1ms, but in browsers it can be as much as 50ms.

The reason for this is that there is no preemption of JavaScript by JavaScript. Consider this example:

setTimeout(function () {
  console.log('boo')
}, 100)
var end = Date.now() + 5000
while (Date.now() < end) ;
console.log('imma let you finish but blocking the event loop is the best bug of all TIME')

The flow here is:

  1. schedule the timeout for 100ms.
  2. busywait for 5000ms.
  3. return to the event loop. check for pending timers and execute.

If this was not the case, then you could have one bit of JavaScript "interrupt" another. We'd have to set up mutexes and semaphors and such, to prevent code like this from being extremely hard to reason about:

var a = 100;
setTimeout(function () {
  a = 0;
}, 0);
var b = a; // 100 or 0?

The single-threadedness of Node's JavaScript execution makes it much simpler to work with than most other styles of concurrency. Of course, the trade-off is that it's possible for a badly-behaved part of the program to block the whole thing with an infinite loop.

Is this a better demon to battle than the complexity of preemption? That depends.

trace a particular IP and port

you can use tcpdump on the server to check if the client even reaches the server.

  tcpdump -i any tcp port 9100

also make sure your firewall is not blocking incoming connections.

EDIT: you can also write the dump into a file and view it with wireshark on your client if you don't want to read it on the console.

2nd Edit: you can check if you can reach the port via

 nc ip 9100 -z -v

from your local PC.

An error occurred while collecting items to be installed (Access is denied)

I got this error on my ubuntu box until I ran eclipse as root and installed from there:

$ gksudo eclipse

Eclipse was trying to download the packages to /usr/lib/* where I don't have write permissions

Java Timer vs ExecutorService?

ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.

An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...

Just look at what each offers to decide.

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

css h1 - only as wide as the text

An easy fix for this is to float your H1 element left:

.centercol h1{
    background: #F2EFE9;
    border-left: 3px solid #C6C1B8;
    color: #006BB6;
    display: block;
    float: left;
    font-weight: normal;
    font-size: 18px;
    padding: 3px 3px 3px 6px;
}

I have put together a simple jsfiddle example that shows the effect of the "float: left" style on the width of your H1 element for anyone looking for a more generic answer:

http://jsfiddle.net/zmEBt/1/

How to run Unix shell script from Java code?

You can use Apache Commons exec library also.

Example :

package testShellScript;

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
    int iExitValue;
    String sCommandString;

    public void runScript(String command){
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("permission denied.");
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        TestScript testScript = new TestScript();
        testScript.runScript("sh /root/Desktop/testScript.sh");
    }
}

For further reference, An example is given on Apache Doc also.

What is the difference between task and thread?

Task is like a operation that you wanna perform , Thread helps to manage those operation through multiple process nodes. task is a lightweight option as Threading can lead to a complex code management
I will suggest to read from MSDN(Best in world) always

Task

Thread

Python time measure function

I don't see what the problem with the timeit module is. This is probably the simplest way to do it.

import timeit
timeit.timeit(a, number=1)

Its also possible to send arguments to the functions. All you need is to wrap your function up using decorators. More explanation here: http://www.pythoncentral.io/time-a-python-function/

The only case where you might be interested in writing your own timing statements is if you want to run a function only once and are also want to obtain its return value.

The advantage of using the timeit module is that it lets you repeat the number of executions. This might be necessary because other processes might interfere with your timing accuracy. So, you should run it multiple times and look at the lowest value.

how to remove new lines and returns from php string?

you can pass an array of strings to str_replace, so you can do all in a single statement:

$content = str_replace(["\r\n", "\n", "\r"], "", $content);

Animate a custom Dialog

I've been struggling with Dialog animation today, finally got it working using styles, so here is an example.

To start with, the most important thing — I probably had it working 5 different ways today but couldn't tell because... If your devices animation settings are set to "No Animations" (Settings ? Display ? Animation) then the dialogs won't be animated no matter what you do!

The following is a stripped down version of my styles.xml. Hopefully it is self-explanatory. This should be located in res/values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="PauseDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
    </style>

    <style name="PauseDialogAnimation">
        <item name="android:windowEnterAnimation">@anim/spin_in</item>
        <item name="android:windowExitAnimation">@android:anim/slide_out_right</item>
    </style>
</resources>

The windowEnterAnimation is one of my animations and is located in res\anim. The windowExitAnimation is one of the animations that is part of the Android SDK.

Then when I create the Dialog in my activities onCreateDialog(int id) method I do the following.

Dialog dialog = new Dialog(this, R.style.PauseDialog);

// Setting the title and layout for the dialog
dialog.setTitle(R.string.pause_menu_label);
dialog.setContentView(R.layout.pause_menu);

Alternatively you could set the animations the following way instead of using the Dialog constructor that takes a theme.

Dialog dialog = new Dialog(this);
dialog.getWindow().getAttributes().windowAnimations = R.style.PauseDialogAnimation;

How to resolve cURL Error (7): couldn't connect to host?

Check if port 80 and 443 are blocked. or enter - IP graph.facebook.com and enter it in etc/hosts file

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

csv.Error: iterator should return strings, not bytes

In Python3, csv.reader expects, that passed iterable returns strings, not bytes. Here is one more solution to this problem, that uses codecs module:

import csv
import codecs
ifile  = open('sample.csv', "rb")
read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))
for row in read :
    print (row) 

How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

{
    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

How to convert int to float in C?

No, because you do the expression using integers, so you divide the integer 50 by the integer 100, which results in the integer 0. Type cast one of them to a float and it should work.

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

When I'm running a springboot project, the application.yml configuration is like this:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Notice that there isn't quotation marks around the password. And I can run this project in my windows System.

But when I try to deploy to the server, I have the problem and I fix it by changing the application.yml to:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
    username: root
    password: "root"
    driver-class-name: com.mysql.cj.jdbc.Driver

Add IIS 7 AppPool Identities as SQL Server Logons

This may be what you are looking for...

http://technet.microsoft.com/en-us/library/cc730708%28WS.10%29.aspx

I would also advise longer term to consider a limited rights domain user, what you are trying works fine in a silo machine scenario but you are going to have to make changes if you move to another machine for the DB server.

Are there any log file about Windows Services Status?

Take a look at the System log in Windows EventViewer (eventvwr from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,

Event Type: Information
Event Source:   Service Control Manager
Event Category: None
Event ID:   7036
Date:       7/1/2009
Time:       12:09:43 PM
User:       N/A
Computer:   MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

String concatenation in Jinja

You can use + if you know all the values are strings. Jinja also provides the ~ operator, which will ensure all values are converted to string first.

{% set my_string = my_string ~ stuff ~ ', '%}

Adding two Java 8 streams, or an extra element to a stream

Just do:

Stream.of(stream1, stream2, Stream.of(element)).flatMap(identity());

where identity() is a static import of Function.identity().

Concatenating multiple streams into one stream is the same as flattening a stream.

However, unfortunately, for some reason there is no flatten() method on Stream, so you have to use flatMap() with the identity function.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

To call a sub inside another sub you only need to do:

Call Subname()

So where you have CalculateA(Nc,kij, xi, a1, a) you need to have call CalculateA(Nc,kij, xi, a1, a)

As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...) cause this way it does not appear in the macro list and it's easier to work

Hope it helps, Bruno

PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."

Fastest way to convert Image to Byte array

The fastest way i could find out is this :

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

Hope to be useful

How to set initial value and auto increment in MySQL?

For this you have to set AUTO_INCREMENT value

ALTER TABLE tablename AUTO_INCREMENT = <INITIAL_VALUE>

Example

ALTER TABLE tablename AUTO_INCREMENT = 101

Python xml ElementTree from a string source?

You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

Exit while loop by user hitting ENTER key

The following works from me:

i = '0'
while len(i) != 0:
    i = list(map(int, input(),split()))

How to tell if a JavaScript function is defined

If you look at the source of the library @Venkat Sudheer Reddy Aedama mentioned, underscorejs, you can see this:

_.isFunction = function(obj) {
  return typeof obj == 'function' || false;
};

This is just my HINT, HINT answer :>

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

A simple explanation that made it more clear to me is:

When you deploy your app, modules in dependencies need to be installed or your app won't work. Modules in devDependencies don't need to be installed on the production server since you're not developing on that machine. link

How do I count unique visitors to my site?

Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)

Register and show online users and visitors

Count Online users and visitors using a MySQL table

In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.

You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.

First it's presented the method with recording in a text file on the server, than the method with MySQL table.

To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.

• Both scripts can be included in ".php" files (with include()), or in ".html" files (with <script>), as you can see in the examples presented at the bottom of this page; but the server must run PHP.

Storing online users and visitors in a text file

To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.

  1. Create a text file on your server (for example, named userson.txt) and give it CHMOD 0777 permissions (in your FTP application, right click on that file, choose Properties, then select Read, Write, and Execute options).
  2. Create a PHP file (named usersontxt.php) having the code below, then copy this php file in the same directory as userson.txt.

The code for usersontxt.php;

<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. If you want to include the script above in a ".php" file, add the following code in the place you want to show the number of online users and visitors:

4.To show the number of online visitors /users in a ".html" file, use this code:

<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>

This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table

To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.

  1. First we create the "userson" table, with 2 columns (uvon, dt). In the "uvon" column is stored the name of the user (if logged in) or the visitor's IP. In the "dt" column is stored a number with the timestamp (Unix time) when the page is accessed.
  • Add the following code in a php file (for example, named "create_userson.php"):

The code for create_userson.php:

<?php
header('Content-type: text/html; charset=utf-8');

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());

// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
 `uvon` VARCHAR(32) PRIMARY KEY,
 `dt` INT(10) UNSIGNED NOT NULL
 ) CHARACTER SET utf8 COLLATE utf8_general_ci"; 

// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;

$conn->close();
?>
  1. Now we create the script that Inserts, Deletes, and Selects data in the userson table (For explanations about the code, see the comments in script).
  • Add the code below in another php file (named usersmysql.php): In both file you must add your personal data for connecting to MySQL database, in the variables: $host, $user, $pass, and $dbname .

The code for usersmysql.php:

<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();         // start Session, if not already started

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-';         // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the rows with visitors
$dt = time();                                    // current timestamp
$timeon = 120;             // number of secconds to keep a user online
$nrvst = 0;                                     // to store the number of visitors
$nrusr = 0;                                     // to store the number of usersrs
$usron = '';                                    // to store the name of logged users

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";

// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
  while($row = $result->fetch_assoc()) {
    if(preg_match($rgxvst, $row['uvon'])) $nrvst++;       // increment the visitors
    else {
      $nrusr++;                   // increment the users
      $usron .= '<br/> - <i>'.$row['uvon']. '</i>';          // stores the user's name
    }
  }
}

$conn->close();                  // close the MySQL connection

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.

  2. Include the usersmysql.php file in the php file in which you want to display the number of online users and visitors.

  3. Or, if you want to insert it in a ".html" file, add this code:

Examples using these scripts

• Including the "usersontxt.php` in a php file:

<!doctype html>

Counter Online Users and Visitors

• Including the "usersmysql.php" in a html file:

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <title>Counter Online Users and Visitors</title>
 <meta name="description" content="PHP script to count and show the number of online users and visitors" />
 <meta name="keywords" content="online users, online visitors" />
</head>
<body>

<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>

</body>
</html>

Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5

Visitors: 3 Users: 2

  • MarPlo
  • Marius

How to declare a static const char* in your header file?

Constant initializer allowed by C++ Standard only for integral or enumeration types. See 9.4.2/4 for details:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

And 9.4.2/7:

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

So you should write somewhere in cpp file:

const char* SomeClass::SOMETHING = "sommething";

Python equivalent to 'hold on' in Matlab

The hold on feature is switched on by default in matplotlib.pyplot. So each time you evoke plt.plot() before plt.show() a drawing is added to the plot. Launching plt.plot() after the function plt.show() leads to redrawing the whole picture.

Using global variables in a function

You need to reference the global variable in every function you want to use.

As follows:

var = "test"

def printGlobalText():
    global var #wWe are telling to explicitly use the global version
    var = "global from printGlobalText fun."
    print "var from printGlobalText: " + var

def printLocalText():
    #We are NOT telling to explicitly use the global version, so we are creating a local variable
    var = "local version from printLocalText fun"
    print "var from printLocalText: " + var

printGlobalText()
printLocalText()
"""
Output Result:
var from printGlobalText: global from printGlobalText fun.
var from printLocalText: local version from printLocalText
[Finished in 0.1s]
"""

Convert string to hex-string in C#

var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));

OR

var result  =string.Join("", 
                input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));

Android studio- "SDK tools directory is missing"

I googled this error and tried all suggestions but nothing to work. My problem is a little bit different. I'm using Ubuntu 16.04 64bit. I was set mount /tmp folder as tmpfs for increasing the performance of applications. My fstab entry was:

tmpfs /tmp tmpfs defaults,noatime,nosuid,nodev,exec,mode=1777,size=1024M 0 0

This is setting /tmp file space to 1G and this is bottleneck for android studio becouse it needs more space in /tmp folder for download SDK files. Now I removed this line and rebooted my computer and everything is working now.

I spend 3 hours for this. I hope help to others.

Why does range(start, end) not include end?

Basically in python range(n) iterates n times, which is of exclusive nature that is why it does not give last value when it is being printed, we can create a function which gives inclusive value it means it will also print last value mentioned in range.

def main():
    for i in inclusive_range(25):
        print(i, sep=" ")


def inclusive_range(*args):
    numargs = len(args)
    if numargs == 0:
        raise TypeError("you need to write at least a value")
    elif numargs == 1:
        stop = args[0]
        start = 0
        step = 1
    elif numargs == 2:
        (start, stop) = args
        step = 1
    elif numargs == 3:
        (start, stop, step) = args
    else:
        raise TypeError("Inclusive range was expected at most 3 arguments,got {}".format(numargs))
    i = start
    while i <= stop:
        yield i
        i += step


if __name__ == "__main__":
    main()

parsing JSONP $http.jsonp() response in angular.js

The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":

JSON_CALLBACK(json_response);  // wrong!

Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!

AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:

angular.callbacks._0(json_response);

CodeIgniter - How to return Json response from controller

//do the edit in your javascript

$('.signinform').submit(function() { 
   $(this).ajaxSubmit({ 
       type : "POST",
       //set the data type
       dataType:'json',
       url: 'index.php/user/signin', // target element(s) to be updated with server response 
       cache : false,
       //check this in Firefox browser
       success : function(response){ console.log(response); alert(response)},
       error: onFailRegistered
   });        
   return false; 
}); 


//controller function

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    

   //add the header here
    header('Content-Type: application/json');
    echo json_encode( $arr );
}

How can I conditionally import an ES6 module?

No, you can't!

However, having bumped into that issue should make you rethink on how you organize your code.

Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/

I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Related to the response using ClientHttpInterceptor, I found a way of keeping the whole response without Buffering factories. Just store the response body input stream inside byte array using some utils method that will copy that array from body, but important, surround this method with try catch because it will break if response is empty (that is the cause of Resource Access Exception) and in catch just create empty byte array, and than just create anonymous inner class of ClientHttpResponse using that array and other parameters from the original response. Than you can return that new ClientHttpResponse object to the rest template execution chain and you can log response using body byte array that is previously stored. That way you will avoid consuming InputStream in the actual response and you can use Rest Template response as it is. Note, this may be dangerous if your's response is too big

using extern template (C++11)

Wikipedia has the best description

In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.

C++03 has this syntax to oblige the compiler to instantiate a template:

  template class std::vector<MyClass>;

C++11 now provides this syntax:

  extern template class std::vector<MyClass>;

which tells the compiler not to instantiate the template in this translation unit.

The warning: nonstandard extension used...

Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.

Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.

How to autosize and right-align GridViewColumn data in WPF?

I created a function for updating GridView column headers for a list and call it whenever the window is re-sized or the listview updates it's layout.

public void correctColumnWidths()
{
    double remainingSpace = myList.ActualWidth;

    if (remainingSpace > 0)
    {
         for (int i = 0; i < (myList.View as GridView).Columns.Count; i++)
              if (i != 2)
                   remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth;

          //Leave 15 px free for scrollbar
          remainingSpace -= 15;

          (myList.View as GridView).Columns[2].Width = remainingSpace;
    }
}

How to loop through Excel files and load them into a database using SSIS package?

I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here

Extract and convert all Excel worksheets into CSV files using PowerShell

is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.

Once the Excel files have been converted to CSV the data import is much less complicated.

Preloading images with jQuery

I usually use this snippet of code on my projects for the loading of the images in a page. You can see the result here https://jsfiddle.net/ftor34ey/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<img src="https://live.staticflickr.com/65535/50020763321_d61d49e505_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50021019427_692a8167e9_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020228418_d730efe386_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020230828_7ef175d07c_k_d.jpg" width="100" />

<div style="background-image: url(https://live.staticflickr.com/65535/50020765826_e8da0aacca_k_d.jpg);"></div>
<style>
    .bg {
        background-image: url("https://live.staticflickr.com/65535/50020765651_af0962c22e_k_d.jpg");
    }
</style>
<div class="bg"></div>

<div id="loadingProgress"></div>

The script save in an array all the src and background-image of the page and load all of them.

You can see/read/show the progress of the loading by the var loadCount.

let backgroundImageArray = [];

function backgroundLoading(i) {

    let loadCount = 0;

    let img = new Image();
    $(img).on('load', function () {

        if (i < backgroundImageArray.length) {

            loadCount = parseInt(((100 / backgroundImageArray.length) * i));
            backgroundLoading(i + 1);

        } else {

            loadCount = 100;
            // do something when the page finished to load all the images
            console.log('loading completed!!!');
            $('#loadingProgress').append('<div>loading completed!!!</div>');

        }

        console.log(loadCount + '%');
        $('#loadingProgress').append('<div>' + loadCount + '%</div>');

    }).attr('src', backgroundImageArray[i - 1]);

}

$(document).ready(function () {

    $('*').each(function () {

        var backgroundImage = $(this).css('background-image');
        var putInArray = false;

        var check = backgroundImage.substr(0, 3);

        if (check == 'url') {

            backgroundImage = backgroundImage.split('url(').join('').split(')').join('');
            backgroundImage = backgroundImage.replace('"', '');
            backgroundImage = backgroundImage.replace('"', '');

            if (backgroundImage.substr(0, 4) == 'http') {
                backgroundImage = backgroundImage;
            }
            putInArray = true;

        } else if ($(this).get(0).tagName == 'IMG') {

            backgroundImage = $(this).attr('src');
            putInArray = true;

        }

        if (putInArray) {
            backgroundImageArray[backgroundImageArray.length] = backgroundImage;
        }

    });

    backgroundLoading(1);

});

What is the difference between a "function" and a "procedure"?

Procedures and functions are both subroutines the only difference between them is that a procedure returns multiple (or at least can do) values whereas a function can only return one value (this is why function notation is used in maths as usually only one value is found at one given time) although some programming languages do not follow these rules this is their true definitions

Storing a file in a database as opposed to the file system?

I'd say, it depends on your situation. For example, I work in local government, and we have lots of images like mugshots, etc. We don't have a high number of users, but we need to have good security and auditing around the data. The database is a better solution for us since it makes this easier and we aren't going to run into scaling problems.

How to create an HTML button that acts like a link?

I used this for a website I'm currently working on and it works great!. If you want some cool styling too I'll put the CSS down here.

_x000D_
_x000D_
input[type="submit"] {_x000D_
  background-color: white;_x000D_
  width: 200px;_x000D_
  border: 3px solid #c9c9c9;_x000D_
  font-size: 24pt;_x000D_
  margin: 5px;_x000D_
  color: #969696;_x000D_
}_x000D_
_x000D_
input[type="submit"]:hover {_x000D_
  color: white;_x000D_
  background-color: #969696;_x000D_
  transition: color 0.2s 0.05s ease;_x000D_
  transition: background-color 0.2s 0.05s ease;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<input type="submit" name="submit" onClick="window.location= 'http://example.com'">
_x000D_
_x000D_
_x000D_

Working JSFiddle here.

Classes residing in App_Code is not accessible

make sure that you are using the same namespace as your pages

What's the difference between map() and flatMap() methods in Java 8?

Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.

This is reflected in the arguments to each operation.

The map operation takes a Function, which is called for each value in the input stream and produces one result value, which is sent to the output stream.

The flatMap operation takes a function that conceptually wants to consume one value and produce an arbitrary number of values. However, in Java, it's cumbersome for a method to return an arbitrary number of values, since methods can return only zero or one value. One could imagine an API where the mapper function for flatMap takes a value and returns an array or a List of values, which are then sent to the output. Given that this is the streams library, a particularly apt way to represent an arbitrary number of return values is for the mapper function itself to return a stream! The values from the stream returned by the mapper are drained from the stream and are passed to the output stream. The "clumps" of values returned by each call to the mapper function are not distinguished at all in the output stream, thus the output is said to have been "flattened."

Typical use is for the mapper function of flatMap to return Stream.empty() if it wants to send zero values, or something like Stream.of(a, b, c) if it wants to return several values. But of course any stream can be returned.

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

How to get the browser viewport dimensions?

I looked and found a cross browser way:

_x000D_
_x000D_
function myFunction(){_x000D_
  if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
    var w = window.innerWidth;_x000D_
    var h = window.innerHeight;_x000D_
  } else {  _x000D_
    var w = document.documentElement.clientWidth;_x000D_
    var h = document.documentElement.clientHeight;_x000D_
  }_x000D_
  var txt = "Page size: width=" + w + ", height=" + h;_x000D_
  document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <body onresize="myFunction()" onload="myFunction()">_x000D_
   <p>_x000D_
    Try to resize the page._x000D_
   </p>_x000D_
   <p id="demo">_x000D_
    &nbsp;_x000D_
   </p>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SQL - select distinct only on one column

You will use the following query:

SELECT * FROM [table] GROUP BY NUMBER;

Where [table] is the name of the table.

This provides a unique listing for the NUMBER column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.

MySQL: View with Subquery in the FROM Clause Limitation

You can work around this by creating a separate VIEW for any subquery you want to use and then join to that in the VIEW you're creating. Here's an example: http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/

This is quite handy as you'll very likely want to reuse it anyway and helps you keep your SQL DRY.

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

How to split a string by spaces in a Windows batch file?

@echo off

:: read a file line by line
for /F  %%i in ('type data.csv') do (
    echo %%i
    :: and we extract four tokens, ; is the delimiter.
    for /f "tokens=1,2,3,4 delims=;" %%a in ("%%i") do (
        set first=%%a&set second=%%b&set third=%%c&set fourth=%%d
        echo %first% and %second% and %third% and %fourth% 
    )
)

How to get memory usage at runtime using C++?

A more elegant way for Don Wakefield method:

#include <iostream>
#include <fstream>

using namespace std;

int main(){

    int tSize = 0, resident = 0, share = 0;
    ifstream buffer("/proc/self/statm");
    buffer >> tSize >> resident >> share;
    buffer.close();

    long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
    double rss = resident * page_size_kb;
    cout << "RSS - " << rss << " kB\n";

    double shared_mem = share * page_size_kb;
    cout << "Shared Memory - " << shared_mem << " kB\n";

    cout << "Private Memory - " << rss - shared_mem << "kB\n";
    return 0;
}

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Alternative #6233....

Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:

// Using the current date/time
let now_local = new Date();
let now_utc = new Date();

// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())

// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';

// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));

I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:

enter image description here

Getting HTML elements by their attribute names

With prototypejs :

 $$('span[property=v.name]');

or

document.body.select('span[property=v.name]');

Both return an array

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

Add following code in info.plist file

<key>NSPhotoLibraryUsageDescription</key>
<string>My description about why I need this capability</string>

enter image description here

"Sub or Function not defined" when trying to run a VBA script in Outlook

This error “Sub or Function not defined”, will come every time when there is some compile error in script, so please check syntax again of your script.

I guess that is why when you used msqbox instead of msgbox it throws the error.

Pointer arithmetic for void pointer in C

Pointer arithmetic is not allowed on void* pointers.

How to submit a form using PhantomJS

Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.

CasperJS

Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.

(Thanks to commenter Mr. M!)

A simple scenario using wait() and notify() in java

Have you taken a look at this Java Tutorial?

Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.

That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.

Javascript "Not a Constructor" Exception while creating objects

In my case I'd forgotten the open and close parantheses at the end of the definition of the function wrapping all of my code in the exported module. I.e. I had:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
);

Instead of:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
)();

The compiler doesn't complain, but the require statement in the importing module doesn't set the variable it's being assigned to, so it's undefined at the point you try to construct it and it will give the TypeError: MyClass is not a constructor error.

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

My mistake was simply using the CSR file instead of the CERT file.

Getting realtime output using subprocess

By setting the buffer size to 1, you essentially force the process to not buffer the output.

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()

Set position / size of UI element as percentage of screen size

Take a look at this:

http://developer.android.com/reference/android/util/DisplayMetrics.html

You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

How do I create executable Java program?

I'm not quite sure what you mean.

But I assume you mean either 1 of 2 things.

  • You want to create an executable .jar file

Eclipse can do this really easily File --> Export and create a jar and select the appropriate Main-Class and it'll generate the .jar for you. In windows you may have to associate .jar with the java runtime. aka Hold shift down, Right Click "open with" browse to your jvm and associate it with javaw.exe

  • create an actual .exe file then you need to use an extra library like

http://jsmooth.sourceforge.net/ or http://launch4j.sourceforge.net/ will create a native .exe stub with a nice icon that will essentially bootstrap your app. They even figure out if your customer hasn't got a JVM installed and prompt you to get one.

Showing all errors and warnings

Set these on php.ini:

;display_startup_errors = On
display_startup_errors=off
display_errors =on
html_errors= on

From your PHP page, use a suitable filter for error reporting.

error_reporting(E_ALL);

Filers can be made according to requirements.

E_ALL
E_ALL | E_STRICT

Creating a zero-filled pandas data frame

If you already have a dataframe, this is the fastest way:

In [1]: columns = ["col{}".format(i) for i in range(10)]
In [2]: orig_df = pd.DataFrame(np.ones((10, 10)), columns=columns)
In [3]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
10000 loops, best of 3: 60.2 µs per loop

Compare to:

In [4]: %timeit d = pd.DataFrame(0, index = np.arange(10), columns=columns)
10000 loops, best of 3: 110 µs per loop

In [5]: temp = np.zeros((10, 10))
In [6]: %timeit d = pd.DataFrame(temp, columns=columns)
10000 loops, best of 3: 95.7 µs per loop

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

How do you Change a Package's Log Level using Log4j?

This work for my:

log4j.logger.org.hibernate.type=trace

Also can try:

log4j.category.org.hibernate.type=trace

Null vs. False vs. 0 in PHP

Below is an example:

            Comparisons of $x with PHP functions

Expression          gettype()   empty()     is_null()   isset() boolean : if($x)
$x = "";            string      TRUE        FALSE       TRUE    FALSE
$x = null;          NULL        TRUE        TRUE        FALSE   FALSE
var $x;             NULL        TRUE        TRUE        FALSE   FALSE
$x is undefined     NULL        TRUE        TRUE        FALSE   FALSE
$x = array();       array       TRUE        FALSE       TRUE    FALSE
$x = false;         boolean     TRUE        FALSE       TRUE    FALSE
$x = true;          boolean     FALSE       FALSE       TRUE    TRUE
$x = 1;             integer     FALSE       FALSE       TRUE    TRUE
$x = 42;            integer     FALSE       FALSE       TRUE    TRUE
$x = 0;             integer     TRUE        FALSE       TRUE    FALSE
$x = -1;            integer     FALSE       FALSE       TRUE    TRUE
$x = "1";           string      FALSE       FALSE       TRUE    TRUE
$x = "0";           string      TRUE        FALSE       TRUE    FALSE
$x = "-1";          string      FALSE       FALSE       TRUE    TRUE
$x = "php";         string      FALSE       FALSE       TRUE    TRUE
$x = "true";        string      FALSE       FALSE       TRUE    TRUE
$x = "false";       string      FALSE       FALSE       TRUE    TRUE

Please see this for more reference of type comparisons in PHP. It should give you a clear understanding.

Is there a developers api for craigslist.org

Craigslist does have a "bulk posting interface" which allows for multiple posts to happen at once through HTTPS POST. See:

http://www.craigslist.org/about/bulk_posting_interface

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Note: this solution and any other "edit the policy.xml" solution disables safety measures against arbitrary code execution vulnerabilities in ImageMagick. If you need to process input that you do not control 100%, you should use a different program (not ImageMagick).

If you're still here, you are trying to edit images that you have complete control over, know are safe, and cannot be edited by users.

There is an /etc/ImageMagick/policy.xml file that is installed by yum. It disallows almost everything (for security and to protect your system from getting overloaded with ImageMagick calls).

If you're getting a ReadImage error as above, you can change the line to:

<policy domain="coder" rights="read" pattern="LABEL" />

which should fix the issue.

The file has a bunch of documentation in it, so you should read that. For example, if you need more permissions, you can combine them like:

<policy domain="coder" rights="read|write" pattern="LABEL" />

...which is preferable to removing all permissions checks (i.e., deleting or commenting out the line).

Format of the initialization string does not conform to specification starting at index 0

I had the same error. In my case, this was because I was missing an closing quote for the password in the connection string.

Changed from this

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password" providerName="System.Data.SqlClient" />

To

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password'" providerName="System.Data.SqlClient" />

Overwriting txt file in java

Your code works fine for me. It replaced the text in the file as expected and didn't append.

If you wanted to append, you set the second parameter in

new FileWriter(fnew,false);

to true;

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

I figured it out. The problem was that there were still some pages in the project that hadn't been converted to use "namespaces" as needed in a web application project. I guess I thought that it wouldn't compile if there were still any of those pages around, but if the page didn't reference anything from outside itself it didn't appear to squawk. So when it was saying that it didn't inherit from "System.Web.UI.Page" that was because it couldn't actually find the class "BasePage" at run time because the page itself was not in the WebApplication namespace. I went through all my pages one by one and made sure that they were properly added to the WebApplication namespace and now it not only compiles without issue, it also displays normally. yay!

what a trial converting from website to web application project can be!

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

Insert auto increment primary key to existing table

For those like myself getting a Multiple primary key defined error try:

ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;

On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

C# difference between == and Equals()

I would add that if you cast your object to a string then it will work correctly. This is why the compiler will give you a warning saying:

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

How to embed a YouTube channel into a webpage

YouTube supports a fairly easy to use iframe and url interface to embed videos, playlists and all user uploads to your channel: https://developers.google.com/youtube/player_parameters

For example this HTML will embed a player loaded with a playlist of all the videos uploaded to your channel. Replace YOURCHANNELNAME with the actual name of your channel:

<iframe src="http://www.youtube.com/embed/?listType=user_uploads&list=YOURCHANNELNAME" width="480" height="400"></iframe>

How to use and style new AlertDialog from appCompat 22.1 and above

    <item name="editTextColor">@color/white</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:textColorHint">@color/gray</item>
    <item name="android:textColorPrimary">@color/gray</item>
    <item name="colorControlNormal">@color/gray</item>
    <item name="colorControlActivated">@color/white</item>
    <item name="colorControlHighlight">#30FFFFFF</item>

Deleting an object in C++

saveLeaves(vec,msh);
I'm assuming takes the msh pointer and puts it inside of vec. Since msh is just a pointer to the memory, if you delete it, it will also get deleted inside of the vector.

Exporting result of select statement to CSV format in DB2

DBeaver allows you connect to a DB2 database, run a query, and export the result-set to a CSV file that can be opened and fine-tuned in MS Excel or LibreOffice Calc.

To do this, all you have to do (in DBeaver) is right-click on the results grid (after running the query) and select "Export Resultset" from the context-menu.

This produces the dialog below, where you can ultimately save the result-set to a file as CSV, XML, or HTML:

enter image description here

Auto Increment after delete in MySQL

There is actually a way to fix that. First you delete the auto_incremented primary key column, and then you add it again, like this:

ALTER TABLE table_name DROP column_name;
ALTER TABLE table_name ADD column_name int not null auto_increment primary key first;

How do you show animated GIFs on a Windows Form (c#)

Public Class Form1

    Private animatedimage As New Bitmap("C:\MyData\Search.gif")
    Private currentlyanimating As Boolean = False

    Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Me.Invalidate()

    End Sub

    Private Sub AnimateImage()

        If currentlyanimating = True Then
            ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
            currentlyanimating = False
        End If

    End Sub

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

        AnimateImage()
        ImageAnimator.UpdateFrames(animatedimage)
        e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click

        currentlyanimating = False
        ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
        BtnStart.Enabled = True
        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click

        currentlyanimating = True
        AnimateImage()
        BtnStart.Enabled = False
        BtnStop.Enabled = True

    End Sub

End Class

How to declare a constant map in Golang?

You may emulate a map with a closure:

package main

import (
    "fmt"
)

// http://stackoverflow.com/a/27457144/10278

func romanNumeralDict() func(int) string {
    // innerMap is captured in the closure returned below
    innerMap := map[int]string{
        1000: "M",
        900:  "CM",
        500:  "D",
        400:  "CD",
        100:  "C",
        90:   "XC",
        50:   "L",
        40:   "XL",
        10:   "X",
        9:    "IX",
        5:    "V",
        4:    "IV",
        1:    "I",
    }

    return func(key int) string {
        return innerMap[key]
    }
}

func main() {
    fmt.Println(romanNumeralDict()(10))
    fmt.Println(romanNumeralDict()(100))

    dict := romanNumeralDict()
    fmt.Println(dict(400))
}

Try it on the Go playground

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

On my machine mysqld service stopped that's why it was giving me the same problem.

1:- Go to terminal and type

sudo service mysqld restart

This will restart the mysqld service and create a new sock file on the required location.

class method generates "TypeError: ... got multiple values for keyword argument ..."

The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled self. If the class is declared thus:

class foo(object):
  def foodo(self, thing=None, thong='not underwear'):
    print thing if thing else "nothing" 
    print 'a thong is',thong

it behaves as expected.

Explanation:

Without self as the first parameter, when myfoo.foodo(thing="something") is executed, the foodo method is called with arguments (myfoo, thing="something"). The instance myfoo is then assigned to thing (since thing is the first declared parameter), but python also attempts to assign "something" to thing, hence the Exception.

To demonstrate, try running this with the original code:

myfoo.foodo("something")
print
print myfoo

You'll output like:

<__main__.foo object at 0x321c290>
a thong is something

<__main__.foo object at 0x321c290>

You can see that 'thing' has been assigned a reference to the instance 'myfoo' of the class 'foo'. This section of the docs explains how function arguments work a bit more.

"Faceted Project Problem (Java Version Mismatch)" error message

Did you check your Project Properties -> Project Facets panel? (From that post)

A WTP project is composed of multiple units of functionality (known as facets).

The Java facet version needs to always match the java compiler compliance level.
The best way to change java level is to use the Project Facets properties panel as that will update both places at the same time.

WTP

The "Project->Preferences->Project Facets" stores its configuration in this file, "org.eclipse.wst.common.project.facet.core.xml", under the ".settings" directory.

The content might look like this

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <runtime name="WebSphere Application Server v6.1"/>
  <fixed facet="jst.java"/>
  <fixed facet="jst.web"/>
  <installed facet="jst.java" version="5.0"/>
  <installed facet="jst.web" version="2.4"/>
  <installed facet="jsf.ibm" version="7.0"/>
  <installed facet="jsf.base" version="7.0"/>
  <installed facet="web.jstl" version="1.1"/>
</faceted-project>

Check also your Java compliance level:

Java compliance level

IIS Config Error - This configuration section cannot be used at this path

I think the better way is that you must remove you configuration from your web.config. Publish your code on the server and do what you want to remove directly from the IIS server interface.

Thanks to this method if you sucessfully do what you want, you just have to get the web.config and compare the differences. After that you just have to post the solution in this post :-P.

Capturing URL parameters in request.GET

This is not exactly what you asked for, but this snippet is helpful for managing query_strings in templates.

Pandas: Setting no. of max rows

As in this answer to a similar question, there is no need to hack settings. It is much simpler to write:

print(foo.to_string())

How to keep :active css style after clicking an element

Combine JS & CSS :

button{
  /* 1st state */
}

button:hover{
  /* hover state */
}

button:active{
  /* click state */
}

button.active{
  /* after click state */
}


jQuery('button').click(function(){
   jQuery(this).toggleClass('active');
});

Prevent BODY from scrolling when a modal is opened

Most of the pieces are here, but I don't see any answer that puts it all together.

The problem is threefold.

(1) prevent the scroll of the underlying page

$('body').css('overflow', 'hidden')

(2) and remove the scroll bar

var handler = function (e) { e.preventDefault() }
$('.modal').bind('mousewheel touchmove', handler)

(3) clean up when the modal is dismissed

$('.modal').unbind('mousewheel touchmove', handler)
$('body').css('overflow', '')

If the modal is not full-screen then apply the .modal bindings to a full screen overlay.

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

What does servletcontext.getRealPath("/") mean and when should I use it

There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?

Linking a qtDesigner .ui file to python/pyqt?

Using Anaconda3 (September 2018) and QT designer 5.9.5. In QT designer, save your file as ui. Open Anaconda prompt. Search for your file: cd C:.... (copy/paste the access path of your file). Then write: pyuic5 -x helloworld.ui -o helloworld.py (helloworld = name of your file). Enter. Launch Spyder. Open your file .py.

How do I capture the output of a script if it is being ran by the task scheduler?

This snippet uses wmic.exe to build the date string. It isn't mangled by locale settings

rem DATE as YYYY-MM-DD via WMIC.EXE
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set RDATE=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2% 

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

The closest legal equivalent to illegal syntax mentioned in question is:

select * from myTable m
where not exists (
  select 1
  from table(sys.ku$_vcnt('Done', 'Finished except', 'In Progress')) patterns
  where m.status like patterns.column_value || '%'
)

Both mine and @Sethionic's answer make possible to list patterns dynamically (just by choosing other source than auxiliar sys.whatever table).

Note, if we had to search pattern inside string (rather than from the beginning) and database contained for example status = 'Done In Progress', then my solution (modified to like '%' || patterns.column_value || '%') would still generate one row for given record, whileas the @Sethionic's solution (modified to another auxiliar join before a) would produce multiple rows for each pattern occurence. Not judging which is better, just be aware of differences and choose which better fits your need.

Detect if the app was launched/opened from a push notification

M.Othman's answer is correct for apps that don't contain scene delegate For Scene Delegate Apps This worked for me on iOS 13

Here is the code for that should be written in will connect scene

if connectionOptions.notificationResponse == nil { 
//Not opened from push notification
} else {
  //Opened from push notification
}

Code for app delegate to support earlier versions didFinishLaunchingWithOptions

let notification = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification]
        if (notification != nil) {

            //Launched from push notification
        } else {

            //Launch from other source
        }

How to convert strings into integers in Python?

Try this.

x = "1"

x is a string because it has quotes around it, but it has a number in it.

x = int(x)

Since x has the number 1 in it, I can turn it in to a integer.

To see if a string is a number, you can do this.

def is_number(var):
    try:
        if var == int(var):
            return True
    except Exception:
        return False

x = "1"

y = "test"

x_test = is_number(x)

print(x_test)

It should print to IDLE True because x is a number.

y_test = is_number(y)

print(y_test)

It should print to IDLE False because y in not a number.

How can I make PHP display the error instead of giving me 500 Internal Server Error

Enabling error displaying from PHP code doesn't work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don't know which line. From the console, I use this:

/var/log/php-fpm# cat www-error.log | grep mycode.php

And I have the output:

[04-Apr-2016 06:58:27] PHP Parse error:  syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458

This helps me find the line where I have the typo.

How to create an empty array in Swift?

var myArr1 = [AnyObject]()

can store any object

var myArr2 = [String]()

can store only string

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

How should I use try-with-resources with JDBC?

There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ; at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:

public List<User> getUser(int userId) {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    List<User> users = new ArrayList<>();
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setInt(1, userId);
        try (ResultSet rs = ps.executeQuery()) {
            while(rs.next()) {
                users.add(new User(rs.getInt("id"), rs.getString("name")));
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}

How can I compare time in SQL Server?

if (cast('2012-06-20 23:49:14.363' as time) between 
    cast('2012-06-20 23:49:14.363' as time) and 
    cast('2012-06-20 23:49:14.363' as time))

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Desktop: first-class support

Oracle JavaFX from Java SE supports only OS X (macOS), GNU/Linux and Microsoft Windows. On these platforms, JavaFX applications are typically run on JVM from Java SE or OpenJDK.

Android: should work

There is also a JavaFXPorts project, which is an open-source project sponsored by a third-party. It aims to port JavaFX library to Android and iOS.

On Android, this library can be used like any other Java library; the JVM bytecode is compiled to Dalvik bytecode. It's what people mean by saying that "Android runs Java".

iOS: status not clear

On iOS, situation is a bit more complex, as neither Java SE nor OpenJDK supports Apple mobile devices. Till recently, the only sensible option was to use RoboVM ahead-of-time Java compiler for iOS. Unfortunately, on 15 April 2015, RoboVM project was shut down.

One possible alternative is Intel's Multi-OS Engine. Till recently, it was a proprietary technology, but on 11 August 2016 it was open-sourced. Although it can be possible to compile an iOS JavaFX app using JavaFXPorts' JavaFX implementation, there is no evidence for that so far. As you can see, the situation is dynamically changing, and this answer will be hopefully updated when new information is available.

Windows Phone: no support

With Windows Phone it's simple: there is no JavaFX support of any kind.

How to call two methods on button's onclick method in HTML or JavaScript?

The modern event handling method:

element.addEventListener('click', startDragDrop, false);
element.addEventListener('click', spyOnUser, false);

The first argument is the event, the second is the function and the third specifies whether to allow event bubbling.

From QuirksMode:

W3C’s DOM Level 2 Event specification pays careful attention to the problems of the traditional model. It offers a simple way to register as many event handlers as you like for the same event on one element.

The key to the W3C event registration model is the method addEventListener(). You give it three arguments: the event type, the function to be executed and a boolean (true or false) that I’ll explain later on. To register our well known doSomething() function to the onclick of an element you do:

Full details here: http://www.quirksmode.org/js/events_advanced.html

Using jQuery

if you're using jQuery, there is a nice API for event handling:

$('#myElement').bind('click', function() { doStuff(); });
$('#myElement').bind('click', function() { doMoreStuff(); });
$('#myElement').bind('click', doEvenMoreStuff);

Full details here: http://api.jquery.com/category/events/

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

Programmatically navigate to another view controller/scene

I already found the answer

Swift 4

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "nextView") as! NextViewController
self.present(nextViewController, animated:true, completion:nil)

Swift 3

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)

How do you set a JavaScript onclick event to a class with css

You can't do it with just CSS, but you can do it with Javascript, and (optionally) jQuery.

If you want to do it without jQuery:

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            anchor.onclick = function() {
                alert('ho ho ho');
            }
        }
    }
</script>

And to do it without jQuery, and only on a specific class (ex: hohoho):

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            if(/\bhohoho\b/).match(anchor.className)) {
                anchor.onclick = function() {
                    alert('ho ho ho');
                }
            }
        }
    }
</script>

If you are okay with using jQuery, then you can do this for all anchors:

<script>
    $(document).ready(function() {
        $('a').click(function() {
            alert('ho ho ho');
        });
    });
</script>

And this jQuery snippet to only apply it to anchors with a specific class:

<script>
    $(document).ready(function() {
        $('a.hohoho').click(function() {
            alert('ho ho ho');
        });
    });
</script>

How to get the first day of the current week and month?

The first day of week can be determined with help of java.util.Calendar as follows:

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
long firstDayOfWeekTimestamp = calendar.getTimeInMillis();

The first day of month can be determined as follows:

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DATE) > 1) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of month.
}
long firstDayOfMonthTimestamp = calendar.getTimeInMillis();

Pretty verbose, yes.


Java 7 will come with a much improved Date and Time API (JSR-310). If you can't switch yet, then you can as far use JodaTime which makes it all less complicated:

DateTime dateTime = new DateTime(timestamp);
long firstDayOfWeekTimestamp = dateTime.withDayOfWeek(1).getMillis();

and

DateTime dateTime = new DateTime(timestamp);
long firstDayOfMonthTimestamp = dateTime.withDayOfMonth(1).getMillis();

How to get css background color on <tr> tag to span entire row

Removing the borders should make the background color paint without any gaps between the cells. If you look carefully at this jsFiddle, you should see that the light blue color stretches across the row with no white gaps.

If all else fails, try this:

table { border-collapse: collapse; }

Rounding a number to the nearest 5 or 10 or X

Integrated Answer

X = 1234 'number to round
N = 5    'rounding factor
round(X/N)*N   'result is 1235

For floating point to integer, 1234.564 to 1235, (this is VB specific, most other languages simply truncate) do:

int(1234.564)   'result is 1235

Beware: VB uses Bankers Rounding, to the nearest even number, which can be surprising if you're not aware of it:

msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too

Thank you everyone.

How to request a random row in SQL?

I have to agree with CD-MaN: Using "ORDER BY RAND()" will work nicely for small tables or when you do your SELECT only a few times.

I also use the "num_value >= RAND() * ..." technique, and if I really want to have random results I have a special "random" column in the table that I update once a day or so. That single UPDATE run will take some time (especially because you'll have to have an index on that column), but it's much faster than creating random numbers for every row each time the select is run.

Aliases in Windows command prompt

Naturally, I would not rest until I have the most convenient solution of all. Combining the very many answers and topics on the vast internet, here is what you can have.

  • Loads automatically with every instance of cmd
  • Doesn't require keyword DOSKEY for aliases
    example: ls=ls --color=auto $*

Note that this is largely based on Argyll's answer and comments, definitely read it to understand the concepts.

How to make it work?

  1. Create a mac macro file with the aliases
    you can even use a bat/cmd file to also run other stuff (similar to .bashrc in linux)
  2. Register it in Registry to run on each instance of cmd
      or run it via shortcut only if you want

Example steps:

%userprofile%/cmd/aliases.mac
;==============================================================================
;= This file is registered via registry to auto load with each instance of cmd.
;================================ general info ================================
;= https://stackoverflow.com/a/59978163/985454  -  how to set it up?
;= https://gist.github.com/postcog/5c8c13f7f66330b493b8  -  example doskey macrofile
;========================= loading with cmd shortcut ==========================
;= create a shortcut with the following target :
;= %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"

alias=subl %USERPROFILE%\cmd\aliases.mac
hosts=runas /noprofile /savecred /user:QWERTY-XPS9370\administrator "subl C:\Windows\System32\drivers\etc\hosts" > NUL

p=@echo "~~ powercfg -devicequery wake_armed ~~" && powercfg -devicequery wake_armed && @echo "~~ powercfg -requests ~~ " && powercfg -requests && @echo "~~ powercfg -waketimers ~~"p && powercfg -waketimers

ls=ls --color=auto $*
ll=ls -l --color=auto $*
la=ls -la --color=auto $*
grep=grep --color $*

~=cd %USERPROFILE%
cdr=cd C:\repos
cde=cd C:\repos\esquire
cdd=cd C:\repos\dixons
cds=cd C:\repos\stekkie
cdu=cd C:\repos\uplus
cduo=cd C:\repos\uplus\oxbridge-fe
cdus=cd C:\repos\uplus\stratus

npx=npx --no-install $*
npxi=npx $*
npr=npm run $*

now=vercel $*


;=only in bash
;=alias whereget='_whereget() { A=$1; B=$2; shift 2; eval \"$(where $B | head -$A | tail -1)\" $@; }; _whereget'

history=doskey /history
;= h [SHOW | SAVE | TSAVE ]
h=IF ".$*." == ".." (echo "usage: h [ SHOW | SAVE | TSAVE ]" && doskey/history) ELSE (IF /I "$1" == "SAVE" (doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "TSAVE" (echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "SHOW" (type %USERPROFILE%\cmd\history.log) ELSE (doskey/history))))
loghistory=doskey /history >> %USERPROFILE%\cmd\history.log

;=exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved, exiting & timeout 1 & exit $*
exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & exit $*

;============================= :end ============================
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line.  It clears out the ';'
;= rem * macro. We're using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=

Now you have three options:

  • a) load manually with shortcut

    create a shortcut to cmd.exe with the following target :
    %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"

  • b) register just the aliases.mac macrofile

  • c) register a regular cmd/bat file to also run arbitrary commands
    see example cmdrc.cmd file at the bottom

note: Below, Autorun_ is just a placeholder key which will not do anything. Pick one and rename the other.

Manually edit registry at this path:

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
  Autorun    REG_SZ    doskey /macrofile=%userprofile%\cmd\aliases.mac
  Autorun_    REG_SZ    %USERPROFILE%\cmd\cmdrc.cmd

Or import reg file:

%userprofile%/cmd/cmd-aliases.reg
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="doskey /macrofile=%userprofile%\\cmd\\aliases.mac"
"Autorun_"="%USERPROFILE%\\cmd\\cmdrc.cmd"
%userprofile%/cmd/cmdrc.cmd you don't need this file if you decided for b) above
:: This file is registered via registry to auto load with each instance of cmd.
:: https://stackoverflow.com/a/59978163/985454

@echo off
doskey /macrofile=%userprofile%\cmd\aliases.mac

:: put other commands here

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

Button that refreshes the page on click

Though the question is for button, but if anyone wants to refresh the page using <a>, you can simply do

<a href="./">Reload</a>

How to create Windows EventLog source from command line?

Try PowerShell 2.0's EventLog cmdlets

Throwing this in for PowerShell 2.0 and upwards:

  • Run New-EventLog once to register the event source:

    New-EventLog -LogName Application -Source MyApp
    
  • Then use Write-EventLog to write to the log:

    Write-EventLog 
        -LogName Application 
        -Source MyApp 
        -EntryType Error 
        -Message "Immunity to iocaine powder not detected, dying now" 
        -EventId 1
    

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Modulus works to get bottom bits (only), although I think value & 0x1ffff expresses "take the bottom 17 bits" more directly than value % 131072, and so is easier to understand as doing that.

The top 17 bits of a 32-bit unsigned value would be value & 0xffff8000 (if you want them still in their positions at the top), or value >> 15 if you want the top 17 bits of the value in the bottom 17 bits of the result.

Drawing circles with System.Drawing

There is no DrawCircle method; use DrawEllipse instead. I have a static class with handy graphics extension methods. The following ones draw and fill circles. They are wrappers around DrawEllipse and FillEllipse:

public static class GraphicsExtensions
{
    public static void DrawCircle(this Graphics g, Pen pen,
                                  float centerX, float centerY, float radius)
    {
        g.DrawEllipse(pen, centerX - radius, centerY - radius,
                      radius + radius, radius + radius);
    }

    public static void FillCircle(this Graphics g, Brush brush,
                                  float centerX, float centerY, float radius)
    {
        g.FillEllipse(brush, centerX - radius, centerY - radius,
                      radius + radius, radius + radius);
    }
}

You can call them like this:

g.FillCircle(myBrush, centerX, centerY, radius);
g.DrawCircle(myPen, centerX, centerY, radius);

Paste multiple columns together

Just to add additional solution with Reduce which probably is slower than do.call but probebly better than apply because it will avoid the matrix conversion. Also, instead a for loop we could just use setdiff in order to remove unwanted columns

cols <- c('b','c','d')
data$x <- Reduce(function(...) paste(..., sep = "-"), data[cols])
data[setdiff(names(data), cols)]
#   a     x
# 1 1 a-d-g
# 2 2 b-e-h
# 3 3 c-f-i

Alternatively we could update data in place using the data.table package (assuming fresh data)

library(data.table)
setDT(data)[, x := Reduce(function(...) paste(..., sep = "-"), .SD[, mget(cols)])]
data[, (cols) := NULL]
data
#    a     x
# 1: 1 a-d-g
# 2: 2 b-e-h
# 3: 3 c-f-i

Another option is to use .SDcols instead of mget as in

setDT(data)[, x := Reduce(function(...) paste(..., sep = "-"), .SD), .SDcols = cols]

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

Just to elaborate a bit more on Henry's answer, you can also use specific error codes, from raise_application_error and handle them accordingly on the client side. For example:

Suppose you had a PL/SQL procedure like this to check for the existence of a location record:

   PROCEDURE chk_location_exists
   (
      p_location_id IN location.gie_location_id%TYPE
   )
   AS
      l_cnt INTEGER := 0;
   BEGIN
      SELECT COUNT(*)
        INTO l_cnt
        FROM location
       WHERE gie_location_id = p_location_id;

       IF l_cnt = 0
       THEN
          raise_application_error(
             gc_entity_not_found,
             'The associated location record could not be found.');
       END IF;
   END;

The raise_application_error allows you to raise a specific error code. In your package header, you can define: gc_entity_not_found INTEGER := -20001;

If you need other error codes for other types of errors, you can define other error codes using -20002, -20003, etc.

Then on the client side, you can do something like this (this example is for C#):

/// <summary>
/// <para>Represents Oracle error number when entity is not found in database.</para>
/// </summary>
private const int OraEntityNotFoundInDB = 20001;

And you can execute your code in a try/catch

try
{
   // call the chk_location_exists SP
}
catch (Exception e)
{
    if ((e is OracleException) && (((OracleException)e).Number == OraEntityNotFoundInDB))
    {
        // create an EntityNotFoundException with message indicating that entity was not found in
        // database; use the message of the OracleException, which will indicate the table corresponding
        // to the entity which wasn't found and also the exact line in the PL/SQL code where the application
        // error was raised
        return new EntityNotFoundException(
            "A required entity was not found in the database: " + e.Message);
    }
}

How to enable native resolution for apps on iPhone 6 and 6 Plus?

Note that iPhone 6 will use the 320pt (640px) resolution if you have enabled the 'Display Zoom' in iPhone > Settings > Display & Brightness > View.

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

You should use NVARCHAR anytime you have to store multiple languages. I believe you have to use it for the Asian languages but don't quote me on it.

Here's the problem if you take Russian for example and store it in a varchar, you will be fine so long as you define the correct code page. But let's say your using a default english sql install, then the russian characters will not be handled correctly. If you were using NVARCHAR() they would be handled properly.

Edit

Ok let me quote MSDN and maybee I was to specific but you don't want to store more then one code page in a varcar column, while you can you shouldn't

When you deal with text data that is stored in the char, varchar, varchar(max), or text data type, the most important limitation to consider is that only information from a single code page can be validated by the system. (You can store data from multiple code pages, but this is not recommended.) The exact code page used to validate and store the data depends on the collation of the column. If a column-level collation has not been defined, the collation of the database is used. To determine the code page that is used for a given column, you can use the COLLATIONPROPERTY function, as shown in the following code examples:

Here's some more:

This example illustrates the fact that many locales, such as Georgian and Hindi, do not have code pages, as they are Unicode-only collations. Those collations are not appropriate for columns that use the char, varchar, or text data type

So Georgian or Hindi really need to be stored as nvarchar. Arabic is also a problem:

Another problem you might encounter is the inability to store data when not all of the characters you wish to support are contained in the code page. In many cases, Windows considers a particular code page to be a "best fit" code page, which means there is no guarantee that you can rely on the code page to handle all text; it is merely the best one available. An example of this is the Arabic script: it supports a wide array of languages, including Baluchi, Berber, Farsi, Kashmiri, Kazakh, Kirghiz, Pashto, Sindhi, Uighur, Urdu, and more. All of these languages have additional characters beyond those in the Arabic language as defined in Windows code page 1256. If you attempt to store these extra characters in a non-Unicode column that has the Arabic collation, the characters are converted into question marks.

Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h.

All in all with all the issues you have to deal with when dealing with internalitionalization. It is my opinion that is easier to just use Unicode characters from the start, avoid the extra conversions and take the space hit. Hence my statement earlier.

MySQL select query with multiple conditions

You have conditions that are mutually exclusive - if meta_key is 'first_name', it can't also be 'yearofpassing'. Most likely you need your AND's to be OR's:

$result = mysql_query("SELECT user_id FROM wp_usermeta 
WHERE (meta_key = 'first_name' AND meta_value = '$us_name') 
OR (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') 
OR (meta_key = 'u_city' AND meta_value = '$us_reg') 
OR (meta_key = 'us_course' AND meta_value = '$us_course')")

custom facebook share button

This solution is using javascript to open a new window when a user clicks on your custom share button.

HTML:

<a href="#" onclick="share_fb('http://urlhere.com/test/55d7258b61707022e3050000');return false;" rel="nofollow" share_url="http://urlhere.com/test/55d7258b61707022e3050000" target="_blank">

  //using fontawesome
  <i class="uk-icon-facebook uk-float-left"></i>
    Share
</a>

and in your javascript file. note window.open params are (url, dialogue title, width, height)

function share_fb(url) {
  window.open('https://www.facebook.com/sharer/sharer.php?u='+url,'facebook-share-dialog',"width=626, height=436")
}

How to get param from url in angular 4?

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If this is a node service, try the steps outlined here

Basically, it's a Cross-Origin Resource Sharing (CORS) error. More information about such errors here.

Once I updated my node service with the following lines it worked:

let express = require("express");
let app = express();

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");    
    next();
  });

What does it mean by select 1 from table?

I see it is always used in SQL injection,such as:

www.urlxxxxx.com/xxxx.asp?id=99 union select 1,2,3,4,5,6,7,8,9 from database;

These numbers can be used to guess where the database exists and guess the column name of the database you specified.And the values of the tables.

Calling dynamic function with dynamic number of parameters

Here's what you need:

function mainfunc (){
    window[Array.prototype.shift.call(arguments)].apply(null, arguments);
}

The first argument is used as the function name and all of the remaining ones are used as arguments to the called function...

We're able to use the shift method to return and then delete the first value from the arguments array. Note that we've called it from the Array prototype since, strictly speaking, 'arguments' is not a real array and so doesn't inherit the shift method like a regular array would.


You can also call the shift method like this:

[].shift.call(arguments);

Javascript - remove an array item by value

You can use lodash.js

_.pull(arrayName,valueToBeRemove);

In your case :- _.pull(id_tag,90);

Paste a multi-line Java String in Eclipse

You can use this Eclipse Plugin: http://marketplace.eclipse.org/node/491839#.UIlr8ZDwCUm This is a multi-line string editor popup. Place your caret in a string literal press ctrl-shift-alt-m and paste your text.

Can I write or modify data on an RFID tag?

We have recently started looking into RFID solutions at my work place and we found a cheap solution for testing purposes.

One of the units from here:

http://www.sdid.com/products.shtml

Plugs into any windows mobile device with an SD slot and allows reading / writing. There is also a development kit to get you on your way with your own apps.

Hope this helps

What is the difference between primary, unique and foreign key constraints, and indexes?

  1. A primary key is a column or a set of columns that uniquely identify a row in a table. A primary key should be short, stable and simple. A foreign key is a column (or set of columns) in a second table whose value is required to match the value of the primary key in the original table. Usually a foreign key is in a table that is different from the table whose primary key is required to match. A table can have multiple foreign keys.
  2. The primary key cannot accept null values. Foreign keys can accept multiple.
  3. We can have only one primary key in a table. We can have more than one foreign key in a table.
  4. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. Foreign keys do not automatically create an index, clustered or non-clustered. You can manually create an index on a foreign key.

Font size of TextView in Android application changes on changing font size from native settings

this may help. add the code in your custom Application or BaseActivity

/**
 * ?? getResource ??,????????
 *
 * @return
 */
@Override
public Resources getResources() {
    Resources resources = super.getResources();
    if (resources != null && resources.getConfiguration().fontScale != 1) {
        Configuration configuration = resources.getConfiguration();
        configuration.fontScale = 1;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    }
    return resources;
}

however, Resource#updateConfiguration is deplicated in API level 25, which means it will be unsupported some day in the future.

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

Return value in SQL Server stored procedure

Try to call your proc in this way:

DECLARE @UserIDout int

EXEC YOURPROC @EmailAddress = 'sdfds', @NickName = 'sdfdsfs', ..., @UserId = @UserIDout OUTPUT

SELECT @UserIDout 

Create own colormap using matplotlib and plot color scale

Since the methods used in other answers seems quite complicated for such easy task, here is a new answer:

Instead of a ListedColormap, which produces a discrete colormap, you may use a LinearSegmentedColormap. This can easily be created from a list using the from_list method.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

x,y,c = zip(*np.random.rand(30,3)*4-2)

norm=plt.Normalize(-2,2)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red","violet","blue"])

plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()

enter image description here


More generally, if you have a list of values (e.g. [-2., -1, 2]) and corresponding colors, (e.g. ["red","violet","blue"]), such that the nth value should correspond to the nth color, you can normalize the values and supply them as tuples to the from_list method.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

x,y,c = zip(*np.random.rand(30,3)*4-2)

cvals  = [-2., -1, 2]
colors = ["red","violet","blue"]

norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)

plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()

enter image description here

Visual Studio move project to a different folder

I had the same problem. I solved with move the references and in less than 15 minutes, without change the references.

For me the solution was simple:

  1. Move your files where you need.
  2. Delete the folder with name .vs. Must be as not visible folder.
  3. Open the solution file (.sln) using a simple editor like note or notepad++.
  4. Change the reference where your file is, using the following structure: if you put your project in the same folder remove the previous folder or the reference "..\"; if you put in a above folder add the reference "..\" or the name of the folder.
  5. Save the file with the changes.
  6. Open the project file (.csproj) and do the same, remove or add the reference.
  7. Save the changes.
  8. Open the solution file.

Examples:

In solution file (.sln)

  • Original: Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.UI", "ScannerPDF\PATH1.UI\PATH1.UI.csproj", "{A26438AD-E428-4AE4-8AB8-A5D6933E2D7B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.DataService", "ScannerPDF\PATH1.DataService\PATH1.DataService.csproj", "{ED5A561B-3674-4613-ADE5-B13661146E2E}"

    New: Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.MX.UI", "PATH1.MX.UI\PATH1.UI.csproj", "{A26438AD-E428-4AE4-8AB8-A5D6933E2D7B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.DataService", "PATH1.DataService\PATH1.DataService.csproj", "{ED5A561B-3674-4613-ADE5-B13661146E2E}"

In project file:

  • Original:

    New:

    Original reference: ....\lib\RCWF\2018.1.220.40\TelerikCommon.dll

    New reference: ..\lib\RCWF\2018.1.220.40\TelerikCommon.dll

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

The operation is not allowed in chrome. You can either use a HTTP server(Tomcat) or you use Firefox instead.

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8, ViewChild always takes 2 param, and second params always has static: true or static: false

You can try like this:

@ViewChild('nameInput', {static: false}) component

Also,the static: false is going to be the default fallback behaviour in Angular 9.

What are static false/true: So as a rule of thumb you can go for the following:

  • { static: true } needs to be set when you want to access the ViewChild in ngOnInit.

    { static: false } can only be accessed in ngAfterViewInit. This is also what you want to go for when you have a structural directive (i.e. *ngIf) on your element in your template.

What are the options for (keyup) in Angular2?

Have hit the same problem today.

These are poorly documented, an open issue exist.

Some for keyup, like space:

<input (keyup.space)="doSomething()">
<input (keyup.spacebar)="doSomething()">  

Some for keydown
(may work for keyup too):

<input (keydown.enter)="...">
<input (keydown.a)="...">
<input (keydown.esc)="...">
<input (keydown.alt)="...">
<input (keydown.shift.esc)="...">
<input (keydown.shift.arrowdown)="...">
<input (keydown.f4)="...">

All above are from below links:

https://github.com/angular/angular/issues/18870
https://github.com/angular/angular/issues/8273
https://github.com/angular/angular/blob/master/packages/platform-browser/src/dom/events/key_events.ts
https://alligator.io/angular/binding-keyup-keydown-events/

How do I calculate square root in Python?

This might be a little late to answer but most simple and accurate way to compute square root is newton's method.

You have a number which you want to compute its square root (num) and you have a guess of its square root (estimate). Estimate can be any number bigger than 0, but a number that makes sense shortens the recursive call depth significantly.

new_estimate = (estimate + num / estimate) / 2

This line computes a more accurate estimate with those 2 parameters. You can pass new_estimate value to the function and compute another new_estimate which is more accurate than the previous one or you can make a recursive function definition like this.

def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num / estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)

For example we need to find 30's square root. We know that the result is between 5 and 6.

newtons_method(30,5)

number is 30 and estimate is 5. The result from each recursive calls are:

5.5
5.477272727272727
5.4772255752546215
5.477225575051661

The last result is the most accurate computation of the square root of number. It is the same value as the built-in function math.sqrt().

Calculate text width with JavaScript

The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.

function textWidth(text, fontProp) {
    var tag = document.createElement("div");
    tag.style.position = "absolute";
    tag.style.left = "-999em";
    tag.style.whiteSpace = "nowrap";
    tag.style.font = fontProp;
    tag.innerHTML = text;

    document.body.appendChild(tag);

    var result = tag.clientWidth;

    document.body.removeChild(tag);

    return result;
}

Usage:

if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

Sometimes you just need to suppress only some warnings and you want to keep other warnings, just to be safe. In your code, you can suppress the warnings for variables and even formal parameters by using GCC's unused attribute. Lets say you have this code snippet:

void func(unsigned number, const int version)
{
  unsigned tmp;
  std::cout << number << std::endl;
}

There might be a situation, when you need to use this function as a handler - which (imho) is quite common in C++ Boost library. Then you need the second formal parameter version, so the function's signature is the same as the template the handler requires, otherwise the compilation would fail. But you don't really need it in the function itself either...

The solution how to mark variable or the formal parameter to be excluded from warnings is this:

void func(unsigned number, const int version __attribute__((unused)))
{
  unsigned tmp __attribute__((unused));
  std::cout << number << std::endl;
}

GCC has many other parameters, you can check them in the man pages. This also works for the C programs, not only C++, and I think it can be used in almost every function, not just handlers. Go ahead and try it! ;)

P.S.: Lately I used this to suppress warnings of Boosts' serialization in template like this:

template <typename Archive>
void serialize(Archive &ar, const unsigned int version __attribute__((unused)))

EDIT: Apparently, I didn't answer your question as you needed, drak0sha done it better. It's because I mainly followed the title of the question, my bad. Hopefully, this might help other people, who get here because of that title... :)

Difference between SRC and HREF

HREF: Is a REFerence to information for the current page ie css info for the page style or link to another page. Page Parsing is not stopped.

SRC: Is a reSOURCE to be added/loaded to the page as in images or javascript. Page Parsing may stop depending on the coded attribute. That is why it's better to add script just before the ending body tag so that page rendering is not held up.

How to lose margin/padding in UITextView?

Building off some of the good answers already given, here is a purely Storyboard / Interface Builder-based solution that works in iOS 7.0+

Set the UITextView's User Defined Runtime Attributes for the following keys:

textContainer.lineFragmentPadding
textContainerInset

Interface Builder

object==null or null==object?

This also closely relates to:

if ("foo".equals(bar)) {

which is convenient if you don't want to deal with NPEs:

if (bar!=null && bar.equals("foo")) {

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

CodeIgniter Active Record not equal

According to the manual this should work:

Custom key/value method:

You can include an operator in the first parameter in order to control the comparison:

$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45

Search for $this->db->where(); and look at item #2.

Creating a Plot Window of a Particular Size

As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:

If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

How to escape strings in SQL Server using PHP?

After struggling with this for hours, I've come up with a solution that feels almost the best.

Chaos' answer of converting values to hexstring doesn't work with every datatype, specifically with datetime columns.

I use PHP's PDO::quote(), but as it comes with PHP, PDO::quote() is not supported for MS SQL Server and returns FALSE. The solution for it to work was to download some Microsoft bundles:

After that you can connect in PHP with PDO using a DSN like the following example:

sqlsrv:Server=192.168.0.25; Database=My_Database;

Using the UID and PWD parameters in the DSN didn't worked, so username and password are passed as the second and third parameters on the PDO constructor when creating the connection. Now you can use PHP's PDO::quote(). Enjoy.

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

I got the solution for onunload in all browsers except Opera by changing the Ajax asynchronous request into synchronous request.

xmlhttp.open("POST","LogoutAction",false);

It works well for all browsers except Opera.

How can I format a nullable DateTime with ToString()?

Shortest answer

$"{dt:yyyy-MM-dd hh:mm:ss}"

Tests

DateTime dt1 = DateTime.Now;
Console.Write("Test 1: ");
Console.WriteLine($"{dt1:yyyy-MM-dd hh:mm:ss}"); //works

DateTime? dt2 = DateTime.Now;
Console.Write("Test 2: ");
Console.WriteLine($"{dt2:yyyy-MM-dd hh:mm:ss}"); //Works

DateTime? dt3 = null;
Console.Write("Test 3: ");
Console.WriteLine($"{dt3:yyyy-MM-dd hh:mm:ss}"); //Works - Returns empty string

Output
Test 1: 2017-08-03 12:38:57
Test 2: 2017-08-03 12:38:57
Test 3: 

Gradle DSL method not found: 'runProguard'

runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.

To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.

enter image description here

How do I check if a given string is a legal/valid file name under Windows?

Rather than explicitly include all possible characters, you could do a regex to check for the presence of illegal characters, and report an error then. Ideally your application should name the files exactly as the user wishes, and only cry foul if it stumbles across an error.

How to add a tooltip to an svg graphic?

I came up with something using HTML + CSS only. Hope it works for you

_x000D_
_x000D_
.mzhrttltp {
  position: relative;
  display: inline-block;
}
.mzhrttltp .hrttltptxt {
  visibility: hidden;
  width: 120px;
  background-color: #040505;
  font-size:13px;color:#fff;font-family:IranYekanWeb;
  text-align: center;
  border-radius: 3px;
  padding: 4px 0;
  position: absolute;
  z-index: 1;
  top: 105%;
  left: 50%;
  margin-left: -60px;
}

.mzhrttltp .hrttltptxt::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent #040505 transparent;
}

.mzhrttltp:hover .hrttltptxt {
  visibility: visible;
}
_x000D_
<div class="mzhrttltp"><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#e2062c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg><div class="hrttltptxt">?????&zwnj;????&zwnj;??</div></div>
_x000D_
_x000D_
_x000D_

What's the difference between primitive and reference types?

As many have stated more or less correctly what reference and primitive types are, one might be interested that we have some more relevant types in Java. Here is the complete lists of types in java (as far as I am aware of (JDK 11)).

Primitive Type

Describes a value (and not a type).

11

Reference Type

Describes a concrete type which instances extend Object (interface, class, enum, array). Furthermore TypeParameter is actually a reference type!

Integer

Note: The difference between primitive and reference type makes it necessary to rely on boxing to convert primitives in Object instances and vise versa.

Note2: A type parameter describes a type having an optional lower or upper bound and can be referenced by name within its context (in contrast to the wild card type). A type parameter typically can be applied to parameterized types (classes/interfaces) and methods. The parameter type defines a type identifier.

Wildcard Type

Expresses an unknown type (like any in TypeScript) that can have a lower or upper bound by using super or extend.

? extends List<String>
? super ArrayList<String>

Void Type

Nothingness. No value/instance possible.

void method();

Null Type

The only representation is 'null'. It is used especially during type interference computations. Null is a special case logically belonging to any type (can be assigned to any variable of any type) but is actual not considered an instance of any type (e.g. (null instanceof Object) == false).

null

Union Type

A union type is a type that is actual a set of alternative types. Sadly in Java it only exists for the multi catch statement.

catch(IllegalStateException | IOException e) {}

Interference Type

A type that is compatibile to multiple types. Since in Java a class has at most one super class (Object has none), interference types allow only the first type to be a class and every other type must be an interface type.

void method(List<? extends List<?> & Comparable> comparableList) {}

Unknown Type

The type is unknown. That is the case for certain Lambda definitions (not enclosed in brackets, single parameter).

list.forEach(element -> System.out.println(element.toString)); //element is of unknown type

Var Type

Unknown type introduced by a variable declaration spotting the 'var' keyword.

var variable = list.get(0);

Reverse / invert a dictionary mapping

def invertDictionary(d):
    myDict = {}
  for i in d:
     value = d.get(i)
     myDict.setdefault(value,[]).append(i)   
 return myDict
 print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})

This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}

Passing HTML input value as a JavaScript Function Parameter

You can get the values with use of ID. But ID should be Unique.

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    a = $('#a').val();
    b = $('#b').val();
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

Java 8 lambda Void argument

The syntax you're after is possible with a little helper function that converts a Runnable into Action<Void, Void> (you can place it in Action for example):

public static Action<Void, Void> action(Runnable runnable) {
    return (v) -> {
        runnable.run();
        return null;
    };
}

// Somewhere else in your code
 Action<Void, Void> action = action(() -> System.out.println("foo"));

What is the difference between a web API and a web service?

API and Web service serve as a means of communication.

The only difference is that a Web service facilitates interaction between two machines over a network. An API acts as an interface between two different applications so that they can communicate with each other. An API is a method by which third-party vendors can write programs that interface easily with other programs. A Web service is designed to have an interface that is depicted in a machine-processable format usually specified in Web Service Description Language (WSDL)

All Web services are APIs but not all APIs are Web services.

A Web service is merely an API wrapped in HTTP.


This here article provides good knowledge regarding web service and API.