Programs & Examples On #Web config transform

Web.config transformation lets you easily transform .NET application configuration files.

App.Config Transformation for projects which are not Web Projects in Visual Studio?

I wrote nice extension to automate app.config transformation like the one built in Web Application Project Configuration Transform

The biggest advantage of this extension is that you don’t need to install it on all build machines

SQL sum with condition

Try moving ValueDate:

select sum(CASE  
             WHEN ValueDate > @startMonthDate THEN cash 
              ELSE 0 
           END) 
 from Table a
where a.branch = p.branch 
  and a.transID = p.transID

(reformatted for clarity)

You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.

node and Error: EMFILE, too many open files

I did installing watchman, changing limit etc. and it didn't work in Gulp.

Restarting iterm2 actually helped though.

Get total of Pandas column

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

jQuery animate scroll

var page_url = windws.location.href;
var page_id = page_url.substring(page_url.lastIndexOf("#") + 1);
if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
} else if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
}

});

I want my android application to be only run in portrait mode?

I use

 android:screenOrientation="nosensor"

It is helpful if you do not want to support up side down portrait mode.

WordPress path url in js script file

If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

MySQL 8 changed the default charset to utf8mb4. But some clients don't know this charset. Hence when the server reports its default charset to the client, and the client doesn't know what the server means, it throws this error.

See also https://bugs.mysql.com/bug.php?id=71606

That bug is against the MySQL Connector/C++ so it's affecting more than just PHP.

Okay—I got it to work by changing the character set to utf8, to be compatible with non-upgraded clients. I added this to /etc/my.cnf and restarted mysqld:

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8


[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

I found these settings in an answer from 2010: Change MySQL default character set to UTF-8 in my.cnf?

how to add css class to html generic control div?

I think the answer of Curt is correct, however, what if you want to add a class to a div that already has a class declared in the ASP.NET code.

Here is my solution for that, it is a generic method so you can call it directly as this:

Asp Net Div declaration:

<div id="divButtonWrapper" runat="server" class="text-center smallbutton fixPad">

Code to add class:

divButtonWrapper.AddClassToHtmlControl("nameOfYourCssClass")

Generic class:

public static class HtmlGenericControlExtensions
{
    public static void AddClassToHtmlControl(this HtmlGenericControl htmlGenericControl, string className)
    {
        if (string.IsNullOrWhiteSpace(className))
            return;

        htmlGenericControl
            .Attributes.Add("class", string.Join(" ", htmlGenericControl
            .Attributes["class"]
            .Split(' ')
            .Except(new[] { "", className })
            .Concat(new[] { className })
            .ToArray()));
    }
}

how to convert current date to YYYY-MM-DD format with angular 2

Example as per doc

@Component({
  selector: 'date-pipe',
  template: `<div>
    <p>Today is {{today | date}}</p>
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
    <p>The time is {{today | date:'jmZ'}}</p>
  </div>`
})
export class DatePipeComponent {
  today: number = Date.now();
}

Template

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mmss' }}        // output is '43:11'
{{dateObj  | date: 'dd/MM/yyyy'}} // 15/06/2015

To Use in your component.

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need. 
  }
}

In your app.module.ts

providers: [DatePipe,...] 

all you have to do is use this service now.

Integrating the ZXing library directly into my Android application

I tried all possible ways to achieve this and then I discovered Minified version of xZing by JourneyApps. I have ported that for eclipse and shared on GitHub.

If you are using eclipse use this project:-

https://github.com/hiteshsahu/XZing-Barcode-Scanner-Minified-Eclipse

If you are using Studio use this project :-

https://github.com/journeyapps/zxing-android-embedded

Advantages

  1. Inbuilt Barcode scanner in your App do not required to install third party apps using playstore.

  2. You dont need to get confused between Core,Android client etc jars simply drop this packages and relevent layouts in your project and you are good to go. Only Jar required is com.google.zxing:core:3.2.0 which you can download from

    http://mvnrepository.com/artifact/com.google.zxing/core/3.2.0

  3. No need to add tons of packages see images below for comparison

Before :-

enter image description here

After :-

enter image description here

  1. Most important part is they are highly customizable ie. you can add flash light, use it in fragment and support orientation change.

  2. You can use this Capture activity in Cordova App for barcode scanneing.

your capture activity in app manifest would look like this

  <activity
            android:name="com.journeyapps.barcodescanner.CaptureActivity"
            android:clearTaskOnLaunch="true"
            android:configChanges="orientation|keyboardHidden"
            android:exported="false"
            android:screenOrientation="fullSensor"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden" >
            <intent-filter>
                <action android:name="com.google.zxing.client.android.SCAN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

and plugin will look like this

public class BarcodeScanner extends CordovaPlugin {
    public static final int REQUEST_CODE = 0x0ba7c0de;

    private static final String SCAN = "scan";
    private static final String CANCELLED = "cancelled";
    private static final String FORMAT = "format";
    private static final String TEXT = "text";
    private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN";

    private static final String LOG_TAG = "BarcodeScanner";

    private CallbackContext callbackContext;

    /**
     * Constructor.
     */
    public BarcodeScanner() {


    }

    /**
     * Executes the request.
     *
     * This method is called from the WebView thread. To do a non-trivial amount of work, use:
     *     cordova.getThreadPool().execute(runnable);
     *
     * To run on the UI thread, use:
     *     cordova.getActivity().runOnUiThread(runnable);
     *
     * @param action          The action to execute.
     * @param args            The exec() arguments.
     * @param callbackContext The callback context used when calling back into JavaScript.
     * @return                Whether the action was valid.
     *
     * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
     */
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
        this.callbackContext = callbackContext;
        if (action.equals(SCAN)) {
            scan(args);
        } else {
            return false;
        }
        return true;
    }

    /**
     * Starts an intent to scan and decode a barcode.
     */
    public void scan(JSONArray args) {
        Intent intentScan = new Intent(SCAN_INTENT);
        intentScan.addCategory(Intent.CATEGORY_DEFAULT);

        // add config as intent extras
        if(args.length() > 0) {

            JSONObject obj;
            JSONArray names;
            String key;
            Object value;

            for(int i=0; i<args.length(); i++) {

                try {
                    obj = args.getJSONObject(i);
                } catch(JSONException e) {
                    Log.i("CordovaLog", e.getLocalizedMessage());
                    continue;
                }

                names = obj.names();
                for(int j=0; j<names.length(); j++) {
                    try {
                        key = names.getString(j);
                        value = obj.get(key);

                        if(value instanceof Integer) {
                            intentScan.putExtra(key, (Integer)value);
                        } else if(value instanceof String) {
                            intentScan.putExtra(key, (String)value);
                        }

                    } catch(JSONException e) {
                        Log.i("CordovaLog", e.getLocalizedMessage());
                        continue;
                    }
                }
            }

        }

        // avoid calling other phonegap apps
        intentScan.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());

        this.cordova.startActivityForResult((CordovaPlugin) this, intentScan, REQUEST_CODE);
    }

    /**
     * Called when the barcode scanner intent completes.
     *
     * @param requestCode The request code originally supplied to startActivityForResult(),
     *                       allowing you to identify who this result came from.
     * @param resultCode  The integer result code returned by the child activity through its setResult().
     * @param intent      An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                JSONObject obj = new JSONObject();
                try {
                    obj.put(TEXT, intent.getStringExtra("SCAN_RESULT"));
                    obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT"));
                    obj.put(CANCELLED, false);
                } catch (JSONException e) {
                    Log.d(LOG_TAG, "JSONException "+e.getMessage());
                }
                this.callbackContext.success(obj);
            } else if (resultCode == Activity.RESULT_CANCELED) {
                this.callbackContext.success("");
            } else {
                this.callbackContext.error("Technical Problem");
            }
        }
    }
}

Happy Integration !!

Git merge with force overwrite

I had a similar issue, where I needed to effectively replace any file that had changes / conflicts with a different branch.

The solution I found was to use git merge -s ours branch.

Note that the option is -s and not -X. -s denotes the use of ours as a top level merge strategy, -X would be applying the ours option to the recursive merge strategy, which is not what I (or we) want in this case.

Steps, where oldbranch is the branch you want to overwrite with newbranch.

  • git checkout newbranch checks out the branch you want to keep
  • git merge -s ours oldbranch merges in the old branch, but keeps all of our files.
  • git checkout oldbranch checks out the branch that you want to overwrite
  • get merge newbranch merges in the new branch, overwriting the old branch

How to clear the entire array?

ReDim aFirstArray(0)

This will resize the array to zero and erase all data.

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

Is there a way to run Bash scripts on Windows?

Best option? Windows 10. Native Bash support!

How to convert date to timestamp in PHP?

Using strtotime() function you can easily convert date to timestamp

<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');

//define date and time
$date = date("d M Y H:i:s");

// output
echo strtotime($date);
?> 

More info: http://php.net/manual/en/function.strtotime.php

Online conversion tool: http://freeonlinetools24.com/

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

First please check in module.ts file that in @NgModule all properties are only one time. If any of are more than one time then also this error come. Because I had also occur this error but in module.ts file entryComponents property were two time that's why I was getting this error. I resolved this error by removing one time entryComponents from @NgModule. So, I recommend that first you check it properly.

How can I hide a checkbox in html?

Elements that are not being rendered (be it through visibility: hidden, display: none, opacity: 0.0, whatever) will not indicate focus. The browser will not draw a focus border around nothing.

If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex property:

<label tabindex="0" class="checkbox">
  <input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>

Fiddle

In this case, the <label> tag above is actually receiving focus and everything within it will have a focus border when it's in focus.

I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" /> tag instead.

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

get everything between <tag> and </tag> with php

To retrieve or delete the content of a script tag, even with special cases like <script async>.

$str = '
Some js embed
<script async>
  alert("js")
  let job, origin = new Date().getTime()
</script>
<span id="OUT"></span>
<button onclick="alert()">RESET</button>
timer experiment
';

$reg = '/<script([\s\S]*)<\/script>/';

preg_match($reg, $str, $matches);
$match = substr($matches[0], (strpos($matches[0], ">")+1));
$match = str_replace("</script>", "", $match);
echo $match;
/* OUTPUT
  alert("js")
  let job, origin = new Date().getTime()
*/
echo "\n---------------------\n";
echo preg_replace($reg, "DELETED", $str);
/* OUTPUT
  Some js embed
  DELETED
  <span id="OUT"></span>
  <button onclick="alert()">RESET</button>
  timer experiment
*/

Oracle pl-sql escape character (for a " ' ")

Your question implies that you're building the INSERT statement up by concatenating strings together. I suggest that this is a poor choice as it leaves you open to SQL injection attacks if the strings are derived from user input. A better choice is to use parameter markers and to bind the values to the markers. If you search for Oracle parameter markers you'll probably find some information for your specific implementation technology (e.g. C# and ADO, Java and JDBC, Ruby and RubyDBI, etc).

Share and enjoy.

How can I check if given int exists in array?

I think you are looking for std::any_of, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)

int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
    return i == val;
});

If you want to know where the element is, std::find will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).

int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
    // not found
}
else
{
    // found
}

Adding a line break in MySQL INSERT INTO text

In SQL or MySQL you can use the char or chr functions to enter in an ASCII 13 for carriage return line feed, the \n equivilent. But as @David M has stated, you are most likely looking to have the HTML show this break and a br is what will work.

How to get access to raw resources that I put in res folder?

In some situations we have to get image from drawable or raw folder using image name instead if generated id

// Image View Object 
        mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for  to Fetch  image from resourse 
Context mContext=getApplicationContext();

// getResources().getIdentifier("image_name","res_folder_name", package_name);

// find out below example 
    int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());

// now we will get contsant id for that image       
        mIv.setBackgroundResource(i);

SQL: how to use UNION and order by a specific select?

Using @Adrian tips, I found a solution:

I'm using GROUP BY and COUNT. I tried to use DISTINCT with ORDER BY but I'm getting error message: "not a SELECTed expression"

select id from 
(
    SELECT id FROM a -- returns 1,4,2,3
    UNION ALL -- changed to ALL
    SELECT id FROM b -- returns 2,1
)
GROUP BY id ORDER BY count(id);

Thanks Adrian and this blog.

Fastest way to count number of occurrences in a Python list

By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.

If our python list is:-

l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']

To find occurrence of every items in the python list use following:-

\>>from collections import Counter

\>>c=Counter(l)

\>>print c

Counter({'1': 6, '2': 4, '7': 3, '10': 2})

To find most/highest occurrence of items in the python list:-

\>>k=c.most_common()

\>>k

[('1', 6), ('2', 4), ('7', 3), ('10', 2)]

For Highest one:-

\>>k[0][1]

6

For the item just use k[0][0]

\>>k[0][0]

'1'

For nth highest item and its no of occurrence in the list use follow:-

**for n=2 **

\>>print k[n-1][0] # For item

2

\>>print k[n-1][1] # For value

4

Xcode 7.2 no matching provisioning profiles found

I also had some problems after updating Xcode.

I fixed it by opening Xcode Preferences (?+,), going to AccountsView Details. Then select all provisioning profiles and delete them with backspace (note: they can't be removed in Xcode 7.2). Restart Xcode, else the list doesn't seem to update properly.

Now click the Download all button, and you should have all provisioning profiles that you defined in the Member center back in Xcode. Don't worry about the Xcode-generated ones (Prefixed with XC:), Xcode will regenerate them if necessary. Restart Xcode again.

Now go to the Code Signing section in your Build Settings and select the correct profile and cert.

Why this happens at all? No idea... I gave up on understanding Apple's policies regarding app signing.

Downloading MySQL dump from command line

If downloading from remote server, here is a simple example:

mysqldump -h my.address.amazonaws.com -u my_username -p db_name > /home/username/db_backup_name.sql

The -p indicates you will enter a password, it does not relate to the db_name. After entering the command you will be prompted for the password. Type it in and press enter.

How can I divide two integers to get a double?

I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

CentOS: Enabling GD Support in PHP Installation

CentOs 6.5+ & PHP 5.6:

sudo yum install php56-gd

service httpd restart

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

Is there a way to perform "if" in python's lambda

Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like and, not, or, etc) in their body.

So, there's no way you could use a lambda for your example (because you can't use raise), but if you're willing to concede on that… You could use:

f = lambda x: x == 2 and x or None

Git - What is the difference between push.default "matching" and "simple"

git push can push all branches or a single one dependent on this configuration:

Push all branches

git config --global push.default matching

It will push all the branches to the remote branch and would merge them. If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default.

Push only the current branch if its named upstream is identical

git config --global push.default simple

So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

Laravel Query Builder where max id

You should be able to perform a select on the orders table, using a raw WHERE to find the max(id) in a subquery, like this:

 \DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();

If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON or toArray will not work without using Eloquent models.

 $order = Order::whereRaw('id = (select max(`id`) from orders)')->get();

That, of course, requires that you have a model that extends Eloquent.

 class Order extends Eloquent {}

As mentioned in the comments, you don't need to use whereRaw, you can do the entire query using the query builder without raw SQL.

 // Using the Query Builder
 \DB::table('orders')->find(\DB::table('orders')->max('id'));

 // Using Eloquent
 $order = Order::find(\DB::table('orders')->max('id'));

(Note that if the id field is not unique, you will only get one row back - this is because find() will only return the first result from the SQL server.).

How can I determine whether a 2D Point is within a Polygon?

Really like the solution posted by Nirg and edited by bobobobo. I just made it javascript friendly and a little more legible for my use:

function insidePoly(poly, pointx, pointy) {
    var i, j;
    var inside = false;
    for (i = 0, j = poly.length - 1; i < poly.length; j = i++) {
        if(((poly[i].y > pointy) != (poly[j].y > pointy)) && (pointx < (poly[j].x-poly[i].x) * (pointy-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) inside = !inside;
    }
    return inside;
}

How to append one file to another in Linux from the shell?

Another solution:

cat file1 | tee -a file2

tee has the benefit that you can append to as many files as you like, for example:

cat file1 | tee -a file2 file3 file3

will append the contents of file1 to file2, file3 and file4.

From the man page:

-a, --append
       append to the given FILEs, do not overwrite

How to install pywin32 module in windows 7

I disagree with the accepted answer being "the easiest", particularly if you want to use virtualenv.

You can use the Unofficial Windows Binaries instead. Download the appropriate wheel from there, and install it with pip:

pip install pywin32-219-cp27-none-win32.whl

(Make sure you pick the one for the right version and bitness of Python).

You might be able to get the URL and install it via pip without downloading it first, but they're made it a bit harder to just grab the URL. Probably better to download it and host it somewhere yourself.

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

Get/pick an image from Android's built-in Gallery app programmatically

Just in case it helps; I do this to get the Bitmap:

InputStream is = context.getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);

How do I check the operating system in Python?

You can get a pretty coarse idea of the OS you're using by checking sys.platform.

Once you have that information you can use it to determine if calling something like os.uname() is appropriate to gather more specific information. You could also use something like Python System Information on unix-like OSes, or pywin32 for Windows.

There's also psutil if you want to do more in-depth inspection without wanting to care about the OS.

Retrieve list of tasks in a queue in Celery

If you control the code of the tasks then you can work around the problem by letting a task trigger a trivial retry the first time it executes, then checking inspect().reserved(). The retry registers the task with the result backend, and celery can see that. The task must accept self or context as first parameter so we can access the retry count.

@task(bind=True)
def mytask(self):
    if self.request.retries == 0:
        raise self.retry(exc=MyTrivialError(), countdown=1)
    ...

This solution is broker agnostic, ie. you don't have to worry about whether you are using RabbitMQ or Redis to store the tasks.

EDIT: after testing I've found this to be only a partial solution. The size of reserved is limited to the prefetch setting for the worker.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

I figured out my own variation of this problem.

The issue was not changing the protocol from https to ssl, but instead, setting the Github global username and email! (I was trying to push to a private repository.

git config --global user.email "[email protected]"

git config --global user.name "Your full name"

Sort list in C# with LINQ

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

IIS AppPoolIdentity and file system write access permissions

I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:

Log Name:      Application
Source:        ASP.NET 4.0.30319.0
Date:          1/5/2012 4:12:33 PM
Event ID:      1314
Task Category: Web Event
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      SALTIIS01

Description:
Event code: 4008 
Event message: File authorization failed for the request. 
Event time: 1/5/2012 4:12:33 PM 
Event time (UTC): 1/6/2012 12:12:33 AM 
Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c 
Event sequence: 7 
Event occurrence: 3 
Event detail code: 0 

Application information: 
    Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 
    Trust level: Full 
    Application Virtual Path: /Application/SNCDW 
    Application Path: D:\Sites\WCF\Application\SNCDW\ 
    Machine name: SALTIIS01 

Process information: 
    Process ID: 1896 
    Process name: w3wp.exe 
    Account name: iisservice 

Request information: 
    Request URL: http://webservicestest/Application/SNCDW/PC.svc 
    Request path: /Application/SNCDW/PC.svc 
    User host address: 10.60.16.79 
    User: js3228 
    Is authenticated: True 
    Authentication Type: Negotiate 
    Thread account name: iisservice 

In the end I had to give the Windows Everyone group read access to that folder to get it to work properly.

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

How can I send emails through SSL SMTP with the .NET Framework?

For gmail these settings worked for me, the ServicePointManager.SecurityProtocol line was necessary. Because I has setup 2 step verification I needed get a App Password from google app password generator.

SmtpClient mailer = new SmtpClient();
mailer.Host = "smtp.gmail.com";
mailer.Port = 587;
mailer.EnableSsl = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Installing mysqlclient using anaconda is pretty simple and straight forward.

conda install -c bioconda mysqlclient

and then, install pymysql using pip.

pip install pymysql

happy learning..

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

I am on XAMPP on Mac OS X, and Brian Lowe's solution above worked with a slight modification.

The mysql.sock file is actually in "/Applications/xampp/xamppfiles/var/mysql/" folder. So had to link it up both in /tmp and /var/mysql. I haven't checked which one is used by PHP command line, but this did the fix, so I am happy :-)

sudo su
ln -s /Applications/xampp/xamppfiles/var/mysql/mysql.sock /tmp/mysql.sock
mkdir /var/mysql
ln -s /Applications/xampp/xamppfiles/var/mysql/mysql.sock /var/mysql/mysql.sock

symfony2 twig path with parameter url creation

Make sure your routing.yml file has 'id' specified in it. In other words, it should look like:

_category:
    path: /category/{id}

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

It seems like there may be a issue to dump numpy.int64 into json string in Python 3 and the python team already have a conversation about it. More details can be found here.

There is a workaround provided by Serhiy Storchaka. It works very well so I paste it here:

def convert(o):
    if isinstance(o, numpy.int64): return int(o)  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

How do I use a regex in a shell script?

To complement the existing helpful answers:

Using Bash's own regex-matching operator, =~, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:

set -- '12-34-5678' # set $1 to sample value

kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match

Note, however, that the caveat re using flavor-specific regex constructs such as \d equally applies: While =~ supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.

To remain portable (in the context of Bash), stick to the POSIX ERE specification.

Note that =~ even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]} array variable.

Further notes:

  • $kREGEX_DATE is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).

  • While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \.

    • E.g., on Linux, where \< is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes does.
  • I've changed variable name REGEX_DATE to kREGEX_DATE (k signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.

HTTP GET in VBS

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.

Spring Boot - Cannot determine embedded database driver class for database type NONE

I had two dependencies with groupId of org.springframework.data, then I removed jpa and kept mongodb only , and it worked!

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
</dependency>

REST / SOAP endpoints for a WCF service

This post has already a very good answer by "Community wiki" and I also recommend to look at Rick Strahl's Web Blog, there are many good posts about WCF Rest like this.

I used both to get this kind of MyService-service... Then I can use the REST-interface from jQuery or SOAP from Java.

This is from my Web.Config:

<system.serviceModel>
 <services>
  <service name="MyService" behaviorConfiguration="MyServiceBehavior">
   <endpoint name="rest" address="" binding="webHttpBinding" contract="MyService" behaviorConfiguration="restBehavior"/>
   <endpoint name="mex" address="mex" binding="mexHttpBinding" contract="MyService"/>
   <endpoint name="soap" address="soap" binding="basicHttpBinding" contract="MyService"/>
  </service>
 </services>
 <behaviors>
  <serviceBehaviors>
   <behavior name="MyServiceBehavior">
    <serviceMetadata httpGetEnabled="true"/>
    <serviceDebug includeExceptionDetailInFaults="true" />
   </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
   <behavior name="restBehavior">
    <webHttp/>
   </behavior>
  </endpointBehaviors>
 </behaviors>
</system.serviceModel>

And this is my service-class (.svc-codebehind, no interfaces required):

    /// <summary> MyService documentation here ;) </summary>
[ServiceContract(Name = "MyService", Namespace = "http://myservice/", SessionMode = SessionMode.NotAllowed)]
//[ServiceKnownType(typeof (IList<MyDataContractTypes>))]
[ServiceBehavior(Name = "MyService", Namespace = "http://myservice/")]
public class MyService
{
    [OperationContract(Name = "MyResource1")]
    [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "MyXmlResource/{key}")]
    public string MyResource1(string key)
    {
        return "Test: " + key;
    }

    [OperationContract(Name = "MyResource2")]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource/{key}")]
    public string MyResource2(string key)
    {
        return "Test: " + key;
    }
}

Actually I use only Json or Xml but those both are here for a demo purpose. Those are GET-requests to get data. To insert data I would use method with attributes:

[OperationContract(Name = "MyResourceSave")]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource")]
public string MyResourceSave(string thing){
    //...

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.

How to validate white spaces/empty spaces? [Angular 2]

Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

In this approach, you have to use FormControl then watch for value changes and then apply your mask to the value. An example should be:

...
form: FormGroup;
...


ngOnInit(){
    this.form.valueChanges
            .map((value) => {
                // Here you can manipulate your value
                value.firstName = value.firstName.trim();
                return value;
            })
            .filter((value) => this.form.valid)
            .subscribe((value) => {
               console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
            });

}

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

Opera Blocker and others check all files/urls in Network. Then compares to the list. It is EasyPrivacy and EasyList. If your file/url in this, your will be ban. Good luck.

So... I find FilterLists for all addBlockers!

How do you UrlEncode without using System.Web?

There's a client profile usable version, System.Net.WebUtility class, present in client profile System.dll. Here's the MSDN Link:

WebUtility

How to sort a data frame by alphabetic order of a character variable in R?

#sort dataframe by col
sort.df <- with(df,  df[order(sortbythiscolumn) , ])

#can also sort by more than one variable: sort by col1 and then by col2
sort2.df <- with(df, df[order(col1, col2) , ])

#sort in reverse order
sort2.df <- with(df, df[order(col1, -col2) , ])

Opacity of background-color, but not the text

I've created that effect on my blog Landman Code.

What I did was

_x000D_
_x000D_
#Header {
  position: relative;
}
#Header H1 {
  font-size: 3em;
  color: #00FF00;
  margin:0;
  padding:0;
}
#Header H2 {
  font-size: 1.5em;
  color: #FFFF00;
  margin:0;
  padding:0;
}
#Header .Background {
  background: #557700;
  filter: alpha(opacity=30);
  filter: progid: DXImageTransform.Microsoft.Alpha(opacity=30);
  -moz-opacity: 0.30;
  opacity: 0.3;
  zoom: 1;
}
#Header .Background * {
  visibility: hidden; // hide the faded text
}
#Header .Foreground {
  position: absolute; // position on top of the background div
  left: 0;
  top: 0;
}
_x000D_
<div id="Header">
  <div class="Background">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
  <div class="Foreground">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

The important thing that every padding/margin and content must be the same in both the .Background as .Foreground.

How to edit default.aspx on SharePoint site without SharePoint Designer

You can always use Sharepoint Solution Generator to create a project and edit in VS2008.

You can find the Generator along with Sharepoint Developer tools.

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

Try doing a complete clean of the target/deployment directory for the app to get rid of any stale library jars. Make a fresh build and check that commons-logging.jar is actually being placed in the correct lib folder. It might not be included when you are building the library for the application.

Disable browser's back button

While i'm looking for the answer myself, "Best Practice" is.... outdated... Just like browsers are.(Really browsers are ugly fossils)

The best/safest solution would be for browsers to implement a method/request where the user can grant the page the ability to control the interface.

Why? Because for my current project i'm building a 100% JavaScript built and controlled interface.. And back button's have no place in my project since there is no page change. (Ie bloody fast and no page-flashes because of a refresh.. Just like a real application!)

I know why the ability to "highjack" the interface isn't there, and i understand it. But atleast we should have the ability to request it from the browser! Now that would truly be "best practice" without the highjack dangers.

But browsers being browsers.. I don't expect anything exiting to happen in this regard.

JSON Naming Convention (snake_case, camelCase or PascalCase)

In this document Google JSON Style Guide (recommendations for building JSON APIs at Google),

It recommends that:

  1. Property names must be camelCased, ASCII strings.

  2. The first character must be a letter, an underscore (_) or a dollar sign ($).

Example:

{
  "thisPropertyIsAnIdentifier": "identifier value"
}

My team follows this convention.

How do I center this form in css?

I css I got no idea but I made that just by centering the form in html something like this:

in css:

form.principal {width:12em;}    
form.principal label { float:left; display:block; clear:both; padding:3px;}
form.principal input { float:left; width:8em;}
form.principal button{clear:both; width:130px; height:50px; margin-top:8px;}

then in html:

<center><form class="principal" method="POST">
<fieldset>
<p><label for="username">User</label><input id="username" type="text" name="username" />
<p><label for="password">Password</label><input id="password" type="password" name="password" /></p>
<button>Log in</button>
</fieldset>
</form></center>

This will center the form, and the content will be in the left of the centered form.

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

We had the same issue with our ClickOnce application that uses Interop with Microsoft Office. It happened only on a few computers in the company.

The best fix we found out was to modify MS Office installation on problematic computers (through the Programs and Features panel) and ensure that ".NET programmability feature" (not sure of the name of the component - our Microsoft_Office versions are not English) was installed for each of the MS Office applications (Excel, Word, Outlook, etc.). This seems to not be included in a default install.

Then the problem with stdole.dll was fixed.

I hope this might help.

Using the "start" command with parameters passed to the started program

Change The "Virtual PC.exe" to a name without space like "VirtualPC.exe" in the folder. When you write start "path" with "" the CMD starts a new cmd window with the path as the title. Change the name to a name without space,write this on Notepad and after this save like Name.cmd or Name.bat:

CD\
CD Program Files
CD Microsoft Virtual PC
start VirtualPC.exe
timeout 2
exit

This command will redirect the CMD to the folder,start the VirualPC.exe,wait 2 seconds and exit.

How to get UTC+0 date in Java 8?

1 line solution in Java 8:

public Date getCurrentUtcTime() {
    return Date.from(Instant.now());
}

Check if a string within a list contains a specific string with Linq

LINQ Any() would do the job:

bool contains = myList.Any(s => s.Contains(pattern));

Any(), MSDN:

Determines whether any element of a sequence satisfies a condition

SSL InsecurePlatform error when using Requests package

All of the solutions given here haven't helped (I'm constrained to python 2.6.6). I've found the answer in a simple switch to pass to pip:

$ sudo pip install --trusted-host pypi.python.org <module_name>

This tells pip that it's OK to grab the module from pypi.python.org.

For me, the issue is my company's proxy behind it's firewall that makes it look like a malicious client to some servers. Hooray security.


Update: See @Alex 's answer for changes in the PyPi domains, and additional --trusted-host options that can be added. (I'd copy/paste here, but his answer, so +1 him)

Pandas read_csv from url

In the latest version of pandas (0.19.2) you can directly pass the url

import pandas as pd

url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
c=pd.read_csv(url)

Angular 2 - View not updating after model changes

In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:

  • ChangeDetectorRef.detectChanges()
  • ChangeDetectorRef.markForCheck()
  • ApplicationRef.tick()

How to select data of a table from another database in SQL Server?

Try using OPENDATASOURCE The syntax is like this:

select * from OPENDATASOURCE ('SQLNCLI', 'Data Source=192.168.6.69;Initial Catalog=AnotherDatabase;Persist Security Info=True;User ID=sa;Password=AnotherDBPassword;MultipleActiveResultSets=true;' ).HumanResources.Department.MyTable    

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

If you want to find interactively logged on users, I found a great tip here :https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/ (Win32_ComputerSystem did not help me)

$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
    "No explorer process found / Nobody interactively logged on"
}
Else
{
    ForEach ($i in $explorerprocesses)
    {
        $Username = $i.GetOwner().User
        $Domain = $i.GetOwner().Domain
        Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
    }
}

First Heroku deploy failed `error code=H10`

I just had a similar issue with my app, I got the issue after a migration of the DB, after trying many options, the one that helped me was this:

heroku restart

(Using Heroku toolbelt for mac)

How to make a div fill a remaining horizontal space?

Since this is a rather popular question, I'm inclined to share a nice solution using BFC.
Codepen sample of the following here.

.left {
  float: left;
  width: 100px;
}
.right {
  overflow: auto;
}

In this case, overflow: auto triggers context behavior and makes the right element expand only to the available remaining width and it will naturally expand to full width if .left disappears. A highly useful and clean trick for many UI layouts, but perhaps hard to understand the "why it works" at first.

Declaring array of objects

You can instantiate an array of "object type" in one line like this (just replace new Object() with your object):

var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });

Webpack not excluding node_modules

try this below solution:

exclude:path.resolve(__dirname, "node_modules")

Catch checked change event of a checkbox

For JQuery 1.7+ use:

$('input[type=checkbox]').on('change', function() {
  ...
});

How to increase editor font size?

In my case it was because of my 4K screen too thin to read. Then u need to change from monospace In my case it was because of my 4K screen too thin to read. Then u need to change from Monospaced to Consolas.

Settings --> Color Scheme Font --> Font --> Consolas

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';

Remove quotes (') after ALTER USER and keep quote (') after mysql_native_password BY

It is working for me also.

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Calculate percentage saved between two numbers?

I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:

(1 - (oldNumber / newNumber)) * 100

So, the percentage difference from 30 to 40 is:

(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)

The percentage difference from 40 to 30 is:

(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)

In php, I use a function like this:

function calculatePercentage($oldFigure, $newFigure) {
        if (($oldFigure != 0) && ($newFigure != 0)) {
            $percentChange = (1 - $oldFigure / $newFigure) * 100;
        }
        else {
            $percentChange = null;
        }
        return $percentChange;
}

Ping all addresses in network, windows

for /l %%a in (254, -1, 1) do ( 
    for /l %%b in (1, 1, 254) do (
        for %%c in (20, 168) do (
            for %%e in (172, 192) do (
                ping /n 1 %%e.%%c.%%b.%%a>>ping.txt
            )
        )
    )
)
pause>nul

Invalid application path

I was also getting this error. The problem for me turned out to be that I had two separate websites on the machine, and I had not designated which address went to which website. To resolve this, go to IIS Manager -> Select Web Site -> Bindings -> Add... -> Enter the host name that you want to resolve for this website. Repeat for any other websites on the machine.

HTH. Rick

Wordpress plugin install: Could not create directory

To solve permission issue on plugins and themes on localhost or production quickly, you just run this

sudo chmod 757 wp-content/themes
sudo chmod 757 wp-content/plugins

if take care permission on production, you can run

sudo chown -R www-data:www-data wp-content/themes
sudo chown -R www-data:www-data wp-content/plugins

Reportviewer tool missing in visual studio 2017 RC

Update: this answer works with both ,Visual Sudio 2017 and 2019

For me it worked by the following three steps:

  1. Updating Visual Studio to the latest build.
  2. Adding Report / Report Wizard to the Add/New Item menu by:
    • Going to Visual Studio menu Tools/Extensions and Updates
    • Choose Online from the left panel.
    • Search for Microsoft Rdlc Report Designer for Visual Studio
    • Download and install it.
  3. Adding Report viewer control by:

    • Going to NuGet Package Manager.

    • Installing Microsoft.ReportingServices.ReportViewerControl.Winforms

    • Go to the folder that contains Microsoft.ReportViewer.WinForms.dll: %USERPROFILE%\.nuget\packages\microsoft.reportingservices.reportviewercontrol.winforms\140.1000.523\lib\net40
    • Drag the Microsoft.ReportViewer.WinForms.dll file and drop it at Visual Studio Toolbox Window.

For WebForms applications:

  1. The same.
  2. The same.
  3. Adding Report viewer control by:

    • Going to NuGet Package Manager.

    • Installing Microsoft.ReportingServices.ReportViewerControl.WebForms

    • Go to the folder that contains Microsoft.ReportViewer.WebForms.dll file: %USERPROFILE%\.nuget\packages\microsoft.reportingservices.reportviewercontrol.webforms\140.1000.523\lib\net40
    • Drag the Microsoft.ReportViewer.WebForms.dll file and drop it at Visual Studio Toolbox Window.

That's all!

Getting attributes of Enum's value

This should do what you need.

var enumType = typeof(FunkyAttributesEnum);
var memberInfos = enumType.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == enumType);
var valueAttributes = 
      enumValueMemberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
var description = ((DescriptionAttribute)valueAttributes[0]).Description;

Sublime Text 2: How do I change the color that the row number is highlighted?

If you have SublimeLinter installed, your theme (at least it ST3) may end up in .../Packages/User/SublimeLinter/[ your-chosen-theme ]

As mentioned above - find the nested 'settings' dict and edit or add the 'lineHighlight' entry with your desired #RRGGBB or #RRGGBBAA. I like #0000AA99 when on a black(ish) background.

Handy tool if you do not know your color combinations: RGBtoHEX and HEXtoRGB

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

How to check if variable's type matches Type stored in a variable

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

or

 u.GetType.Equals(typeof(User));

should do it. Obviously you could use '==' to do your comparison if you prefer.

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

Bootstrap: wider input field

In bootstrap 4, they have designed a bigger input file.

A simple solution to increase the size input file is to use font-size:

Add you style, for example:

input[type="file"] {
  font-size:35px
}

Otherwise, you can make one custom class and add to input control.

How To: Execute command line in C#, get STD OUT results

// usage
const string ToolFileName = "example.exe";
string output = RunExternalExe(ToolFileName);

public string RunExternalExe(string filename, string arguments = null)
{
    var process = new Process();

    process.StartInfo.FileName = filename;
    if (!string.IsNullOrEmpty(arguments))
    {
        process.StartInfo.Arguments = arguments;
    }

    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.UseShellExecute = false;

    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    var stdOutput = new StringBuilder();
    process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.

    string stdError = null;
    try
    {
        process.Start();
        process.BeginOutputReadLine();
        stdError = process.StandardError.ReadToEnd();
        process.WaitForExit();
    }
    catch (Exception e)
    {
        throw new Exception("OS error while executing " + Format(filename, arguments)+ ": " + e.Message, e);
    }

    if (process.ExitCode == 0)
    {
        return stdOutput.ToString();
    }
    else
    {
        var message = new StringBuilder();

        if (!string.IsNullOrEmpty(stdError))
        {
            message.AppendLine(stdError);
        }

        if (stdOutput.Length != 0)
        {
            message.AppendLine("Std output:");
            message.AppendLine(stdOutput.ToString());
        }

        throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + message);
    }
}

private string Format(string filename, string arguments)
{
    return "'" + filename + 
        ((string.IsNullOrEmpty(arguments)) ? string.Empty : " " + arguments) +
        "'";
}

How to find my realm file?

Under Tools -> Android Device Monitor

And under File Explorer. Search for the apps. And the file is under data/data.

How do you create a Spring MVC project in Eclipse?

This is the easiest way :

step 1) install Spring Tool Suite (STS) for eclipse (version 3.7.0RELEASE or above) To do this you can go to Help >> eclipse market place , then type Spring Tool suite in search box.

step 2) now go to file >> new >> spring project as shown in the image below enter image description here

step 3)now choose the template as "spring MVC Project" and give a name to your project on the top as shown below ( I named it 'SpringProject') enter image description here

step 4)now give a base package name like this enter image description here

and that is . The project will be created in a few minutes and Now you can right click on it and run on server.

What is the minimum I have to do to create an RPM file?

Process of generating RPM from source file:

  1. download source file with.gz extention.
  2. install rpm-build and rpmdevtools from yum install. (rpmbuild folder will be generated...SPECS,SOURCES,RPMS.. folders will should be generated inside the rpmbuild folder).
  3. copy the source code.gz to SOURCES folder.(rpmbuild/SOURCES)
  4. Untar the tar ball by using the following command. go to SOURCES folder :rpmbuild/SOURCES where tar file is present. command: e.g tar -xvzf httpd-2.22.tar.gz httpd-2.22 folder will be generated in the same path.
  5. go to extracted folder and then type below command: ./configure --prefix=/usr/local/apache2 --with-included-apr --enable-proxy --enable-proxy-balancer --with-mpm=worker --enable-mods-static=all (.configure may vary according to source for which RPM has to built-- i have done for apache HTTPD which needs apr and apr-util dependency package).
  6. run below command once the configure is successful: make
  7. after successfull execution od make command run: checkinstall in tha same folder. (if you dont have checkinstall software please download latest version from site) Also checkinstall software has bug which can be solved by following way::::: locate checkinstallrc and then replace TRANSLATE = 1 to TRANSLATE=0 using vim command. Also check for exclude package: EXCLUDE="/selinux"
  8. checkinstall will ask for option (type R if you want tp build rpm for source file)
  9. Done .rpm file will be built in RPMS folder inside rpmbuild/RPMS file... ALL the BEST ....

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

How to put two divs on the same line with CSS in simple_form in rails?

Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.

.left {
  float: left;
  width: 125px;
  text-align: right;
  margin: 2px 10px;
  display: inline;
}

.right {
  float: left;
  text-align: left;
  margin: 2px 10px;
  display: inline;
}

How to Make A Chevron Arrow Using CSS?

Here's a different approach:

1) Use the multiplication character: &times; ×

2) Hide half of it with overflow:hidden

3) Then add a triangle as a pseudo element for the tip.

The advantage here is that no transforms are necessary. (It will work in IE8+)

FIDDLE

_x000D_
_x000D_
.arrow {_x000D_
  position: relative;_x000D_
}_x000D_
.arrow:before {_x000D_
  content: '×';_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  font-size: 240px;_x000D_
  font-weight: bold;_x000D_
  font-family: verdana;_x000D_
  width: 103px;_x000D_
  height: 151px;_x000D_
  overflow: hidden;_x000D_
  line-height: 117px;_x000D_
}_x000D_
.arrow:after {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  left: 101px;_x000D_
  top: 51px;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border-style: solid;_x000D_
  border-width: 25px 0 25px 24px;_x000D_
  border-color: transparent transparent transparent black;_x000D_
}
_x000D_
<div class="arrow"></div>
_x000D_
_x000D_
_x000D_

How to delete all files and folders in a folder by cmd call

One easy one-line option is to create an empty directory somewhere on your file system, and then use ROBOCOPY (http://technet.microsoft.com/en-us/library/cc733145.aspx) with the /MIR switch to remove all files and subfolders. By default, robocopy does not copy security, so the ACLs in your root folder should remain intact.

Also probably want to set a value for the retry switch, /r, because the default number of retries is 1 million.

robocopy "C:\DoNotDelete_UsedByScripts\EmptyFolder" "c:\temp\MyDirectoryToEmpty" /MIR /r:3

Rest-assured. Is it possible to extract value from request json?

JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();

I want to delete all bin and obj folders to force all projects to rebuild everything

Nothing worked for me. I needed to delete all files in bin and obj folders for debug and release. My solution:

1.Right click project, unload, right click again edit, go to bottom

2.Insert

<Target Name="DeleteBinObjFolders" BeforeTargets="Clean">
  <RemoveDir Directories="..\..\Publish" />
  <RemoveDir Directories=".\bin" />
  <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
</Target>

3. Save, reload project, right click clean and presto.

Conditional Replace Pandas

Try

df.loc[df.my_channel > 20000, 'my_channel'] = 0

Note: Since v0.20.0, ix has been deprecated in favour of loc / iloc.

How can I use SUM() OVER()

Query would be like this:

SELECT ID, AccountID, Quantity, 
       SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT 

       FROM #Empl ORDER BY AccountID

Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.

First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10

so result would appear like attached snapshot.

How to do HTTP authentication in android?

This works for me

 URL imageUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) imageUrl
                            .openConnection();
                    conn.setRequestProperty("Authorization", "basic " +
                            Base64.encode("username:password".getBytes()));
                    conn.setConnectTimeout(30000);
                    conn.setReadTimeout(30000);
                    conn.setInstanceFollowRedirects(true);
                    InputStream is = conn.getInputStream();

Should I use != or <> for not equal in T-SQL?

'<>' is from the SQL-92 standard and '!=' is a proprietary T-SQL operator. It's available in other databases as well, but since it isn't standard you have to take it on a case-by-case basis.

In most cases, you'll know what database you're connecting to so this isn't really an issue. At worst you might have to do a search and replace in your SQL.

How can I serve static html from spring boot?

In Spring boot, /META-INF/resources/, /resources/, static/ and public/ directories are available to serve static contents.

So you can create a static/ or public/ directory under resources/ directory and put your static contents there. And they will be accessible by: http://localhost:8080/your-file.ext. (assuming the server.port is 8080)

You can customize these directories using spring.resources.static-locations in the application.properties.

For example:

spring.resources.static-locations=classpath:/custom/

Now you can use custom/ folder under resources/ to serve static files.

Update:

This is also possible using java config:

@Configuration
public class StaticConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/custom/");
    }
}

This confugration maps contents of custom directory to the http://localhost:8080/static/** url.

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

Why does Lua have no "continue" statement?

The first part is answered in the FAQ as slain pointed out.

As for a workaround, you can wrap the body of the loop in a function and return early from that, e.g.

-- Print the odd numbers from 1 to 99
for a = 1, 99 do
  (function()
    if a % 2 == 0 then
      return
    end
    print(a)
  end)()
end

Or if you want both break and continue functionality, have the local function perform the test, e.g.

local a = 1
while (function()
  if a > 99 then
    return false; -- break
  end
  if a % 2 == 0 then
    return true; -- continue
  end
  print(a)
  return true; -- continue
end)() do
  a = a + 1
end

How do I install chkconfig on Ubuntu?

sysv-rc-conf is an alternate option for Ubuntu.

sudo apt-get install sysv-rc-conf

sysv-rc-conf --list xxxx

How to change lowercase chars to uppercase using the 'keyup' event?

Let say your html code is :

<input type="text" id="txtMyText" />

then the jquery should be :

$('#txtMyText').keyup(function() {
  this.value = this.value.toUpperCase();
});

PHP ternary operator vs null coalescing operator

Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.

var_export (false ?? 'value2');   // false
var_export (true  ?? 'value2');   // true
var_export (null  ?? 'value2');   // value2
var_export (''    ?? 'value2');   // ""
var_export (0     ?? 'value2');   // 0

var_export (false ?: 'value2');   // value2
var_export (true  ?: 'value2');   // true
var_export (null  ?: 'value2');   // value2
var_export (''    ?: 'value2');   // value2
var_export (0     ?: 'value2');   // value2

The Null Coalescing Operator ??

  • ?? is like a "gate" that only lets NULL through.
  • So, it always returns first parameter, unless first parameter happens to be NULL.
  • This means ?? is same as ( !isset() || is_null() )

Use of ??

  • shorten !isset() || is_null() check
  • e.g $object = $object ?? new objClassName();

Stacking Null Coalese Operator

        $v = $x ?? $y ?? $z; 

        // This is a sequence of "SET && NOT NULL"s:

        if( $x  &&  !is_null($x) ){ 
            return $x; 
        } else if( $y && !is_null($y) ){ 
            return $y; 
        } else { 
            return $z; 
        }

The Ternary Operator ?:

  • ?: is like a gate that lets anything falsy through - including NULL
  • Anything falsy: 0, empty string, NULL, false, !isset(), empty()
  • Same like old ternary operator: X ? Y : Z
  • Note: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables

Use of ?:

  • checking empty(), !isset(), is_null() etc
  • shorten ternary operation like !empty($x) ? $x : $y to $x ?: $y
  • shorten if(!$x) { echo $x; } else { echo $y; } to echo $x ?: $y

Stacking Ternary Operator

        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 1 ?: 0 ?: 3 ?: 2; //1
        echo 2 ?: 1 ?: 0 ?: 3; //2
        echo 3 ?: 2 ?: 1 ?: 0; //3
    
        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 0 ?: 0 ?: 2 ?: 3; //2
        echo 0 ?: 0 ?: 0 ?: 3; //3

    
        // Source & Credit: http://php.net/manual/en/language.operators.comparison.php#95997
   
        // This is basically a sequence of:

 
        if( truthy ) {}
        else if(truthy ) {}
        else if(truthy ) {}
        ..
        else {}

Stacking both, we can shorten this:

        if( isset($_GET['name']) && !is_null($_GET['name'])) {
            $name = $_GET['name'];
        } else if( !empty($user_name) ) {
             $name = $user_name; 
        } else {
            $name = 'anonymous';
        }

To this:

        $name = $_GET['name'] ?? $user_name ?: 'anonymous';

Cool, right? :-)

How to print the data in byte array as characters?

Try this one : new String(byte[])

Can someone explain Microsoft Unity?

MSDN has a Developer's Guide to Dependency Injection Using Unity that may be useful.

The Developer's Guide starts with the basics of what dependency injection is, and continues with examples of how to use Unity for dependency injection. As of the February 2014 the Developer's Guide covers Unity 3.0, which was released in April 2013.

jump to line X in nano editor

I am using nano editor in a Raspberry Pi with Italian OS language and Italian keyboard. Don't know the exact reason, but in this environment the shortcut is:

Ctrl+-

How to remove underline from a name on hover

To keep the color and prevent an underline on the link:

legend.green-color a{
    color:green;
    text-decoration: none;
}

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

How to remove all the occurrences of a char in c++ string

string RemoveChar(string str, char c) 
{
   string result;
   for (size_t i = 0; i < str.size(); i++) 
   {
          char currentChar = str[i];
          if (currentChar != c)
              result += currentChar;
   }
       return result;
}

This is how I did it.

Or you could do as Antoine mentioned:

See this question which answers the same problem. In your case:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

Gson: Directly convert String to JsonObject (no POJO)

com.google.gson.JsonParser#parse(java.lang.String) is now deprecated

so use com.google.gson.JsonParser#parseString, it works pretty well

Kotlin Example:

val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject

Java Example:

JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

Like others already wrote, in short:

shared project
reuse on the code (file) level, allowing for folder structure and resources as well

pcl
reuse on the assembly level

What was mostly missing from answers here for me is the info on reduced functionality available in a PCL: as an example you have limited file operations (I was missing a lot of File.IO fuctionality in a Xamarin cross-platform project).

In more detail
shared project:
+ Can use #if when targeting multiple platforms (e. g. Xamarin iOS, Android, WinPhone)
+ All framework functionality available for each target project (though has to be conditionally compiled)
o Integrates at compile time
- Slightly larger size of resulting assemblies
- Needs Visual Studio 2013 Update 2 or higher

pcl:
+ generates a shared assembly
+ usable with older versions of Visual Studio (pre-2013 Update 2)
o dynamically linked
- lmited functionality (subset of all projects it is being referenced by)

If you have the choice, I would recommend going for shared project, it is generally more flexible and more powerful. If you know your requirements in advance and a PCL can fulfill them, you might go that route as well. PCL also enforces clearer separation by not allowing you to write platform-specific code (which might not be a good choice to be put into a shared assembly in the first place).

Main focus of both is when you target multiple platforms, else you would normally use just an ordinary library/dll project.

Why should I use a pointer rather than the object itself?

One reason for using pointers is to interface with C functions. Another reason is to save memory; for example: instead of passing an object which contains a lot of data and has a processor-intensive copy-constructor to a function, just pass a pointer to the object, saving memory and speed especially if you're in a loop, however a reference would be better in that case, unless you're using an C-style array.

How to stop/shut down an elasticsearch node?

Stopping the service and killing the daemon are indeed the correct ways to shutdown a node. However, it's not recommended to do so directly if you want to take down a node for maintenance. In fact, if you don't have replicas you will lose data.

When you directly shutdown a node, Elasticsearch will wait for 1m (default time) for it to come back online. If it doesn't, then it will start to allocate the shards from that node to other nodes wasting lots of IO.

A typical approach would be to disable shard allocation temporarily by issuing:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "none"
  }
}

Now, when you take down a node, ES won't try to allocate shard from that node to other nodes and you can perform you maintenance activity and then once the node is up, you can enable shard allocation again:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "all"
  }
}

Source: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/restart-upgrade.html

If you don't have replicas for all your indexes, then performing this type of activity will have downtime on some of the indexes. A cleaner way in this case would be to migrate all the shards to other nodes before taking the node down:

PUT _cluster/settings
{
  "transient" : {
    "cluster.routing.allocation.exclude._ip" : "10.0.0.1"
  }
}

This will move all shards from 10.0.0.1 to other nodes (will take time depending on the data). Once everything is done, you can kill the node, perform maintenance and get it back online. This is a slower operation and is not required if you have replicas.

(Instead of _ip, _id, _name with wildcards will work just fine.)

More information: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/allocation-filtering.html

Other answers have explained how to kill a process.

Quicksort: Choosing the pivot

Don't try and get too clever and combine pivoting strategies. If you combined median of 3 with random pivot by picking the median of the first, last and a random index in the middle, then you'll still be vulnerable to many of the distributions which send median of 3 quadratic (so its actually worse than plain random pivot)

E.g a pipe organ distribution (1,2,3...N/2..3,2,1) first and last will both be 1 and the random index will be some number greater than 1, taking the median gives 1 (either first or last) and you get an extermely unbalanced partitioning.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

My guess is that you are trying to restore in lower versions which wont work

What is the difference between XAMPP or WAMP Server & IIS?

XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.

XWAMPP/WAMP - Windows,Apache,Mysql,PHP

IIS - Apache,SQL Server, ASP.NET

If you like to read more about XWAMPP vs WAMP

Create pandas Dataframe by appending one row at a time

You can use generator object to create Dataframe, which will be more memory efficient over the list.

num = 10

# Generator function to generate generator object
def numgen_func(num):
    for i in range(num):
        yield ('name_{}'.format(i), (i*i), (i*i*i))

# Generator expression to generate generator object (Only once data get populated, can not be re used)
numgen_expression = (('name_{}'.format(i), (i*i), (i*i*i)) for i in range(num) )

df = pd.DataFrame(data=numgen_func(num), columns=('lib', 'qty1', 'qty2'))

To add raw to existing DataFrame you can use append method.

df = df.append([{ 'lib': "name_20", 'qty1': 20, 'qty2': 400  }])

How can one check to see if a remote file exists using PHP?

As Pies say you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.

Here is example:

function remoteFileExists($url) {
    $curl = curl_init($url);

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}

$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
    echo 'file exists';
} else {
    echo 'file does not exist';   
}

jQuery - select the associated label element of a input field

There are two ways to specify label for element:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label

So, the proper way to find element's label is

   var $element = $( ... )

   var $label = $("label[for='"+$element.attr('id')+"']")
   if ($label.length == 0) {
     $label = $element.closest('label')
   }

   if ($label.length == 0) {
     // label wasn't found
   } else {
     // label was found
   }

write newline into a file

Or you could use something like the following. Pay attention to "\n":

/**
 * Created by mona on 3/26/16.
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
public class FileExample {


    public static void main (String[] args) throws java.io.IOException {

        File newFile = new File("tweet.txt");
        FileWriter fileWriter = new FileWriter(newFile);
        fileWriter.write("Mona Jalal");
        fileWriter.append("\nMona Mona");
        fileWriter.close();
        FileReader fileReader = new FileReader(newFile);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        fileReader.close();
        bufferedReader.close();



    }
}

How to install ADB driver for any android device?

I have found a solution by myself. I use the PDANet tool to find the driver automatically.

http://www.junefabrics.com/android/download.php

Pass variables between two PHP pages without using a form or the URL of page

Use Sessions.

Page1:

session_start();
$_SESSION['message'] = "Some message"

Page2:

session_start();
var_dump($_SESSION['message']);

Laravel eloquent update record without loading from database

You can also use firstOrCreate OR firstOrNew

// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]); 

// update record
$post->title = "Updated title";
$post->save();

Hope it will help you :)

Why am I getting error for apple-touch-icon-precomposed.png

If you don't care about the icon looking pretty on all sort of Apple devices, just add

get '/:apple_touch_icon' => redirect('/icon.png'), constraints: { apple_touch_icon: /apple-touch-icon(-\d+x\d+)?(-precomposed)?\.png/ }

to your config/routes.rb file and some icon.png to your public directory. Redirecting to 404.html instead of icon.png works too.

When should I use Async Controllers in ASP.NET MVC?

Asynchronous action methods are useful when an action must perform several independent long running operations.

A typical use for the AsyncController class is long-running Web service calls.

Should my database calls be asynchronous ?

The IIS thread pool can often handle many more simultaneous blocking requests than a database server. If the database is the bottleneck, asynchronous calls will not speed up the database response. Without a throttling mechanism, efficiently dispatching more work to an overwhelmed database server by using asynchronous calls merely shifts more of the burden to the database. If your DB is the bottleneck, asynchronous calls won’t be the magic bullet.

You should have a look at 1 and 2 references

Derived from @PanagiotisKanavos comments:

Moreover, async doesn't mean parallel. Asynchronous execution frees a valuable threadpool thread from blocking for an external resource, for no complexity or performance cost. This means the same IIS machine can handle more concurrent requests, not that it will run faster.

You should also consider that blocking calls start with a CPU-intensive spinwait. During stress times, blocking calls will result in escalating delays and app pool recycling. Asynchronous calls simply avoid this

how do you view macro code in access?

Open the Access Database, you will see Table, Query, Report, Module & Macro.
This contains the macros which can be used to invoke common MS-Access actions in a sequence.

For custom VBA macro, press ALT+F11.

Sorting a DropDownList? - C#, ASP.NET

If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...

DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";

ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";
ddlOptions.DataBind();

Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.

How to use the unsigned Integer in Java 8 and Java 9?

If using a third party library is an option, there is jOOU (a spin off library from jOOQ), which offers wrapper types for unsigned integer numbers in Java. That's not exactly the same thing as having primitive type (and thus byte code) support for unsigned types, but perhaps it's still good enough for your use-case.

import static org.joou.Unsigned.*;

// and then...
UByte    b = ubyte(1);
UShort   s = ushort(1);
UInteger i = uint(1);
ULong    l = ulong(1);

All of these types extend java.lang.Number and can be converted into higher-order primitive types and BigInteger.

(Disclaimer: I work for the company behind these libraries)

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

You can start by installing the below given command in the conda environment:

conda install pip

Followed by installing all pip packages you need in the environment.

After installing all the conda and pip packages to export the environment use:

conda env export -n <env-name> > environment.yml

This will create the required file in the folder

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I faced the same issue because I was querying db for more than 1000 iterations. I have used try and finally in my code. But was still getting error.

To solve this I just logged into oracle db and ran below query:

ALTER SYSTEM SET open_cursors = 8000 SCOPE=BOTH;

And this solved my problem immediately.

How often should Oracle database statistics be run?

At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)

Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

Are there .NET implementation of TLS 1.2?

You can make use of the SchUseStrongCrypto registry setting to require all .NET applications to use TLS 1.2 instead of 1.0 by default.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

Python: Pandas Dataframe how to multiply entire column with a scalar

The real problem of why you are getting the error is not that there is anything wrong with your code: you can use either iloc, loc, or apply, or *=, another of them could have worked.

The real problem that you have is due to how you created the df DataFrame. Most likely you created your df as a slice of another DataFrame without using .copy(). The correct way to create your df as a slice of another DataFrame is df = original_df.loc[some slicing].copy().

The problem is already stated in the error message you got " SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"
You will get the same message in the most current version of pandas too.

Whenever you receive this kind of error message, you should always check how you created your DataFrame. Chances are you forgot the .copy()

What EXACTLY is meant by "de-referencing a NULL pointer"?

Dereferencing just means reading the memory value at a given address. So when you have a pointer to something, to dereference the pointer means to read or write the data that the pointer points to.

In C, the unary * operator is the dereferencing operator. If x is a pointer, then *x is what x points to. The unary & operator is the address-of operator. If x is anything, then &x is the address at which x is stored in memory. The * and & operators are inverses of each other: if x is any data, and y is any pointer, then these equations are always true:

*(&x) == x
&(*y) == y

A null pointer is a pointer that does not point to any valid data (but it is not the only such pointer). The C standard says that it is undefined behavior to dereference a null pointer. This means that absolutely anything could happen: the program could crash, it could continue working silently, or it could erase your hard drive (although that's rather unlikely).

In most implementations, you will get a "segmentation fault" or "access violation" if you try to do so, which will almost always result in your program being terminated by the operating system. Here's one way a null pointer could be dereferenced:

int *x = NULL;  // x is a null pointer
int y = *x;     // CRASH: dereference x, trying to read it
*x = 0;         // CRASH: dereference x, trying to write it

And yes, dereferencing a null pointer is pretty much exactly like a NullReferenceException in C# (or a NullPointerException in Java), except that the langauge standard is a little more helpful here. In C#, dereferencing a null reference has well-defined behavior: it always throws a NullReferenceException. There's no way that your program could continue working silently or erase your hard drive like in C (unless there's a bug in the language runtime, but again that's incredibly unlikely as well).

Video auto play is not working in Safari and Chrome desktop browser

var video = document.querySelector('video');
video.muted = true;
video.play()

Only this solution helped me, <video autoplay muted ...>...</video> didn't work...

How can I use the HTML5 canvas element in IE?

Currently, ExplorerCanvas is the only option to emulate HTML5 canvas for IE6, 7, and 8. You're also right about its performance, which is pretty poor.

I found a particle simulatior that benchmarks the difference between true HTML5 canvas handling in Google Chrome, Safari, and Firefox, vs ExplorerCanvas in IE. The results show that the major browsers that do support the canvas tag run about 20 to 30 times faster than the emulated HTML5 in IE with ExplorerCanvas.

I doubt that anyone will go through the effort of creating an alternative because 1) excanvas.js is about as cleanly coded as it gets and 2) when IE9 is released all of the major browsers will finally support the canvas object. Hopefully, We'll get IE9 within a year

Eric @ www.webkrunk.com

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

Print time in a batch file (milliseconds)

%TIME% is in the format H:MM:SS,CS after midnight and hence conversion to centiseconds >doesn't work. Seeing Patrick Cuff's post with 6:46am it seems that it is not only me.

But with this lines bevor you should will fix that problem easy:

if " "=="%StartZeit:~0,1%" set StartZeit=0%StartZeit:~-10%
if " "=="%EndZeit:~0,1%" set EndZeit=0%EndZeit:~-10%

Thanks for your nice inspiration! I like to use it in my mplayer, ffmpeg, sox Scripts to pimp my mediafiles for old PocketPlayers just for fun.

com.jcraft.jsch.JSchException: UnknownHostKey

You can also execute the following code. It is tested and working.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class SFTPTest {

    public static void main(String[] args) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("username", "mywebsite.com", 22); //default port is 22
            UserInfo ui = new MyUserInfo();
            session.setUserInfo(ui);
            session.setPassword("123456".getBytes());
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("Connected");
        } catch (JSchException e) {
            e.printStackTrace(System.out);
        } catch (Exception e){
            e.printStackTrace(System.out);
        } finally{
            session.disconnect();
            System.out.println("Disconnected");
        }
    }

    public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {

        @Override
        public String getPassphrase() {
            return null;
        }
        @Override
        public String getPassword() {
            return null;
        }
        @Override
        public boolean promptPassphrase(String arg0) {
            return false;
        }
        @Override
        public boolean promptPassword(String arg0) {
            return false;
        }
        @Override
        public boolean promptYesNo(String arg0) {
            return false;
        }
        @Override
        public void showMessage(String arg0) {
        }
        @Override
        public String[] promptKeyboardInteractive(String arg0, String arg1,
                String arg2, String[] arg3, boolean[] arg4) {
            return null;
        }
    }
}

Please substitute the appropriate values.

What are the differences between the BLOB and TEXT datatypes in MySQL?

According to High-performance Mysql book:

The only difference between the BLOB and TEXT families is that BLOB types store binary data with no collation or character set, but TEXT types have a character set and collation.

Select NOT IN multiple columns

I'm not sure whether you think about:

select * from friend f
where not exists (
    select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)

it works only if id1 is related with id1 and id2 with id2 not both.

What characters are valid for JavaScript variable names?

Javascript Variables

You can start a variable with any letter, $, or _ character. As long as it doesn't start with a number, you can include numbers as well.

Start: [a-z], $, _

Contain: [a-z], [0-9], $, _

jQuery

You can use _ for your library so that it will stand side-by-side with jQuery. However, there is a configuration you can set so that jQuery will not use $. It will instead use jQuery. To do this, simply set:

jQuery.noConflict();

This page explains how to do this.

Skip Git commit hooks

From man githooks:

pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

Using "label for" on radio buttons

You almost got it. It should be this:

_x000D_
_x000D_
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
_x000D_
_x000D_

The value in for should be the id of the element you are labeling.

open link in iframe

Try this:

<iframe name="iframe1" src="target.html"></iframe>

<a href="link.html" target="iframe1">link</a>

The "target" attribute should open in the iframe.

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Here is a code to split the data into n=5 folds in a stratified manner

% X = data array
% y = Class_label
from sklearn.cross_validation import StratifiedKFold
skf = StratifiedKFold(y, n_folds=5)
for train_index, test_index in skf:
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

How to upload and parse a CSV file in php

You can try with this:

function doParseCSVFile($filesArray)
{
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                ExecuteQry($strInsertSql);
            }               
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;
    }
}

How do I use HTML as the view engine in Express?

to server html pages through routing, I have done this.

var hbs = require('express-hbs');
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views/partials'
}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');

and renamed my .html files to .hbs files - handlebars support plain html

How to set base url for rest in spring boot?

I couldn't believe how complicate the answer to this seemingly simple question is. Here are some references:

There are many differnt things to consider:

  1. By settingserver.context-path=/api in application.properties you can configure a prefix for everything.(Its server.context-path not server.contextPath !)
  2. Spring Data controllers annotated with @RepositoryRestController that expose a repository as rest endpoint will use the environment variable spring.data.rest.base-path in application.properties. But plain @RestController won't take this into account. According to the spring data rest documentation there is an annotation @BasePathAwareController that you can use for that. But I do have problems in connection with Spring-security when I try to secure such a controller. It is not found anymore.

Another workaround is a simple trick. You cannot prefix a static String in an annotation, but you can use expressions like this:

@RestController
public class PingController {

  /**
   * Simple is alive test
   * @return <pre>{"Hello":"World"}</pre>
   */
  @RequestMapping("${spring.data.rest.base-path}/_ping")
  public String isAlive() {
    return "{\"Hello\":\"World\"}";
  }
}

android: how to use getApplication and getApplicationContext from non activity / service class

In order to avoid to pass this argument i use class derived from Application

public class MyApplication extends Application {

private static Context sContext;

@Override
public void onCreate() {
    super.onCreate();
    sContext=   getApplicationContext();

}

public static Context getContext() {
    return sContext;
}

and invoke MyApplication.getContext() in Helper classes.

Don't forget to update the manifest.

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example"> 
      <application 
       android:name=".MyApplication"
       android:allowBackup="true" 
       android:icon="@mipmap/ic_launcher" 
       android:label="@string/app_name"> 
         <activity....>
            ......
         </activity>
     </application> 
</manifest>

How do I scroll to an element using JavaScript?

You can use an anchor to "focus" the div. I.e:

<div id="myDiv"></div>

and then use the following javascript:

// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";

Indent List in HTML and CSS

Yes, simply use something like:

ul {
  padding-left: 10px;
}

And it will bump each successive ul by 10 pixels.

Working jsFiddle

JavaScript ternary operator example with functions

There is nothing particularly tricky about the example you posted.

In a ternary operator, the first argument (the conditional) is evaluated and if the result is true, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.

Think of it this way:

var x = (1 < 2) ? true : false;

Could also be written as:

var x = (1 < 2) ? getTrueValue() : getFalseValue();

This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:

(1 < 2) ? getTrueValue() : getFalseValue();

Now simply replace those with any arbitrary functions, and you are left with something like your example:

(1 < 2) ? removeItem($this) : addItem($this);

Now your last example really doesn't need a ternary at all, as it can be written like this:

x = (1 < 2);  // x will be set to "true"

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

Try this:

SELECT
    od.Sku,
    od.mf_item_number,
    od.Qty,
    od.Price,
    s.SupplierId,
    s.SupplierName,
    s.DropShipFees,
    si.Price as cost
FROM
    OrderDetails od
    INNER JOIN Supplier s on s.SupplierId = od.Mfr_ID
    INNER JOIN Group_Master gm on gm.Sku = od.Sku
    INNER JOIN Supplier_Item si on si.SKU = od.Sku and si.SupplierId = s.SupplierID
WHERE
    od.invoiceid = '339740'

This will return multiple rows that are identical except for the cost column. Look at the different cost values that are returned and figure out what is causing the different values. Then ask somebody which cost value they want, and add the criteria to the query that will select that cost.

Changing Background Image with CSS3 Animations

You can follow by this code:

_x000D_
_x000D_
#cd{_x000D_
  position: relative;_x000D_
  margin: 0 auto;_x000D_
  height: 281px;_x000D_
  width: 450px;_x000D_
}_x000D_
#cf img{_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  -moz-transition: opacity 1s ease-in-out;_x000D_
  transition: opacity 1s ease-in-out;_x000D_
}_x000D_
#cf img.top:hover{_x000D_
  opacity: 0;_x000D_
}
_x000D_
<div id="cf">_x000D_
  <img class="button" src="Birdman.jpg" />_x000D_
  <img src="Turtle.jpg" class="top" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Loop X number of times

Here is a simple way to loop any number of times in PowerShell.

It is the same as the for loop above, but much easier to understand for newer programmers and scripters. It uses a range, and foreach. A range is defined as:

range = lower..upper

or

$range = 1..10

A range can be used directly in a for loop as well, although not the most optimal approach, any performance loss or additional instruction to process would be unnoticeable. The solution is below:

foreach($i in 1..10){
    Write-Host $i
}

Or in your case:

$ActiveCampaigns = 10
foreach($i in 1..$ActiveCampaigns)
{
    Write-Host $i
    If($i==$ActiveCampaigns){
        // Do your stuff on the last iteration here
    }
}

Comparing arrays for equality in C++

You're not comparing the contents of the arrays, you're comparing the addresses of the arrays. Since they're two separate arrays, they have different addresses.

Avoid this problem by using higher-level containers, such as std::vector, std::deque, or std::array.

np.mean() vs np.average() in Python NumPy?

np.mean always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result).

np.average can compute a weighted average if the weights parameter is supplied.

Passing html values into javascript functions

Give the textbox an id of "txtValue" and change the input button declaration to the following:

<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />

How can I uninstall an application using PowerShell?

Use:

function remove-HSsoftware{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,
ValuefromPipeline = $true,
HelpMessage="IdentifyingNumber can be retrieved with `"get-wmiobject -class win32_product`"")]
[ValidatePattern('{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}}')]
[string[]]$ids,
[parameter(Mandatory=$false,
            ValuefromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            HelpMessage="Computer name or IP adress to query via WMI")]
[Alias('hostname,CN,computername')]
[string[]]$computers
)
begin {}
process{
    if($computers -eq $null){
    $computers = Get-ADComputer -Filter * | Select dnshostname |%{$_.dnshostname}
    }
    foreach($computer in $computers){
        foreach($id in $ids){
            write-host "Trying to uninstall sofware with ID ", "$id", "from computer ", "$computer"
            $app = Get-WmiObject -class Win32_Product -Computername "$computer" -Filter "IdentifyingNumber = '$id'"
            $app | Remove-WmiObject

        }
    }
}
end{}}
 remove-hssoftware -ids "{8C299CF3-E529-414E-AKD8-68C23BA4CBE8}","{5A9C53A5-FF48-497D-AB86-1F6418B569B9}","{62092246-CFA2-4452-BEDB-62AC4BCE6C26}"

It's not fully tested, but it ran under PowerShell 4.

I've run the PS1 file as it is seen here. Letting it retrieve all the Systems from the AD and trying to uninstall multiple applications on all systems.

I've used the IdentifyingNumber to search for the Software cause of David Stetlers input.

Not tested:

  1. Not adding ids to the call of the function in the script, instead starting the script with parameter IDs
  2. Calling the script with more then 1 computer name not automatically retrieved from the function
  3. Retrieving data from the pipe
  4. Using IP addresses to connect to the system

What it does not:

  1. It doesn't give any information if the software actually was found on any given system.
  2. It does not give any information about failure or success of the deinstallation.

I wasn't able to use uninstall(). Trying that I got an error telling me that calling a method for an expression that has a value of NULL is not possible. Instead I used Remove-WmiObject, which seems to accomplish the same.

CAUTION: Without a computer name given it removes the software from ALL systems in the Active Directory.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

changing visibility using javascript

If you just want to display it when you get a response add this to your loadpage()

function loadpage(page_request, containerid){
   if (page_request.readyState == 4 && page_request.status==200) { 
      var container = document.getElementById(containerid);
      container.innerHTML=page_request.responseText;
      container.style.visibility = 'visible';
      // or 
      container.style.display = 'block';
}

but this depend entirely on how you hid the div in the first place

How to append a date in batch files

This is all awkward and not local settings independent. Do it like this:

%CYGWIN_DIR%\bin\date +%%Y%%m%%d_%%H%%M% > date.txt
for /f "delims=" %%a in ('type "date.txt" 2^>NUL') do set datetime=%%a
echo %datetime%
del date.txt

Yes, use Cygwin date and all your problems are gone!

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

Replace multiple strings at once

The top answer is equivalent to doing:

let text = find.reduce((acc, item, i) => {
  const regex = new RegExp(item, "g");
  return acc.replace(regex, replace[i]);
}, textarea);

Given this:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

In this case, no imperative programming is going on.

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

In Python, how do you convert seconds since epoch to a `datetime` object?

For those that want it ISO 8601 compliant, since the other solutions do not have the T separator nor the time offset (except Meistro's answer):

from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00

Note, I use fromtimestamp because if I used utcfromtimestamp I would need to chain on .astimezone(...) anyway to get the offset.

If you don't want to go all the way to microseconds you can choose a different unit with the isoformat() method.

How to connect to remote Redis server?

There are two ways to connect remote redis server using redis-cli:

1. Using host & port individually as options in command

redis-cli -h host -p port

If your instance is password protected

redis-cli -h host -p port -a password

e.g. if my-web.cache.amazonaws.com is the host url and 6379 is the port

Then this will be the command:

redis-cli -h my-web.cache.amazonaws.com -p 6379

if 92.101.91.8 is the host IP address and 6379 is the port:

redis-cli -h 92.101.91.8 -p 6379

command if the instance is protected with password pass123:

redis-cli -h my-web.cache.amazonaws.com -p 6379 -a pass123

2. Using single uri option in command

redis-cli -u redis://password@host:port

command in a single uri form with username & password

redis-cli -u redis://username:password@host:port

e.g. for the same above host - port configuration command would be

redis-cli -u redis://[email protected]:6379

command if username is also provided user123

redis-cli -u redis://user123:[email protected]:6379

This detailed answer was for those who wants to check all options. For more information check documentation: Redis command line usage

Android Studio suddenly cannot resolve symbols

In my multi-module project, the problem was that version of "com.android.support:appcompat-v7" in module A was "22.0.0", but in B - "22.2.0".

Solution: make sure
1. version of common libraries is same among modules.
2. each of modules compiles without any errors (try to build each of them from CLI).

Why do people say that Ruby is slow?

Writing code is slow. Reading code is slow. Finding and fixing bugs is slow. Adding features and enhancements is slow. Anything that improves on the previous is a win. Very rarely is execution performance an issue.

Git remote branch deleted, but still it appears in 'branch -a'

Use:

git remote prune <remote>

Where <remote> is a remote source name like origin or upstream.

Example: git remote prune origin

Is it possible to decrypt MD5 hashes?

MD5 is considered broken, not because you can get back the original content from the hash, but because with work, you can craft two messages that hash to the same hash.

You cannot un-hash an MD5 hash.

C++ IDE for Linux?

Checkout Netbeans, it's written in Java so you'll have the same environment regardless of your OS, and it supports a lot more than just C++.

I'm not going to try to convince you, because I think IDEs can be a very personal choice. For me it improves my productivity by being fast, supporting the languages I code in and has the standard features you'd expect from an IDE.

What is a stack pointer used for in microprocessors?

Should you ever crave deeper understanding, I heartily recommend Patterson and Hennessy as an intro and Hennessy and Patterson as an intermediate to advanced text. They're pricey, but truly non-pareil; I just wish either or both were available when I got my Masters' degree and entered the workforce designing chips, systems, and parts of system software for them (but, alas!, that was WAY too long ago;-). Stack pointers are so crucial (and the distinction between a microprocessor and any other kind of CPU so utterly meaningful in this context... or, for that matter, in ANY other context, in the last few decades...!-) that I doubt anything but a couple of thorough from-the-ground-up refreshers can help!-)

Unused arguments in R

One approach (which I can't imagine is good programming practice) is to add the ... which is traditionally used to pass arguments specified in one function to another.

> multiply <- function(a,b) a*b
> multiply(a = 2,b = 4,c = 8)
Error in multiply(a = 2, b = 4, c = 8) : unused argument(s) (c = 8)
> multiply2 <- function(a,b,...) a*b
> multiply2(a = 2,b = 4,c = 8)
[1] 8

You can read more about ... is intended to be used here

Correct way to select from two tables in SQL Server with no common field to join on

You can (should) use CROSS JOIN. Following query will be equivalent to yours:

SELECT 
   table1.columnA
 , table2.columnA
FROM table1 
CROSS JOIN table2
WHERE table1.columnA = 'Some value'

or you can even use INNER JOIN with some always true conditon:

FROM table1 
INNER JOIN table2 ON 1=1

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

How to split strings over multiple lines in Bash?

In certain scenarios utilizing Bash's concatenation ability might be appropriate.

Example:

temp='this string is very long '
temp+='so I will separate it onto multiple lines'
echo $temp
this string is very long so I will separate it onto multiple lines

From the PARAMETERS section of the Bash Man page:

name=[value]...

...In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays) or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable's value.

How to unset a JavaScript variable?

Note that delete returns true when it was successful.

Update 2021: tested on Chrome 88 and Firefox 84:

implicit_global = 1;
delete implicit_global; // true

window.explicit_global = 1;
delete explicit_global; // true

const _object = {property: 1};
delete _object.property; // true

function_set = function() {};
delete function_set; // true

function function_declaration() {};
delete function_declaration; // false

(function () {
    var _var = 1;
    console.log(delete _var); // false
    console.log(_var); // 1
})()

(function () {
    let _let = 1;
    console.log(delete _let); // false
    console.log(_let); // 1
})()

(function () {
    const _const = 1;
    console.log(delete _const); // false
    console.log(_const); // 1
})()

Original answer is no longer relevant. tested in 2015 on Chrome 52:

implicit_global = 1;
window.explicit_global = 1;
function_set = function() {};
function function_dec() { };
var declared_variable = 1;

delete implicit_global; // true, tested on Chrome 52
delete window.explicit_global; // true, tested on Chrome 52
delete function_set; // true, tested on Chrome 52
delete function_dec; // true, tested on Chrome 52
delete declared_variable; // true, tested on Chrome 52

Creating a .dll file in C#.Net

Console Application is an application (.exe), not a Library (.dll). To make a library, create a new project, select "Class Library" in type of project, then copy the logic of your first code into this new project.

Or you can edit the Project Properties and select Class Library instead of Console Application in Output type.

As some code can be "console" dependant, I think first solution is better if you check your logic when you copy it.

alternatives to REPLACE on a text or ntext datatype

IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

For SQL Server 2005+:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

Javascript onclick hide div

just add onclick handler for anchor tag

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

onclick="this.parentNode.parentNode.style.display = 'none'"