Programs & Examples On #Cross page postback

MySQLDump one INSERT statement for each data row

Use:

mysqldump --extended-insert=FALSE 

Be aware that multiple inserts will be slower than one big insert.

Namespace not recognized (even though it is there)

I've had a similar issue, that took a bit to troubleshoot, so I thought to share it:

The namespace that could not be resolved in my case was Company.Project.Common.Models.EF. I had added a file in a new Company.Project.BusinessLogic.Common namespace.

The majority of the files were having a

using Company.Project;

And then referencing the models as Common.Models.EF. All the files that also had a

using Company.Project.BusinessLogic;

Were failing as VS could not determine which namespace to use.

The solution has been to change the second namespace to Company.Project.BusinessLogic.CommonServices

Angular ForEach in Angular4/Typescript?

in angular4 foreach like that. try this.

 selectChildren(data, $event) {
      let parentChecked = data.checked;
       this.hierarchicalData.forEach(obj => {
          obj.forEach(childObj=> {
            value.checked = parentChecked;
         });
      });
    }

How do I install cygwin components from the command line?

For a more convenient installer, you may want to use apt-cyg as your package manager. Its syntax similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps

wget https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg
chmod +x apt-cyg
mv apt-cyg /usr/local/bin

Now that apt-cyg is installed. Here are few examples of installing some packages

apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

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

This is example code I have written for you to understand this concept:

var foo = 5; 
bar = 2;     
fooba = 3;

// Execute an anonymous function
(function() {    
    bar = 100;             //overwrites global scope bar
    var foo = 4;           //a new foo variable is created in this' function's scope
    var fooba = 900;       //same as above
    document.write(foo);   //prints 4
    document.write(bar);   //prints 100
    document.write(fooba); //prints 900
})();

document.write('<br/>');
document.write('<br/>');
document.write(foo);       //prints 5
document.write(bar);       //prints 100
document.write(fooba);     //prints 3

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

Setting Action Bar title and subtitle

You can set the title in action-bar using AndroidManifest.xml. Add label to the activity

<activity
            android:name=".YourActivity"
            android:label="Your Title" />

How to use Elasticsearch with MongoDB?

Here I found another good option to migrate your MongoDB data to Elasticsearch. A go daemon that syncs mongodb to elasticsearch in realtime. Its the Monstache. Its available at : Monstache

Below the initial setp to configure and use it.

Step 1:

C:\Program Files\MongoDB\Server\4.0\bin>mongod --smallfiles --oplogSize 50 --replSet test

Step 2 :

C:\Program Files\MongoDB\Server\4.0\bin>mongo

C:\Program Files\MongoDB\Server\4.0\bin>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
Server has startup warnings:
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
MongoDB Enterprise test:PRIMARY>

Step 3 : Verify the replication.

MongoDB Enterprise test:PRIMARY> rs.status();
{
        "set" : "test",
        "date" : ISODate("2019-01-18T11:39:00.380Z"),
        "myState" : 1,
        "term" : NumberLong(2),
        "syncingTo" : "",
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                },
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                },
                "appliedOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1547811537, 1),
                        "t" : NumberLong(2)
                }
        },
        "lastStableCheckpointTimestamp" : Timestamp(1547811517, 1),
        "members" : [
                {
                        "_id" : 0,
                        "name" : "localhost:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 736,
                        "optime" : {
                                "ts" : Timestamp(1547811537, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDate" : ISODate("2019-01-18T11:38:57Z"),
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1547810805, 1),
                        "electionDate" : ISODate("2019-01-18T11:26:45Z"),
                        "configVersion" : 1,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                }
        ],
        "ok" : 1,
        "operationTime" : Timestamp(1547811537, 1),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1547811537, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        }
}
MongoDB Enterprise test:PRIMARY>

Step 4. Download the "https://github.com/rwynn/monstache/releases". Unzip the download and adjust your PATH variable to include the path to the folder for your platform. GO to cmd and type "monstache -v" # 4.13.1 Monstache uses the TOML format for its configuration. Configure the file for migration named config.toml

Step 5.

My config.toml -->

mongo-url = "mongodb://127.0.0.1:27017/?replicaSet=test"
elasticsearch-urls = ["http://localhost:9200"]

direct-read-namespaces = [ "admin.users" ]

gzip = true
stats = true
index-stats = true

elasticsearch-max-conns = 4
elasticsearch-max-seconds = 5
elasticsearch-max-bytes = 8000000 

dropped-collections = false
dropped-databases = false

resume = true
resume-write-unsafe = true
resume-name = "default"
index-files = false
file-highlighting = false
verbose = true
exit-after-direct-reads = false

index-as-update=true
index-oplog-time=true

Step 6.

D:\15-1-19>monstache -f config.toml

Monstache Running...

Confirm Migrated Data at Elasticsearch

Add Record at Mongo

Monstache Captured the event and migrate the data to elasticsearch

How to stop an app on Heroku?

http://devcenter.heroku.com/articles/maintenance-mode

If you’re deploying a large migration or need to disable access to your application for some length of time, you can use Heroku’s built in maintenance mode. It will serve a static page to all visitors, while still allowing you to run rake tasks or console commands.

$ heroku maintenance:on
Maintenance mode enabled.

and later

$ heroku maintenance:off
Maintenance mode disabled.

How do I get a TextBox to only accept numeric input in WPF?

In the WPF application, you can handle this by handling TextChanged event:

void arsDigitTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    bool handle = regex.IsMatch(this.Text);
    if (handle)
    {
        StringBuilder dd = new StringBuilder();
        int i = -1;
        int cursor = -1;
        foreach (char item in this.Text)
        {
            i++;
            if (char.IsDigit(item))
                dd.Append(item);
            else if(cursor == -1)
                cursor = i;
        }
        this.Text = dd.ToString();

        if (i == -1)
            this.SelectionStart = this.Text.Length;
        else
            this.SelectionStart = cursor;
    }
}

Objective-C for Windows

First of all, forget about GNUStep tools. Neither ProjectManager nor ProjectCenter can be called an IDE. With all due respect, it looks like guys from GNUStep project are stuck in the late 80-s (which is when NeXTSTEP first appeared).

Vim

ctags support Objective-C since r771 (be sure to pick the pre-release 5.9 version and add --langmap=ObjectiveC:.m.h to the command line, see here), so you'll have decent code completion/tag navigation.

Here's a short howto on adding Objective-C support to Vim tagbar plugin.

Emacs

The same applies to etags shipped with modern Emacsen, so you can start with Emacs Objective C Mode. YASnippet will provide useful templates:

YASnippet objc-mode

and if you want something more intelligent than the basic tags-based code completion, take a look at this question.

Eclipse

CDT supports Makefile-based projects:

enter image description here

-- so technically you can build your Objective-C projects out of the box (on Windows, you'll need the Cygwin or MinGW toolchain). The only problem is the code editor which will report plenty of errors against what it thinks is a pure C code (on-the-fly code checking can be turned off, but still...). If you want proper syntax highlighting, you can add Eclim to your Eclipse and enjoy all the good features of both Eclipse and Vim (see above).

Another promising Eclipse plugin is Colorer, but it doesn't support Objective-C as of yet. Feel free to file a feature request though.

SlickEdit

SlickEdit, among other features of a great IDE, does support Objective-C. While it is fairly complex to learn (not as complex as Emacs though), I believe this is your best option provided you don't mind purchasing it (the price is quite affordable).

Additionally, it has an Eclipse plugin which can be used as an alternative to the stand-alone editor.

KDevelop

Rumor has it there exists a KDevelop patch (15 year old, but who cares?). I personally don't think KDevelop is feature-superior compared to Emacsen, so I wouldn't bother trying it.


The above also applies to Objective-C development on Linux, since all of the tools mentioned are more or less portable.

How to use setprecision in C++

#include <iostream>
#include <iomanip>
using namespace std;

You can enter the line using namespace std; for your convenience. Otherwise, you'll have to explicitly add std:: every time you wish to use cout, fixed, showpoint, setprecision(2) and endl

int main()
{
    double num1 = 3.12345678;
    cout << fixed << showpoint;
    cout << setprecision(2);
    cout << num1 << endl;
return 0;
}

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

You can use a lookaround:

^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$

It will check ahead that the string has a letter or number, if it does it will check that the rest of the chars meet your requirements. This can probably be improved upon, but it seems to work with my tests.

UPDATE:

Adding modifications suggested by Chris Lutz:

^(?=.*[^\W_])[\w ]*$/

Android Closing Activity Programmatically

you can use this.finish() if you want to close current activity.

this.finish()

Angular File Upload

Ok, as this thread appears among the first results of google and for other users having the same question, you don't have to reivent the wheel as pointed by trueboroda there is the ng2-file-upload library which simplify this process of uploading a file with angular 6 and 7 all you need to do is:

Install the latest Angular CLI

yarn add global @angular/cli

Then install rx-compat for compatibility concern

npm install rxjs-compat --save

Install ng2-file-upload

npm install ng2-file-upload --save

Import FileSelectDirective Directive in your module.

import { FileSelectDirective } from 'ng2-file-upload';

Add it to [declarations] under @NgModule:
declarations: [ ... FileSelectDirective , ... ]

In your component

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
...

export class AppComponent implements OnInit {

   public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});
}

Template

<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

For better understanding you can check this link: How To Upload a File With Angular 6/7

SQL Server dynamic PIVOT query?

Updated version for SQL Server 2017 using STRING_AGG function to construct the pivot column list:

create table temp
(
    date datetime,
    category varchar(3),
    amount money
);

insert into temp values ('20120101', 'ABC', 1000.00);
insert into temp values ('20120201', 'DEF', 500.00);
insert into temp values ('20120201', 'GHI', 800.00);
insert into temp values ('20120210', 'DEF', 700.00);
insert into temp values ('20120301', 'ABC', 1100.00);


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = (SELECT STRING_AGG(category,',') FROM (SELECT DISTINCT category FROM temp WHERE category IS NOT NULL)t);

set @query = 'SELECT date, ' + @cols + ' from 
            (
                select date
                    , amount
                    , category
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for category in (' + @cols + ')
            ) p ';

execute(@query);

drop table temp;

SQL Update to the SUM of its joined values

An alternate to the above solutions is using Aliases for Tables:

UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;

Return a value if no rows are found in Microsoft tSQL

This Might be one way.

SELECT TOP 1 [Column Name] FROM (SELECT [Column Name] FROM [table]
    WHERE [conditions]
    UNION ALL
    SELECT 0 )A ORDER BY [Column Name] DESC

Storing data into list with class

You are attempting to call

List<EmailData>.Add(string,string,string)
. Try this:

lstemail.add(new EmailData{ FirstName="John", LastName="Smith", Location="Los Angeles"});

How to list imported modules?

print [key for key in locals().keys()
       if isinstance(locals()[key], type(sys)) and not key.startswith('__')]

How do I find the duplicates in a list and create another list with them?

def removeduplicates(a):
  seen = set()

  for i in a:
    if i not in seen:
      seen.add(i)
  return seen 

print(removeduplicates([1,1,2,2]))

The character encoding of the plain text document was not declared - mootool script

FireFox is reporting that the response did not even specify the character encoding in the header, eg. Content-Type: text/html; charset=utf-8 and not just Content-Type: text/plain;.

What web server are you using? Are you sure you are not requesting a non-existing page (404) that responds poorly?

Initializing select with AngularJS and ng-repeat

As suggested you need to use ng-options and unfortunately I believe you need to reference the array element for a default (unless the array is an array of strings).

http://jsfiddle.net/FxM3B/3/

The JavaScript:

function AppCtrl($scope) {


    $scope.operators = [
        {value: 'eq', displayName: 'equals'},
        {value: 'neq', displayName: 'not equal'}
     ]

    $scope.filterCondition={
        operator: $scope.operators[0]
    }
}

The HTML:

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator.value}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.displayName for operator in operators">
</select>
</body>

Javascript: How to check if a string is empty?

But for a better check:

if(str === null || str === '')
{
    //enter code here
}

How to embed a Google Drive folder in a website

For business/Gsuite apps or whatever they call them, you can specify the domain (had problem with 500 errors with the original answer when logged into multiple Google accounts).

<iframe 
  src="https://drive.google.com/a/YOUR_COMPANY_DOMAIN/embeddedfolderview?id=FOLDER-ID" 
  style="width:100%; height:600px; border:0;"
>
</iframe>

Check if number is prime number

You can also find range of prime numbers till the given number by user.

CODE:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Input a number to find Prime numbers\n");
            int inp = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\n Prime Numbers are:\n------------------------------");
            int count = 0;

            for (int i = 1; i <= inp; i++)
            {
                for (int j = 2; j < i; j++) // j=2 because if we divide any number with 1 the remaider will always 0, so skip this step to minimize time duration.
                {
                    if (i % j != 0)
                    {
                        count += 1;
                    }
                }
                if (count == (i - 2))
                    {
                        Console.Write(i + "\t"); 
                    }

                count = 0;
            }

            Console.ReadKey();

        }
    }

Prime numbers

What's the use of "enum" in Java?

an Enum is a safe-type so you can't assign a new value at the runtime. Moreover you can use it in a switch statement (like an int).

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

Here are another 2 options that allow you to invoke SaveChanges() in a for each loop.

The first option is use one DBContext to generate your list objects to iterate through, and then create a 2nd DBContext to call SaveChanges() on. Here is an example:

//Get your IQueryable list of objects from your main DBContext(db)    
IQueryable<Object> objects = db.Object.Where(whatever where clause you desire);

//Create a new DBContext outside of the foreach loop    
using (DBContext dbMod = new DBContext())
{   
    //Loop through the IQueryable       
    foreach (Object object in objects)
    {
        //Get the same object you are operating on in the foreach loop from the new DBContext(dbMod) using the objects id           
        Object objectMod = dbMod.Object.Find(object.id);

        //Make whatever changes you need on objectMod
        objectMod.RightNow = DateTime.Now;

        //Invoke SaveChanges() on the dbMod context         
        dbMod.SaveChanges()
    }
}

The 2nd option is to get a list of database objects from the DBContext, but to select only the id's. And then iterate through the list of id's (presumably an int) and get the object corresponding to each int, and invoke SaveChanges() that way. The idea behind this method is grabbing a large list of integers, is a lot more efficient then getting a large list of db objects and calling .ToList() on the entire object. Here is an example of this method:

//Get the list of objects you want from your DBContext, and select just the Id's and create a list
List<int> Ids = db.Object.Where(enter where clause here)Select(m => m.Id).ToList();

var objects = Ids.Select(id => db.Objects.Find(id));

foreach (var object in objects)
{
    object.RightNow = DateTime.Now;
    db.SaveChanges()
}

Generate list of all possible permutations of a string

Many of the previous answers used backtracking. This is the asymptotically optimal way O(n*n!) of generating permutations after initial sorting

class Permutation {

    /* runtime -O(n) for generating nextPermutaion
     * and O(n*n!) for generating all n! permutations with increasing sorted array as start
     * return true, if there exists next lexicographical sequence
     * e.g [a,b,c],3-> true, modifies array to [a,c,b]
     * e.g [c,b,a],3-> false, as it is largest lexicographic possible */
    public static boolean nextPermutation(char[] seq, int len) {
        // 1
        if (len <= 1)
            return false;// no more perm
        // 2: Find last j such that seq[j] <= seq[j+1]. Terminate if no such j exists
        int j = len - 2;
        while (j >= 0 && seq[j] >= seq[j + 1]) {
            --j;
        }
        if (j == -1)
            return false;// no more perm
        // 3: Find last l such that seq[j] <= seq[l], then exchange elements j and l
        int l = len - 1;
        while (seq[j] >= seq[l]) {
            --l;
        }
        swap(seq, j, l);
        // 4: Reverse elements j+1 ... count-1:
        reverseSubArray(seq, j + 1, len - 1);
        // return seq, add store next perm

        return true;
    }
    private static void swap(char[] a, int i, int j) {
        char temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    private static void reverseSubArray(char[] a, int lo, int hi) {
        while (lo < hi) {
            swap(a, lo, hi);
            ++lo;
            --hi;
        }
    }
    public static void main(String[] args) {
        String str = "abcdefg";
        char[] array = str.toCharArray();
        Arrays.sort(array);
        int cnt=0;
        do {
            System.out.println(new String(array));
            cnt++;
        }while(nextPermutation(array, array.length));
        System.out.println(cnt);//5040=7!
    }
    //if we use "bab"-> "abb", "bab", "bba", 3(#permutations)
}

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

Opening Android Settings programmatically

You can open with

startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);

You can return by pressing back button on device.

ESRI : Failed to parse source map

When I had this issue the cause was a relative reference to template files when using the ui.bootstrap.modal module.

templateUrl: 'js/templates/modal.html'

This works from a root domain (www.example.com) but when a path is added (www.example.com/path/) the reference breaks. The answer in my case was simply to making the reference absolute (js/ -> /js/).

templateUrl: '/js/templates/modal.html'

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Uncaught TypeError: Cannot assign to read only property

If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.

var globalObject = {
    name:"a",
    age:20
}
function() {
    let localObject = {
    name:'a',
    age:21
    }
    this.globalObject = localObject;
}

Reloading/refreshing Kendo Grid

The default/updated configuration/data of the widgets is set to automatically bind to an associated DataSource.

$('#GridId').data('kendoGrid').dataSource.read();
$('#GridId').data('kendoGrid').refresh();

Creating a system overlay window (always on top)

If anyone still reading this thread and not able to get this working, I'm very sorry to tell you this way to intercept motion event is considered as bug and fix in android >=4.2.

The motion event you intercepted, although has action as ACTION_OUTSIDE, return 0 in getX and getY. This means you can not see all the motion position on screen, nor can you do anything. I know the doc said It will get x and y, but the truth is it WILL NOT. It seems that this is to block key logger.

If anyone do have a workaround, please leave your comment.

ref: Why does ACTION_OUTSIDE return 0 everytime on KitKat 4.4.2?

https://code.google.com/p/android/issues/detail?id=72746

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

I've been using the following:

INSERT INTO [TableName] (ID, Name)
values (NEWID(), NEWID())
GO 10

It will add ten rows with unique GUIDs for ID and Name.

Note: do not end the last line (GO 10) with ';' because it will throw error: A fatal scripting error occurred. Incorrect syntax was encountered while parsing GO.

Appending a list or series to a pandas DataFrame as a row?

As mentioned here - https://kite.com/python/answers/how-to-append-a-list-as-a-row-to-a-pandas-dataframe-in-python, you'll need to first convert the list to a series then append the series to dataframe.

df = pd.DataFrame([[1, 2], [3, 4]], columns = ["a", "b"])
to_append = [5, 6]
a_series = pd.Series(to_append, index = df.columns)
df = df.append(a_series, ignore_index=True)

bundle install returns "Could not locate Gemfile"

Search for the Gemfile file in your project, go to that directory and then run "bundle install". prior to running this command make sure you have installed the gem "sudo gem install bundler"

Fixing slow initial load for IIS

I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.

Python NameError: name is not defined

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

Find the files existing in one directory but not in the other

This is a bit late but may help someone. Not sure if diff or rsync spit out just filenames in a bare format like this. Thanks to plhn for giving that nice solution which I expanded upon below.

If you want just the filenames so it's easy to just copy the files you need in a clean format, you can use the find command.

comm -23 <(find dir1 | sed 's/dir1/\//'| sort) <(find dir2 | sed 's/dir2/\//'| sort) | sed 's/^\//dir1/'

This assumes that both dir1 and dir2 are in the same parent folder. sed just removes the parent folder so you can compare apples with apples. The last sed just puts the dir1 name back.

If you just want files:

comm -23 <(find dir1 -type f | sed 's/dir1/\//'| sort) <(find dir2 -type f | sed 's/dir2/\//'| sort) | sed 's/^\//dir1/'

Similarly for directories:

comm -23 <(find dir1 -type d | sed 's/dir1/\//'| sort) <(find dir2 -type d | sed 's/dir2/\//'| sort) | sed 's/^\//dir1/'

Query to check index on a table

Created a stored procedure to list indexes for a table in database in SQL Server

create procedure _ListIndexes(@tableName nvarchar(200))
as
begin
/*
exec _ListIndexes '<YOUR TABLE NAME>'
*/
SELECT DB_NAME(DB_ID()) as DBName,SCH.name + '.' + TBL.name AS TableName,IDX.name as IndexName, IDX.type_desc AS IndexType,COL.Name as ColumnName,IC.*
    FROM sys.tables AS TBL 
         INNER JOIN sys.schemas AS SCH ON TBL.schema_id = SCH.schema_id 
         INNER JOIN sys.indexes AS IDX ON TBL.object_id = IDX.object_id 
         INNER JOIN sys.index_columns IC ON  IDX.object_id = IC.object_id and IDX.index_id = IC.index_id 
         INNER JOIN sys.columns COL ON ic.object_id = COL.object_id and IC.column_id = COL.column_id 
        where TBL.name = @tableName
    ORDER BY TableName,IDX.name

end

Get last 30 day records from today date in SQL Server

Add one more condition in where clause

SELECT * FROM  product 
WHERE pdate >= DATEADD(day,-30,GETDATE()) 
and   pdate <= getdate()

Or use DateDiff

SELECT * FROM  product 
WHERE DATEDIFF(day,pdate,GETDATE()) between 0 and 30 

"Repository does not have a release file" error

I opened up my Software & Updates program and switched from my country to the main servers like so:
Software & Updates screen

After I done this and run the sudo apt update commando again, my problems where gone.

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

I have occurred the same error look following example-

async.waterfall([function(waterCB) {
    waterCB(null);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.

Cheak your function parameters Below are a correct example.

async.waterfall([function(waterCB) {
    waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

Thanks

Auto-redirect to another HTML page

One of these will work...

_x000D_
_x000D_
<head>_x000D_
  <meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
_x000D_
_x000D_

...or it can done with JavaScript:

_x000D_
_x000D_
window.location.href = 'https://example.com/';
_x000D_
_x000D_
_x000D_

CSS3 :unchecked pseudo-class

The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!

Renaming a branch in GitHub

In my case, I needed an additional command,

git branch --unset-upstream

to get my renamed branch to push up to origin newname.

(For ease of typing), I first git checkout oldname. Then run the following:

git branch -m newname <br/> git push origin :oldname*or*git push origin --delete oldname
git branch --unset-upstream
git push -u origin newname or git push origin newname

This extra step may only be necessary because I (tend to) set up remote tracking on my branches via git push -u origin oldname. This way, when I have oldname checked out, I subsequently only need to type git push rather than git push origin oldname.

If I do not use the command git branch --unset-upstream before git push origin newbranch, git re-creates oldbranch and pushes newbranch to origin oldbranch -- defeating my intent.

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

How to make picturebox transparent?

One way to do this is by changing the parent of the overlapping picture box to the PictureBox over which it is lapping. Since the Visual Studio designer doesn't allow you to add a PictureBox to a PictureBox, this will have to be done in your code (Form1.cs) and within the Intializing function:

public Form1()
{
    InitializeComponent();
    pictureBox7.Controls.Add(pictureBox8);
    pictureBox8.Location = new Point(0, 0);
    pictureBox8.BackColor = Color.Transparent;
}

Just change the picture box names to what ever you need. This should return:

enter image description here

Getting list of parameter names inside python function

If you also want the values you can use the inspect module

import inspect

def func(a, b, c):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    print 'function name "%s"' % inspect.getframeinfo(frame)[2]
    for i in args:
        print "    %s = %s" % (i, values[i])
    return [(i, values[i]) for i in args]

>>> func(1, 2, 3)
function name "func"
    a = 1
    b = 2
    c = 3
[('a', 1), ('b', 2), ('c', 3)]

How to print / echo environment variables?

These need to go as different commands e.g.:

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

The expansion $NAME to empty string is done by the shell earlier, before running echo, so at the time the NAME variable is passed to the echo command's environment, the expansion is already done (to null string).

To get the same result in one command:

NAME=sam printenv NAME

Convert base64 png data to javascript file objects

Way 1: only works for dataURL, not for other types of url.

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
    console.log(file);
})

Both works in Chrome and Firefox.

Java escape JSON String?

Try to replace all the " and ' with a \ before them. Do this just for the msget object(String, I guess). Don't forget that \ must be escaped too.

Column/Vertical selection with Keyboard in SublimeText 3

The SublimeText 3 Column-Select plugin should be all you need. Install that, then make sure you have something like the following in your 'Default (OSX).sublime-keymap' file:

    // Column mode
    { "keys": ["ctrl+alt+up"], "command": "column_select", "args": {"by": "lines", "forward": false}},
    { "keys": ["ctrl+alt+down"], "command": "column_select", "args": {"by": "lines", "forward": true}},
    { "keys": ["ctrl+alt+pageup"], "command": "column_select", "args": {"by": "pages", "forward": false}},
    { "keys": ["ctrl+alt+pagedown"], "command": "column_select", "args": {"by": "pages", "forward": true}},
    { "keys": ["ctrl+alt+home"], "command": "column_select", "args": {"by": "all", "forward": false}},
    { "keys": ["ctrl+alt+end"], "command": "column_select", "args": {"by": "all", "forward": true}}

What exactly about it did not work for you?

How to make scipy.interpolate give an extrapolated result beyond the input range?

What about scipy.interpolate.splrep (with degree 1 and no smoothing):

>> tck = scipy.interpolate.splrep([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], k=1, s=0)
>> scipy.interpolate.splev(6, tck)
34.0

It seems to do what you want, since 34 = 25 + (25 - 16).

How to set python variables to true or false?

match_var = a==b

that should more than suffice

you cant use a - in a variable name as it thinks that is match (minus) var

match=1
var=2

print match-var  #prints -1

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

if you have lower version and getting problem importing project with high gradle version and want to run the project without updating gradle than

open your gradle file(Project) and do the small change

  dependencies {
           /*Higher Gradle version*/
//        classpath 'com.android.tools.build:gradle:3.0.0-alpha4'

        /*Add this line and remove the Higher one*/
        classpath 'com.android.tools.build:gradle:2.3.3'
    }

[2.3.3 is stand for your gradle version]

in your case change version to 3.2 or 3.2.0 something like that

Add a tooltip to a div

There are lots of answers to this question but still may be it will help someone. It is for all left, right, top, bottom positions.

Here is the css:

    .m-tb-5 {
        margin-top: 2px;
        margin-bottom: 2px;
    }
    [data-tooltip] {
        display: inline-block;
        position: relative;
        cursor: help;
        padding: 3px;
    }
    /* Tooltip styling */
    [data-tooltip]:before {
        content: attr(data-tooltip);
        display: none;
        position: absolute;
        background: #000;
        color: #fff;
        padding: 3px 6px;
        font-size: 10px;
        line-height: 1.4;
        min-width: 100px;
        text-align: center;
        border-radius: 4px;
    }
    /* Dynamic horizontal centering */
    [data-tooltip-position="top"]:before,
    [data-tooltip-position="bottom"]:before {
        left: 50%;
        -ms-transform: translateX(-50%);
        -moz-transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
    }
    /* Dynamic vertical centering */
    [data-tooltip-position="right"]:before,
    [data-tooltip-position="left"]:before {
        top: 50%;
        -ms-transform: translateY(-50%);
        -moz-transform: translateY(-50%);
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    [data-tooltip-position="top"]:before {
        bottom: 100%;
        margin-bottom: 6px;
    }
    [data-tooltip-position="right"]:before {
        left: 100%;
        margin-left: 6px;
    }
    [data-tooltip-position="bottom"]:before {
        top: 100%;
        margin-top: 6px;
    }
    [data-tooltip-position="left"]:before {
        right: 100%;
        margin-right: 6px;
    }

    /* Tooltip arrow styling/placement */
    [data-tooltip]:after {
        content: '';
        display: none;
        position: absolute;
        width: 0;
        height: 0;
        border-color: transparent;
        border-style: solid;
    }
    /* Dynamic horizontal centering for the tooltip */
    [data-tooltip-position="top"]:after,
    [data-tooltip-position="bottom"]:after {
        left: 50%;
        margin-left: -6px;
    }
    /* Dynamic vertical centering for the tooltip */
    [data-tooltip-position="right"]:after,
    [data-tooltip-position="left"]:after {
        top: 50%;
        margin-top: -6px;
    }
    [data-tooltip-position="top"]:after {
        bottom: 100%;
        border-width: 6px 6px 0;
        border-top-color: #000;
    }
    [data-tooltip-position="right"]:after {
        left: 100%;
        border-width: 6px 6px 6px 0;
        border-right-color: #000;
    }

    [data-tooltip-position="left"]:after {
        right: 100%;
        border-width: 6px 0 6px 6px;
        border-left-color: #000;
    }
    /* Show the tooltip when hovering */
    [data-tooltip]:hover:before,
    [data-tooltip]:hover:after {
        display: block;
        z-index: 50;
    }

And the HTML tag can be like this:

<p data-tooltip-position="right" data-tooltip="Some tooltip text here" title="">Text Here</p>

<p data-tooltip-position="left" data-tooltip="Some tooltip text here" title="">Text Here</p>

<p data-tooltip-position="top" data-tooltip="Some tooltip text here" title="">Text Here</p>

<p data-tooltip-position="bottom" data-tooltip="Some tooltip text here" title="">Text Here</p>

What is meaning of negative dbm in signal strength?

I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.

With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:

|--------|-------------------|
| P(dBm) |        P(mW)      |
|--------|-------------------|
|    50  |  100000           |    
|    40  |   10000           |    strong transmitter
|    30  |    1000           |             ^  
|    20  |     100           |             |
|    10  |      10           |             |
|     0  |       1           |
|   -10  |       0.1         |
|   -20  |       0.01        |
|   -30  |       0.001       |
|   -40  |       0.0001      |
|   -50  |       0.00001     |             |
|   -60  |       0.000001    |             |
|   -70  |       0.0000001   |             v
|   -80  |       0.00000001  |    sensitive receiver
|   -90  |       0.000000001 |
|--------|-------------------|

When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.

When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.

Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

For each conflicted file you get, you can specify

git checkout --ours -- <paths>
# or
git checkout --theirs -- <paths>

From the git checkout docs

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...

--ours
--theirs
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

Make error: missing separator

Just for grins, and in case somebody else runs into a similar error:

I got the infamous "missing separator" error because I had invoked a rule defining a function as

($eval $(call function,args))

rather than

$(eval $(call function,args))

i.e. ($ rather than $(.

Django: List field in model?

If you're on Django 1.10 or newer AND Postgres as your database, you can use ArrayField. It's better to use than django-taggit or other alternatives, as it's native to the Django framework. https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield

from django.db import models
from django.contrib.postgres.fields import ArrayField

class ChessBoard(models.Model):
    board = ArrayField(
        ArrayField(
            models.CharField(max_length=10, blank=True),
            size=8,
        ),
        size=8,
    )

If you're on Django 3.1 or newer they've added support for JSONField with most database backends (MariaDB 10.2.7+, MySQL 5.7.8+, Oracle, PostgreSQL, and SQLite 3.9.0+). You can use this to store your Array!

https://docs.djangoproject.com/en/3.1/ref/models/fields/#jsonfield

from django.db import models

class ChessBoard(models.Model):
    list_of_pieces = models.JSONField()

Windows CMD command for accessing usb?

You can access the USB drive by its drive letter. To know the drive letter you can run this command:

C:\>wmic logicaldisk where drivetype=2 get deviceid, volumename, description

From here you will get the drive letter (Device ID) of your USB drive.

For example if its F: then run the following command in command prompt to see its contents:

C:\> F:

F:\> dir

Escaping ampersand character in SQL string

set escape on
... node_name = 'Geometric Vectors \& Matrices' ...

or alternatively:

set define off
... node_name = 'Geometric Vectors & Matrices' ...

The first allows you to use the backslash to escape the &.

The second turns off & "globally" (no need to add a backslash anywhere). You can turn it on again by set define on and from that line on the ampersands will get their special meaning back, so you can turn it off for some parts of the script and not for others.

MySQL DROP all tables, ignoring foreign keys

every approach above includes a lot more work than this one AFAICT...

( mysqldump --add-drop-table --no-data -u root -p database | grep 'DROP TABLE' ) > ./drop_all_tables.sql
mysql -u root -p database < ./drop_all_tables.sql

Create html documentation for C# code

The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).

Convert list of dictionaries to a pandas DataFrame

For converting a list of dictionaries to a pandas DataFrame, you can use "append":

We have a dictionary called dic and dic has 30 list items (list1, list2,…, list30)

  1. step1: define a variable for keeping your result (ex: total_df)
  2. step2: initialize total_df with list1
  3. step3: use "for loop" for append all lists to total_df
total_df=list1
nums=Series(np.arange(start=2, stop=31))
for num in nums:
    total_df=total_df.append(dic['list'+str(num)])

Changing the URL in react-router v4 without using Redirect or Link

This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.

<GridTile
  key={video_id}
  title={video_title}
  containerElement={<Link to={`/player/${video_id}`}/>}
 >

ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )

Change multiple files

If you are able to run a script, here is what I did for a similar situation:

Using a dictionary/hashMap (associative array) and variables for the sed command, we can loop through the array to replace several strings. Including a wildcard in the name_pattern will allow to replace in-place in files with a pattern (this could be something like name_pattern='File*.txt' ) in a specific directory (source_dir). All the changes are written in the logfile in the destin_dir

#!/bin/bash
source_dir=source_path
destin_dir=destin_path
logfile='sedOutput.txt'
name_pattern='File.txt'

echo "--Begin $(date)--" | tee -a $destin_dir/$logfile
echo "Source_DIR=$source_dir destin_DIR=$destin_dir "

declare -A pairs=( 
    ['WHAT1']='FOR1'
    ['OTHER_string_to replace']='string replaced'
)

for i in "${!pairs[@]}"; do
    j=${pairs[$i]}
    echo "[$i]=$j"
    replace_what=$i
    replace_for=$j
    echo " "
    echo "Replace: $replace_what for: $replace_for"
    find $source_dir -name $name_pattern | xargs sed -i "s/$replace_what/$replace_for/g" 
    find $source_dir -name $name_pattern | xargs -I{} grep -n "$replace_for" {} /dev/null | tee -a $destin_dir/$logfile
done

echo " "
echo "----End $(date)---" | tee -a $destin_dir/$logfile

First, the pairs array is declared, each pair is a replacement string, then WHAT1 will be replaced for FOR1 and OTHER_string_to replace will be replaced for string replaced in the file File.txt. In the loop the array is read, the first member of the pair is retrieved as replace_what=$i and the second as replace_for=$j. The find command searches in the directory the filename (that may contain a wildcard) and the sed -i command replaces in the same file(s) what was previously defined. Finally I added a grep redirected to the logfile to log the changes made in the file(s).

This worked for me in GNU Bash 4.3 sed 4.2.2 and based upon VasyaNovikov's answer for Loop over tuples in bash.

Open images? Python

Instead of

Image.open(picture.jpg)
Img.show

You should have

from PIL import Image

#...

img = Image.open('picture.jpg')
img.show()

You should probably also think about an other system to show your messages, because this way it will be a lot of manual work. Look into string substitution (using %s or .format()).

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

Getting current unixtimestamp using Moment.js

For anyone who finds this page looking for unix timestamp w/ milliseconds, the documentation says

moment().valueOf()

or

+moment();

you can also get it through moment().format('x') (or .format('X') [capital X] for unix seconds with decimal milliseconds), but that will give you a string. Which moment.js won't actually parse back afterwards, unless you convert/cast it back to a number first.

Getting time span between two times in C#?

string startTime = "7:00 AM";
string endTime = "2:00 PM";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Will output: 07:00:00.

It also works if the user input military time:

string startTime = "7:00";
string endTime = "14:00";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Outputs: 07:00:00.

To change the format: duration.ToString(@"hh\:mm")

More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

Addendum:

Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".

eclipse won't start - no java virtual machine was found

This happened to me also. And I found the javaw.exe in C:\Windows\System32 got deleted after the windows update. Copied one more time and Eclipse started all fine.

How do I `jsonify` a list in Flask?

This is working for me. Which version of Flask are you using?

from flask import jsonify

...

@app.route('/test/json')
def test_json():
    list = [
            {'a': 1, 'b': 2},
            {'a': 5, 'b': 10}
           ]
    return jsonify(results = list)

Most useful NLog configurations

Configure NLog via XML, but Programmatically

What? Did you know that you can specify the NLog XML directly to NLog from your app, as opposed to having NLog read it from the config file? Well, you can. Let's say that you have a distributed app and you want to use the same configuration everywhere. You could keep a config file in each location and maintain it separately, you could maintain one in a central location and push it out to the satellite locations, or you could probably do a lot of other things. Or, you could store your XML in a database, get it at app startup, and configure NLog directly with that XML (maybe checking back periodically to see if it had changed).

  string xml = @"<nlog>
                   <targets>
                     <target name='console' type='Console' layout='${message}' />
                   </targets>

                   <rules>
                     <logger name='*' minlevel='Error' writeTo='console' />
                   </rules>
                 </nlog>";

  StringReader sr = new StringReader(xml);
  XmlReader xr = XmlReader.Create(sr);
  XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null);
  LogManager.Configuration = config;
  //NLog is now configured just as if the XML above had been in NLog.config or app.config

  logger.Trace("Hello - Trace"); //Won't log
  logger.Debug("Hello - Debug"); //Won't log
  logger.Info("Hello - Info");   //Won't log
  logger.Warn("Hello - Warn");   //Won't log
  logger.Error("Hello - Error"); //Will log
  logger.Fatal("Hello - Fatal"); //Will log

  //Now let's change the config (the root logging level) ...
  string xml2 = @"<nlog>
                  <targets>
                     <target name='console' type='Console' layout='${message}' />
                   </targets>

                   <rules>
                     <logger name='*' minlevel='Trace' writeTo='console' />
                   </rules>
                 </nlog>";

  StringReader sr2 = new StringReader(xml2);
  XmlReader xr2 = XmlReader.Create(sr2);
  XmlLoggingConfiguration config2 = new XmlLoggingConfiguration(xr2, null);
  LogManager.Configuration = config2;

  logger.Trace("Hello - Trace"); //Will log
  logger.Debug("Hello - Debug"); //Will log
  logger.Info("Hello - Info");   //Will log
  logger.Warn("Hello - Warn");   //Will log
  logger.Error("Hello - Error"); //Will log
  logger.Fatal("Hello - Fatal"); //Will log

I'm not sure how robust this is, but this example provides a useful starting point for people that might want to try configuring like this.

PHP new line break in emails

I know this is an old question but anyway it might help someone.

I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).

echo "line 1".PHP_EOL."line 2".PHP_EOL;

If you're planning to show the result in a browser then you have to use "<br>".

EDIT: since your exact question is about emails, things are a bit different. For pure text emails see Brendan Bullen's accepted answer. For HTML emails you simply use HTML formatting.

git pull error "The requested URL returned error: 503 while accessing"

Try disabling all the system wide HTTP and HTTPS proxies:

export http_proxy="" 
export https_proxy=""
export HTTP_PROXY=""
export HTTPS_PROXY=""

Error: Configuration with name 'default' not found in Android Studio

I also faced the same problem and the problem was that the libraries were missing in some of the following files.

settings.gradle, app/build.gradle, package.json, MainApplication.java

Suppose the library is react-native-vector-icons then it should be mentioned in following files;

In app/build.gradle file under dependencies section add:

compile project(':react-native-vector-icons')

In settings.gradle file under android folder, add the following:

include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')

In MainApplication.java, add the following:

Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;

and then add: new VectorIconsPackage() in getPackages() method.

Check if a number has a decimal place/is a whole number

Simple, but effective!

Math.floor(number) === number;

How to convert a UTF-8 string into Unicode?

I have string that displays UTF-8 encoded characters

There is no such thing in .NET. The string class can only store strings in UTF-16 encoding. A UTF-8 encoded string can only exist as a byte[]. Trying to store bytes into a string will not come to a good end; UTF-8 uses byte values that don't have a valid Unicode codepoint. The content will be destroyed when the string is normalized. So it is already too late to recover the string by the time your DecodeFromUtf8() starts running.

Only handle UTF-8 encoded text with byte[]. And use UTF8Encoding.GetString() to convert it.

How to set max and min value for Y axis

Since none of the suggestions above helped me with charts.js 2.1.4, I solved it by adding the value 0 to my data set array (but no extra label):

statsData.push(0);

[...]

var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        datasets: [{
            data: statsData,
[...]

How to get box-shadow on left & right sides only

I wasn't satisfied with the rounded top and bottom to the shadow present in Deefour's solution so created my own.

inset box-shadow creates a nice uniform shadow with the top and bottom cut off.

To use this effect on the sides of your element, create two pseudo elements :before and :after positioned absolutely on the sides of the original element.

_x000D_
_x000D_
div:before, div:after {
  content: " ";
  height: 100%;
  position: absolute;
  top: 0;
  width: 15px;
}
div:before {
  box-shadow: -15px 0 15px -15px inset;
  left: -15px;
}
div:after {
  box-shadow: 15px 0 15px -15px inset;
  right: -15px;
}

div {
  background: #EEEEEE;
  height: 100px;
  margin: 0 50px;
  width: 100px;
  position: relative;
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


Edit

Depending on your design, you may be able to use clip-path, as shown in @Luke's answer. However, note that in many cases this still results in the shadow tapering off at the top and bottom as you can see in this example:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  background: #EEE;
  box-shadow: 0 0 15px 0px #000;
  clip-path: inset(0px -15px 0px -15px);
  position: relative;
  margin: 0 50px;
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Getting the WordPress Post ID of current post

global $post;
echo $post->ID;

Logical Operators, || or OR?

I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...

Let's say the code looks like this:

$positions = $this->positions() || [];

You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.

If you need to get value of $this->positions() or empty array, you have to use:

$positions = $this->positions() or [];

EDIT:

The above example doesn't work as intended but the truth is that || and or is not the same... Try this:

<?php

function returnEmpty()
{
  //return "string";
  //return [1];
  return null;
}

$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];

var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";

This is the result:

bool(false)
NULL
array(0) {
}

So, actually the third option ?: is the correct solution when you want to set returned value or empty array.

$positions = $this->positions() ?: [];

Tested with PHP 7.2.1

Reusing output from last command in Bash

You can use $(!!) to recompute (not re-use) the output of the last command.

The !! on its own executes the last command.

$ echo pierre
pierre
$ echo my name is $(!!)
echo my name is $(echo pierre)
my name is pierre

Clearing content of text file using php

//create a file handler by opening the file
$myTextFileHandler = @fopen("filelist.txt","r+");

//truncate the file to zero
//or you could have used the write method and written nothing to it
@ftruncate($myTextFileHandler, 0);

//use location header to go back to index.html
header("Location:index.html");

I don't exactly know where u want to show the result.

How to copy marked text in notepad++

It's not possible with Notepad but HERE'S THE EASY SOLUTION:

You will need the freeware Expresso v3.1 http://www.ultrapico.com/ExpressoDownload.htm

I resorted to another piece of free software: Expresso by Ultrapico.

  1. Once installed go in the tab "Test Mode".
  2. Copy your REGEX into the "Regular expressions" pane.
  3. Paste your whole text to be searched into the "Sample text" pane of Expresso,

  4. Press the "Run match" button. Right click in the "Search results pane" and "Export to..." or "Copy matched text to clipboard".

N.B.: The original author is @Andreas Jansson but it is hidden in a comment, so since this page is high ranked in Google Search I leave it here for others.

How can I hide or encrypt JavaScript code?

If you have anything in particular you want to hide (like a proprietary algorithm), put that on the server, or put it in a Flash movie and call it with JavaScript. Writing ActionScript is very similar to writing JavaScript, and you can communicate between JavaScript and ActionScript. You can do the same with Silverlight, but Silverlight doesn't have the penetration Flash does.

However, remember that any mobile phones can run your JavaScript, but not Silverlight or Flash, so you're crippling your mobile users if you go with Flash or Silverlight.

How to disassemble a memory range with GDB?

If all that you want is to see the disassembly with the INTC call, use objdump -d as someone mentioned but use the -static option when compiling. Otherwise the fopen function is not compiled into the elf and is linked at runtime.

Understanding dict.copy() - shallow or deep?

In your second part, you should use new = original.copy()

.copy and = are different things.

c# razor url parameter from view

You can use the following:

Request.Params["paramName"]

See also: When do Request.Params and Request.Form differ?

Regular Expression Match to test for a valid year

/^\d{4}$/ This will check if a string consists of only 4 numbers. In this scenario, to input a year 989, you can give 0989 instead.

Best Practice: Access form elements by HTML id or name attribute?

name field works well. It provides a reference to the elements.

parent.children - Will list all elements with a name field of the parent. parent.elements - Will list only form elements such as input-text, text-area, etc

_x000D_
_x000D_
var form = document.getElementById('form-1');_x000D_
console.log(form.children.firstname)_x000D_
console.log(form.elements.firstname)_x000D_
console.log(form.elements.progressBar); // undefined_x000D_
console.log(form.children.progressBar);_x000D_
console.log(form.elements.submit); // undefined
_x000D_
<form id="form-1">_x000D_
  <input type="text" name="firstname" />_x000D_
  <input type="file" name="file" />_x000D_
  <progress name="progressBar" value="20" min="0" max="100" />_x000D_
  <textarea name="address"></textarea>_x000D_
  <input type="submit" name="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note: For .elements to work, the parent needs to be a <form> tag. Whereas, .children will work on any HTML-element - such as <div>, <span>, etc.

Good Luck...

iPhone: Setting Navigation Bar Title

There's one issue with using self.title = @"title";

If you're using Navigation Bar along with Tab bar, the above line also changes the label for the Tab Bar Item. To avoid this, use what @testing suggested

self.navigationItem.title = @"MyTitle";

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

Source file not compiled Dev C++

I guess you're using windows 7 with the Orwell Dev CPP

This version of Dev CPP is good for windows 8 only. However on Windows 7 you need the older version of it which is devcpp-4.9.9.2_setup.exe Download it from the link and use it. (Don't forget to uninstall any other version already installed on your pc) Also note that the older version does not work with windows 8.

Linq where clause compare only date value without time value

&& x.DateTimeValueColumn <= DateTime.Now

This is supported so long as your schema is correct

&& x.DateTimeValueColumn.Value.Date <=DateTime.Now

How can I set the default value for an HTML <select> element?

This is how I did it...

<form action="../<SamePage>/" method="post">

<?php
    if ( $_POST['drop_down'] == "")
    {
    $selected = "";
    }
    else
    {
    $selected = "selected";
    }
?>

<select name="select" size="1">

  <option value="1" <?php $selected ?>>One</option>
     ////////  OR  ////////
  <option value="2" $selected>Two</option>

</select>
</form>

Ruby on Rails - Import Data from a CSV file

If you want to Use SmartCSV

all_data = SmarterCSV.process(
             params[:file].tempfile, 
             { 
               :col_sep => "\t", 
               :row_sep => "\n" 
             }
           )

This represents tab delimited data in each row "\t" with rows separated by new lines "\n"

MySQL with Node.js

connect the mysql database by installing a library. here, picked the stable and easy to use node-mysql module.

npm install [email protected]

var http = require('http'),
   mysql = require('mysql');

var sqlInfo = {
   host: 'localhost',
   user: 'root',
   password: 'urpass',
   database: 'dbname'
}
client = mysql.createConnection(sqlInfo);

client.connect();

For NodeJS mysql connecting and querying example

How to Compare a long value is equal to Long value

long a = 1111;
Long b = new Long(1113);

System.out.println(b.equals(a) ? "equal" : "different");
System.out.println((long) b == a ? "equal" : "different");

Appending to list in Python dictionary

list.append returns None, since it is an in-place operation and you are assigning it back to dates_dict[key]. So, the next time when you do dates_dict.get(key, []).append you are actually doing None.append. That is why it is failing. Instead, you can simply do

dates_dict.setdefault(key, []).append(date)

But, we have collections.defaultdict for this purpose only. You can do something like this

from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
    dates_dict[key].append(date)

This will create a new list object, if the key is not found in the dictionary.

Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.

Read and write a String from text file

write in ViewDidLoad

var error: NSError?
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var documentsDirectory = paths.first as String
var dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")

if !NSFileManager.defaultManager().fileExistsAtPath(dataPath) {
    NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: &error)
} else {
    println("not creted or exist")
}

func listDocumentDirectoryfiles() -> [String] {
    if let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
        let myFilePath = documentDirectory.stringByAppendingPathComponent("MyFolder")
        return NSFileManager.defaultManager().contentsOfDirectoryAtPath(myFilePath, error: nil) as [String]
    }
    return []
}

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

Referring to @dylanvanw answer. You might still out of luck. I found that you might have a different path that you have installed Python. In my case, I have to move Chromedriver.exe from the cache path (C:\Users\Poom.wdm\drivers\chromedriver\win32\84.0.4147.30) to C:\Python38 then it work!

Root user/sudo equivalent in Cygwin?

Use this to get an admin window with either bash or cmd running, from any directories context menue. Just right click on a directory name, and select the entry or hit the highlited button.

This is based on the chere tool and the unfortunately not working answer (for me) from link_boy. It works fine for me using Windows 8,

A side effect is the different color in the admin cmd window. To use this on bash, you can change the .bashrc file of the admin user.

I coudln't get the "background" version (right click into an open directory) to run. Feel free to add it.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash]
@="&Bash Prompt Here"
"Icon"="C:\\cygwin\\Cygwin.ico"

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash\command]
@="C:\\cygwin\\bin\\bash -c \"/bin/xhere /bin/bash.exe '%L'\""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash_root]
@="&Root Bash Prompt Here"
"Icon"="C:\\cygwin\\Cygwin.ico"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash_root\command]
@="runas /savecred /user:administrator \"C:\\cygwin\\bin\\bash -c \\\"/bin/xhere /bin/bash.exe '%L'\\\"\""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd]
@="&Command Prompt Here"

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd\command]
@="cmd.exe /k cd %L"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd_root]
@="Roo&t Command Prompt Here"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd_root\command]
@="runas /savecred /user:administrator \"cmd.exe /t:1E /k cd %L\""

Least common multiple for 3 or more numbers

Here is a C# port of Virgil Disgr4ce's implemenation:

public class MathUtils
{
    /// <summary>
    /// Calculates the least common multiple of 2+ numbers.
    /// </summary>
    /// <remarks>
    /// Uses recursion based on lcm(a,b,c) = lcm(a,lcm(b,c)).
    /// Ported from http://stackoverflow.com/a/2641293/420175.
    /// </remarks>
    public static Int64 LCM(IList<Int64> numbers)
    {
        if (numbers.Count < 2)
            throw new ArgumentException("you must pass two or more numbers");
        return LCM(numbers, 0);
    }

    public static Int64 LCM(params Int64[] numbers)
    {
        return LCM((IList<Int64>)numbers);
    }

    private static Int64 LCM(IList<Int64> numbers, int i)
    {
        // Recursively iterate through pairs of arguments
        // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))

        if (i + 2 == numbers.Count)
        {
            return LCM(numbers[i], numbers[i+1]);
        }
        else
        {
            return LCM(numbers[i], LCM(numbers, i+1));
        }
    }

    public static Int64 LCM(Int64 a, Int64 b)
    {
        return (a * b / GCD(a, b));
    }

    /// <summary>
    /// Finds the greatest common denominator for 2 numbers.
    /// </summary>
    /// <remarks>
    /// Also from http://stackoverflow.com/a/2641293/420175.
    /// </remarks>
    public static Int64 GCD(Int64 a, Int64 b)
    {
        // Euclidean algorithm
        Int64 t;
        while (b != 0)
        {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }
}'

'NOT NULL constraint failed' after adding to models.py

Since you added a new property to the model, you must first delete the database. Then manage.py migrations then manage.py migrate.

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

As I don't plan to support old MS IE versions at all, I've simply replaced all references to browser.msie with false. Not a nice solution, I know, but it works for me.

(Actually, they appeared as !browser.msie, which could be omitted from the conditions.)

JQUERY ajax passing value from MVC View to Controller

Try using the data option of the $.ajax function. More info here.

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Django URL Redirect

You can try the Class Based View called RedirectView

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

Notice how as url in the <url_to_home_view> you need to actually specify the url.

permanent=False will return HTTP 302, while permanent=True will return HTTP 301.

Alternatively you can use django.shortcuts.redirect

Update for Django 2+ versions

With Django 2+, url() is deprecated and replaced by re_path(). Usage is exactly the same as url() with regular expressions. For replacements without the need of regular expression, use path().

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')

Checking if an object is a number in C#

While writing my own object.IsNumeric() extension method based on Saul Dolgin's answer to this question I ran into a potential issue in that you will get an OverflowException if you try it with double.MaxValue or double.MinValue.

My "solution" was to combine the accepted answer from Noldorin with the one from Saul Dolgin and add a pattern matching switch before trying to parse anything (and use some C#7 goodness to tidy up a bit):

public static bool IsNumeric(this object obj)
{
    if (obj == null) return false;

    switch (obj)
    {
        case sbyte _: return true;
        case byte _: return true;
        case short _: return true;
        case ushort _: return true;
        case int _: return true;
        case uint _: return true;
        case long _: return true;
        case ulong _: return true;
        case float _: return true;
        case double _: return true;
        case decimal _: return true;
    }

    string s = Convert.ToString(obj, CultureInfo.InvariantCulture);

    return double.TryParse(s, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out double _);
}

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

Make sure the target window that you (or Facebook) is posting a message to, has completed loading. Most of the times I've gotten this error were when an iframe I was sending messages to had failed to load.

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

In my case, I was getting value of <input type="text"> with JQuery and I did it like this:

var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
 "firstName": inputFirstName[0] , "email": inputEmail[0].value}

And I was constantly getting this exception

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream@39cb6c98; line: 1, column: 54] (through reference chain: com.springboot.domain.User["firstName"]).

And I banged my head for like an hour until I realised that I forgot to write .value after this"firstName": inputFirstName[0].

So, the correct solution was:

var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
 "firstName": inputFirstName[0].value , "email": inputEmail[0].value}

I came here because I had this problem and I hope I save someone else hours of misery.

Cheers :)

In Perl, how to remove ^M from a file?

This one liner replaces all the ^M characters:

dos2unix <file-name>

You can call this from inside Perl or directly on your Unix prompt.

'str' object has no attribute 'decode'. Python 3 error?

You are trying to decode an object that is already decoded. You have a str, there is no need to decode from UTF-8 anymore.

Simply drop the .decode('utf-8') part:

header_data = data[1][0][1]

As for your fetch() call, you are explicitly asking for just the first message. Use a range if you want to retrieve more messages. See the documentation:

The message_set options to commands below is a string specifying one or more messages to be acted upon. It may be a simple message number ('1'), a range of message numbers ('2:4'), or a group of non-contiguous ranges separated by commas ('1:3,6:9'). A range can contain an asterisk to indicate an infinite upper bound ('3:*').

Replace all double quotes within String

The following regex will work for both:

  text = text.replaceAll("('|\")", "\\\\$1");

How to add new contacts in android

These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.

It's up to the user to save the newly created contact.

You can read about it here: https://developer.android.com/training/contacts-provider/modify-data.html

Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

contactIntent
        .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
        .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");

startActivityForResult(contactIntent, 1);

startActivityForResult() gives you the opportunity to see the result.

I've noticed the resultCode works on >5.0 devices,

but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).

Which I understand is the default return if an activity doesn't expect to return anything.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == 1)
    {
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
        }
    }
}

Split output of command by columns using Bash?

try

ps |&
while read -p first second third fourth etc ; do
   if [[ $first == '11383' ]]
   then
       echo got: $fourth
   fi       
done

How to fix docker: Got permission denied issue

sudo chmod 666 /var/run/docker.sock

this helped me while i was getting error even to log in to the docker But now this works completely fine in my system.

Bootstrap: adding gaps between divs

I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>

Laravel 5.2 redirect back with success message

You can use laravel MessageBag to add our own messages to existing messages.

To use MessageBag you need to use:

use Illuminate\Support\MessageBag;

In the controller:

MessageBag $message_bag

$message_bag->add('message', trans('auth.confirmation-success'));

return redirect('login')->withSuccess($message_bag);

Hope it will help some one.

  • Adi

Get Substring - everything before certain char

Use the split function.

static void Main(string[] args)
{
    string s = "223232-1.jpg";
    Console.WriteLine(s.Split('-')[0]);
    s = "443-2.jpg";
    Console.WriteLine(s.Split('-')[0]);
    s = "34443553-5.jpg";
    Console.WriteLine(s.Split('-')[0]);

Console.ReadKey();
}

If your string doesn't have a - then you'll get the whole string.

Warning: push.default is unset; its implicit value is changing in Git 2.0

It's explained in great detail in the docs, but I'll try to summarize:

  • matching means git push will push all your local branches to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.

  • simple means git push will push only the current branch to the one that git pull would pull from, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.

This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, it only affects what happens when you don't specify which branches you want to push.

fe_sendauth: no password supplied

After making changes to the pg_hba.conf or postgresql.conf files, the cluster needs to be reloaded to pick up the changes.

From the command line: pg_ctl reload

From within a db (as superuser): select pg_reload_conf();

From PGAdmin: right-click db name, select "Reload Configuration"

Note: the reload is not sufficient for changes like enabling archiving, changing shared_buffers, etc -- those require a cluster restart.

How to check if file already exists in the folder

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"

Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.

If System.IO.File.Exists(SavePath) Then
   'The file exists
Else
    'the file doesn't exist
End If

If using maven, usually you put log4j.properties under java or resources?

If your log4j.properties or log4j.xml file not found under src/main/resources use this PropertyConfigurator.configure("log4j.xml");

   PropertyConfigurator.configure("log4j.xml");
   Logger logger = LoggerFactory.getLogger(MyClass.class);
   logger.error(message);

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

Decorators with parameters?

Writing a decorator that works with and without parameter is a challenge because Python expects completely different behavior in these two cases! Many answers have tried to work around this and below is an improvement of answer by @norok2. Specifically, this variation eliminates the use of locals().

Following the same example as given by @norok2:

import functools

def multiplying(f_py=None, factor=1):
    assert callable(f_py) or f_py is None
    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return factor * func(*args, **kwargs)
        return wrapper
    return _decorator(f_py) if callable(f_py) else _decorator


@multiplying
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying()
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying(factor=10)
def summing(x): return sum(x)

print(summing(range(10)))
# 450

Play with this code.

The catch is that the user must supply key,value pairs of parameters instead of positional parameters and the first parameter is reserved.

jQuery validation plugin: accept only alphabetical characters?

Just a small addition to Nick's answer (which works great !) :

If you want to allow spaces in between letters, for example , you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");       

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

  1. Install Entity framework to the current project using the below command: PM> Install-Package EntityFramework -IncludePrerelease

  2. Add a class "MyDBContext" in the Model folder as given below:

    public class MyDBContext : DbContext { public MyDBContext() { } }

  3. Now enable migrations for the current project with the below command: PM> enable-migrations

mysql count group by having

Maybe

SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

although that would not be the sum of all the movies, just how many have 4 genre's.

So maybe you want

SELECT sum(
    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total

What is String pool in Java?

When the JVM loads classes, or otherwise sees a literal string, or some code interns a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like

String s = "test";
return (s == "test");

it'll return true, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals, as there's a single reference comparison rather than a bunch of char comparisons.

You can add a string to the pool by calling String.intern(), which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern) will be equal to any identical literal. For example:

String s1 = "test";
String s2 = new String("test");  // "new String" guarantees a different object

System.out.println(s1 == s2);  // should print "false"

s2 = s2.intern();
System.out.println(s1 == s2);  // should print "true"

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

What's the difference between Apache's Mesos and Google's Kubernetes

Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:

  • pods — a way to group containers together
  • replication controllers — a way to handle the lifecycle of containers
  • labels — a way to find and query containers, and
  • services — a set of containers performing a common function.

So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.

With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.

Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).

When asked, I tend to say:

  1. Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).

  2. If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.

  3. Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.

How to spawn a process and capture its STDOUT in .NET?

Here's some full and simple code to do this. This worked fine when I used it.

var processStartInfo = new ProcessStartInfo
{
    FileName = @"C:\SomeProgram",
    Arguments = "Arguments",
    RedirectStandardOutput = true,
    UseShellExecute = false
};
var process = Process.Start(processStartInfo);
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();

Note that this only captures standard output; it doesn't capture standard error. If you want both, use this technique for each stream.

Changing SqlConnection timeout

You can add Connection Timeout=180; to your connection string

How to get json key and value in javascript?

you have parse that Json string using JSON.parse()

..
}).done(function(data){
    obj = JSON.parse(data);
    alert(obj.jobtitel);
});

jQuery get text as number

If anyone came here trying to do this with a decimal like me:

myFloat = parseFloat(myString);

If you just need an Int, that's well covered in the other answers.

Bootstrap: Position of dropdown menu relative to navbar item

Even if it s late i hope i can help someone. if dropdown menu or submenu is on the right side of screen it's open on the left side, if menu or submenu is on the left it's open on the right side.

$(".dropdown-toggle").on("click", function(event){//"show.bs.dropdown"
    var liparent=$(this.parentElement);
    var ulChild=liparent.find('ul');
    var xOffset=liparent.offset().left;
    var alignRight=($(document).width()-xOffset)<xOffset;


    if (liparent.hasClass("dropdown-submenu"))
    {
        ulChild.css("left",alignRight?"-101%":"");
    }
    else
    {                
        ulChild.toggleClass("dropdown-menu-right",alignRight);
    }

});

To detect vertical position you can also add

$( document ).ready(function() {
        var liparent=$(".dropdown");
    var yOffset=liparent.offset().top;
        var toTop=($(document).height()-yOffset)<yOffset;
    liparent.toggleClass("dropup",toTop);
});

https://jsfiddle.net/jd1100/rf9zvdhg/28/

Case statement in MySQL

Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

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

I had the same issue. After much searching I decided to reconfigure my server in Eclipse. (ie clean it as suggested by Benson Go to Project Explorer, Servers and Delete (ensure you also delete contents on disk) Then go to Windows->Preferences->Server->Runtime Environments Remove the Tomcat server and then add it back in.

This cleans up the server.xml, webxml, context.xml files. It basically rewrites them. Something in one of mine (or multiple things) were awry and this fixes it. A bit simpler than trying to find the offending tags/lines

Add a "sort" to a =QUERY statement in Google Spreadsheets

You can use ORDER BY clause to sort data rows by values in columns. Something like

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")

If you’d like to order by some columns descending, others ascending, you can add desc/asc, ie:

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")

What is Ruby's double-colon `::`?

It is all about preventing definitions from clashing with other code linked in to your project. It means you can keep things separate.

For example you can have one method called "run" in your code and you will still be able to call your method rather than the "run" method that has been defined in some other library that you have linked in.

When to use "new" and when not to, in C++?

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.

Make Frequency Histogram for Factor Variables

Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country

barplot(summary(df$Country))

Passing a local variable from one function to another

First way is

function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;

// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }

Second way is

var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

Can we locate a user via user's phone number in Android?

I checked play.google.com/store/apps/details?id=and.p2l&hl=en They are not locating the user's current location at all. So based on the number itself they are judging the location of the user. Like if the number starts from 240 ( in US) they they are saying location is Maryland but the person can be in California. So i don't think they are getting the user's location through LocationListner of Java at all.

Setting up a cron job in Windows

There's pycron which I really as a Cron implementation for windows, but there's also the built in scheduler which should work just fine for what you need (Control Panel -> Scheduled Tasks -> Add Scheduled Task).

C++ alignment when printing cout <<

C++20 std::format options <, ^ and >

According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:

// left: "42    "
std::cout << std::format("{:<6}", 42);

// right: "    42"
std::cout << std::format("{:>6}", 42);

// center: "  42  "
std::cout << std::format("{:^6}", 42);

More information at: std::string formatting like sprintf

How to make google spreadsheet refresh itself every 1 minute?

If you're on the New Google Sheets, this is all you need to do, according to the docs:

change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.

This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.

If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:

=GoogleClock()

EDIT to include old and new Google Sheets and change to =GoogleClock().

Opening a .ipynb.txt File

go to cmd get into file directory and type jupyter notebook filename.ipynb in my case it open code editor and provide local host connection string copy that string and paste in any browser!done

Using group by on multiple columns

Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.

The GROUP BY clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:

-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

-- GROUP BY with two parameters:
SELECT
    column_name1,
    column_name2,
    AGGREGATE_FUNCTION(column_name3)
FROM
    table_name
GROUP BY
    column_name1,
    column_name2;

Remember this order:

  1. SELECT (is used to select data from a database)

  2. FROM (clause is used to list the tables)

  3. WHERE (clause is used to filter records)

  4. GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)

  5. HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)

  6. ORDER BY (keyword is used to sort the result-set)

You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.

Aggregate Functions are:

MIN() returns the smallest value in a given column

MAX() returns the maximum value in a given column.

SUM() returns the sum of the numeric values in a given column

AVG() returns the average value of a given column

COUNT() returns the total number of values in a given column

COUNT(*) returns the number of rows in a table

SQL script examples about using aggregate functions:

Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING clause and the GROUP BY clause to accomplish this:

SELECT 
    orderId, SUM(unitPrice * qty) Total
FROM
    OrderDetails
GROUP BY orderId
HAVING Total > 950;

Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT function and the GROUP BY, ORDER BY clauses and ASC:

SELECT 
    customerId, COUNT(*)
FROM
    Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;

Retrieve the category that has an average Unit Price greater than $10, using AVG function combine with GROUP BY and HAVING clauses:

SELECT 
    categoryName, AVG(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;

Getting the less expensive product by each category, using the MIN function in a subquery:

SELECT categoryId,
       productId,
       productName,
       unitPrice
FROM Products p1
WHERE unitPrice = (
                SELECT MIN(unitPrice)
                FROM Products p2
                WHERE p2.categoryId = p1.categoryId)

The following statement groups rows with the same values in both categoryId and productId columns:

SELECT 
    categoryId, categoryName, productId, SUM(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId

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

boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
   alltrue &= booleanArray[i];

I think this looks ok and behaves well...

Send email using java

The following code works very well.Try this as a java application with javamail-1.4.5.jar

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailSender
{
    final String senderEmailID = "[email protected]";
    final String senderPassword = "typesenderpassword";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "465";
    String receiverEmailID = null;
    static String emailSubject = "Test Mail";
    static String emailBody = ":)";

    public MailSender(
            String receiverEmailID,
            String emailSubject,
            String emailBody
    ) {
        this.receiverEmailID=receiverEmailID;
        this.emailSubject=emailSubject;
        this.emailBody=emailBody;
        Properties props = new Properties();
        props.put("mail.smtp.user",senderEmailID);
        props.put("mail.smtp.host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        SecurityManager security = System.getSecurityManager();
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmailID));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmailID));
            Transport.send(msg);
            System.out.println("Message send Successfully:)");
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
        }
    }

    public class SMTPAuthenticator extends javax.mail.Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(senderEmailID, senderPassword);
        }
    }

    public static void main(String[] args)
    {
        MailSender mailSender=new
            MailSender("[email protected]",emailSubject,emailBody);
    }
}

Creating a mock HttpServletRequest out of a url string?

for those looking for a way to mock POST HttpServletRequest with Json payload, the below is in Kotlin, but the key take away here is the DelegatingServetInputStream when you want to mock the request.getInputStream from the HttpServletRequest

@Mock
private lateinit var request: HttpServletRequest

@Mock
private lateinit var response: HttpServletResponse

@Mock
private lateinit var chain: FilterChain

@InjectMocks
private lateinit var filter: ValidationFilter


@Test
fun `continue filter chain with valid json payload`() {
    val payload = """{
      "firstName":"aB",
      "middleName":"asdadsa",
      "lastName":"asdsada",
      "dob":null,
      "gender":"male"
    }""".trimMargin()

    whenever(request.requestURL).
        thenReturn(StringBuffer("/profile/personal-details"))
    whenever(request.method).
        thenReturn("PUT")
    whenever(request.inputStream).
        thenReturn(DelegatingServletInputStream(ByteArrayInputStream(payload.toByteArray())))

    filter.doFilter(request, response, chain)

    verify(chain).doFilter(request, response)
}

MySQL - Using COUNT(*) in the WHERE clause

try

SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC

how to install python distutils

By searching all python-distutils related package:

apt-cache search x

I get python3-distutils-extra - enhancements to the Python3 build system

Then just try:

sudo apt-get install python3-distutils-extra

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

This happens because of your application does not allow to append iframe from origin other than your application domain.

If your application have web.config then add the following tag in web.config

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="X-Frame-Options" value="ALLOW" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

This will allow application to append iframe from other origin also. You can also use the following value for X-Frame-Option

X-FRAME-OPTIONS: ALLOW-FROM https://example.com/ 

"Strict Standards: Only variables should be passed by reference" error

Instead of parsing it manually it's better to use pathinfo function:

$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];

How to programmatically close a JFrame

Best way to close a Swing frame programmatically is to make it behave like it would when the "X" button is pressed. To do that you will need to implement WindowAdapter that suits your needs and set frame's default close operation to do nothing (DO_NOTHING_ON_CLOSE).

Initialize your frame like this:

private WindowAdapter windowAdapter = null;

private void initFrame() {

    this.windowAdapter = new WindowAdapter() {
        // WINDOW_CLOSING event handler
        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            // You can still stop closing if you want to
            int res = JOptionPane.showConfirmDialog(ClosableFrame.this, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION);
            if ( res == 0 ) {
                // dispose method issues the WINDOW_CLOSED event
                ClosableFrame.this.dispose();
            }
        }

        // WINDOW_CLOSED event handler
        @Override
        public void windowClosed(WindowEvent e) {
            super.windowClosed(e);
            // Close application if you want to with System.exit(0)
            // but don't forget to dispose of all resources 
            // like child frames, threads, ...
            // System.exit(0);
        }
    };

    // when you press "X" the WINDOW_CLOSING event is called but that is it
    // nothing else happens
    this.setDefaultCloseOperation(ClosableFrame.DO_NOTHING_ON_CLOSE);
    // don't forget this
    this.addWindowListener(this.windowAdapter);
}

You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this:

WindowEvent closingEvent = new WindowEvent(targetFrame, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);

This will close the frame like the "X" button was pressed.

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

Deleting Row in SQLite in Android

Till i understand your question,you want to put two conditions to select a row to be deleted.for that,you need to do:

public void deleteEntry(long row,String key_name) {

      db.delete(DATABASE_TABLE, KEY_ROWID + "=" + row + " and " + KEY_NAME + "=" + key_name, null);

      /*if you just have key_name to select a row,you can ignore passing rowid(here-row) and use:

      db.delete(DATABASE_TABLE, KEY_NAME + "=" + key_name, null);
      */  

}

Two column div layout with fluid left and fixed right column

CSS Solutuion

#left{
    float:right;
    width:200px;
    height:500px;
    background:red;   
}

#right{
    margin-right: 200px;
    height:500px;
    background:blue;
}

Check working example at http://jsfiddle.net/NP4vb/3/

jQuery Solution

var parentw = $('#parent').width();
var rightw = $('#right').width();
$('#left').width(parentw - rightw);

Check working example http://jsfiddle.net/NP4vb/

How to generate random number in Bash?

Reading from /dev/random or /dev/urandom character special files is the way to go.

These devices return truly random numbers when read and are designed to help application software choose secure keys for encryption. Such random numbers are extracted from an entropy pool that is contributed by various random events. {LDD3, Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman]

These two files are interface to kernel randomization, in particular

void get_random_bytes_arch(void* buf, int nbytes)

which draws truly random bytes from hardware if such function is by hardware implemented (usually is), or it draws from entropy pool (comprised of timings between events like mouse and keyboard interrupts and other interrupts that are registered with SA_SAMPLE_RANDOM).

dd if=/dev/urandom count=4 bs=1 | od -t d

This works, but writes unneeded output from dd to stdout. The command below gives just the integer I need. I can even get specified number of random bits as I need by adjustment of the bitmask given to arithmetic expansion:

me@mymachine:~/$ x=$(head -c 1 /dev/urandom > tmp && hexdump 
                         -d tmp | head -n 1 | cut -c13-15) && echo $(( 10#$x & 127 ))

How to use PHP with Visual Studio

I don't understand how other answers don't answer the original question about how to use PHP (not very consistent with the title).
PHP files or PHP code embedded in HTML code start always with the tag <?php and ends with ?>.

You can embed PHP code inside HTML like this (you have to save the file using .php extension to let PHP server recognize and process it, ie: index.php):

<body>
   <?php echo "<div>Hello World!</div>" ?>
</body>

or you can use a whole php file, ie: test.php:

<?php    
$mycontent = "Hello World!";
echo "<div>$mycontent</div>";
?> // is not mandatory to put this at the end of the file

there's no document.ready in PHP, the scripts are processed when they are invoked from the browser or from another PHP file.

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

catch forEach last iteration

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})

How to export a MySQL database to JSON?

THis is somthing that should be done in the application layer.

For example, in php it is a s simple as

Edit Added the db connection stuff. No external anything needed.

$sql = "select ...";
$db = new PDO ( "mysql:$dbname", $user, $password) ;
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

file_put_contents("output.txt", json_encode($result));

Selecting multiple columns with linq query and lambda expression

You can use:

public YourClass[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts.Where(x => x.Status == 1)
                           .OrderBy(x => x.ID)
                           .Select(x => new YourClass { ID = x.ID, Name = x.Name, Price = x.Price})
                           .ToArray();
        }
    }
    catch
    {
        return null;
    }
}

And here is YourClass implementation:

public class YourClass
{
  public string Name {get; set;}
  public int ID {get; set;}
  public int Price {get; set;}
}

And your AllProducts method's return type must be YourClass[].

How do I run Python script using arguments in windows command line

import sys

def hello(a, b):
    print  'hello and that\'s your sum: {0}'.format(a + b)

if __name__ == '__main__':
    hello(int(sys.argv[1]), int(sys.argv[2]))

Moreover see @thibauts answer about how to call python script.

Make a DIV fill an entire table cell

you can do it like that:

<td>
  <div style="width: 100%; position: relative; float: left;">inner div</div>
</td>

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);

How can I get just the first row in a result set AFTER ordering?

An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

Redirect non-www to www in .htaccess

The following example works on both ssl and non-ssl and is much faster as you use just one rule to manage http and https

RewriteEngine on


RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs()
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

[Tested]

This will redirect

http

to

https

to

How to get a complete list of ticker symbols from Yahoo Finance?

I have been researching this for a few days, following endless leads that got close, but not quite, to what I was after.

My need is for a simple list of 'symbol, sector, industry'. I'm working in Java and don't want to use any platform native code.

It seems that most other data, like quotes, etc., is readily available.

Finally, followed a suggestion to look at 'finviz.com'. Looks like just the ticket. Try using the following:

http://finviz.com/export.ashx?v=111&t=aapl,cat&o=ticker This comes back as lines, csv style, with a header row, ordered by ticker symbol. You can keep adding tickers. In code, you can read the stream. Or you can let the browser ask you whether to open or save the file.

http://finviz.com/export.ashx?v=111&&o=ticker Same csv style, but pulls all available symbols (a lot, across global exchanges)

Replace 'export' with 'screener' and the data will show up in the browser.

There are many more options you can use, one for every screener element on the site.

So far, this is the most powerful and convenient programmatic way to get the few pieces of data I couldn't otherwise seem to easily get. And, it looks like this site could well be a single source for most of what you might need other than real- or near-real-time quotes.

CodeIgniter Select Query

use Result Rows.
row() method returns a single result row.

$id = $this 
    -> db
    -> select('id')
    -> where('email', $email)
    -> limit(1)
    -> get('users')
    -> row();

then, you can simply use as you want. :)

echo "ID is" . $id;

Which browsers support <script async="async" />?

Just had a look at the DOM (document.scripts[1].attributes) of this page that uses google analytics. I can tell you that google is using async="".

[type="text/javascript", async="", src="http://www.google-analytics.com/ga.js"]

Mongoose, update values in array of objects

There is a mongoose way for doing it.

const itemId = 2;
const query = {
  item._id: itemId 
};
Person.findOne(query).then(doc => {
  item = doc.items.id(itemId );
  item["name"] = "new name";
  item["value"] = "new value";
  doc.save();

  //sent respnse to client
}).catch(err => {
  console.log('Oh! Dark')
});

Batch file. Delete all files and folders in a directory

You can do this using del and the /S flag (to tell it to recurse all files from all subdirectories):

del /S C:\Path\to\directory\*

The RD command can also be used. Recursively delete quietly without a prompt:

@RD /S /Q %VAR_PATH%

Rmdir (rd)

Table with 100% width with equal size columns

ALL YOU HAVE TO DO:

HTML:

<table id="my-table"><tr>
<td> CELL 1 With a lot of text in it</td>
<td> CELL 2 </td>
<td> CELL 3 </td>
<td> CELL 4 With a lot of text in it </td>
<td> CELL 5 </td>
</tr></table>

CSS:

#my-table{width:100%;} /*or whatever width you want*/
#my-table td{width:2000px;} /*something big*/

if you have th you need to set it too like this:

#my-table th{width:2000px;}

iOS Launching Settings -> Restrictions URL Scheme

iOS 10

Use app-prefs:

App-prefs:root=MOBILE_DATA_SETTINGS_ID

See gist

Is there a bash command which counts files?

You can do this safely (i.e. won't be bugged by files with spaces or \n in their name) with bash:

$ shopt -s nullglob
$ logfiles=(*.log)
$ echo ${#logfiles[@]}

You need to enable nullglob so that you don't get the literal *.log in the $logfiles array if no files match. (See How to "undo" a 'set -x'? for examples of how to safely reset it.)

How to resize a custom view programmatically?

If you have only two or three condition(sizes) then you can use @Overide onMeasure like

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
{
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

And change your size for these conditions in CustomView class easily.

Create a variable name with "paste" in R?

See ?assign.

> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
  [1] 5

"Please try running this command again as Root/Administrator" error when trying to install LESS

I know this is an old questions but none of the solutions seemed like a good practice hence I am putting how I have solved this issue:

Tried solving this issue by using Homebrew but it was also installing node in /usr/local directory which would again cause EACCES error.

Had to use a version manager like nvm for more informations see the official npm guide.

For various operating system.

nvm installs node and it's modules in the user's HOME FOLDER thereby solving EACCES issues.

How to load local html file into UIWebView

A Simple Copy-Paste code snippet:

-(void)LoadLocalHtmlFile:(NSString *)fileName onWebVu:(UIWebView*)webVu
{
    [webVu loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:fileName ofType:@"html"]isDirectory:NO]]];
}

Note:

Make sure the html file's Target membership is checked otherwise following exception will get thrown :-

enter image description here

Terminating app due to uncaught exception

'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'

Random strings in Python

try importing the below package from random import*

Why do Twitter Bootstrap tables always have 100% width?

Bootstrap 3:

Why fight it? Why not simply control your table width using the bootstrap grid?

<div class="row">
    <div class="col-sm-6">
        <table></table>
    </div>
</div>

This will create a table that is half (6 out of 12) of the width of the containing element.

I sometimes use inline styles as per the other answers, but it is discouraged.

Bootstrap 4:

Bootstrap 4 has some nice helper classes for width like w-25, w-50, w-75, w-100, and w-auto. This will make the table 50% width:

<table class="w-50"></table>

Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/

How to close jQuery Dialog within the dialog?

you can close it programmatically by calling

$('#form-dialog').dialog('close')

whenever you want.

Get selected option from select element

Here's a short version:

$('#ddlCodes').change(function() {
  $('#txtEntry2').text($(this).find(":selected").text());
});

karim79 made a good catch, judging by your element name txtEntry2 may be a textbox, if it's any kind of input, you'll need to use .val() instead or .text() like this:

  $('#txtEntry2').val($(this).find(":selected").text());

For the "what's wrong?" part of the question: .text() doesn't take a selector, it takes text you want it set to, or nothing to return the text already there. So you need to fetch the text you want, then put it in the .text(string) method on the object you want to set, like I have above.

Uploading a file in Rails

There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave gem .

I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.

Spring: @Component versus @Bean

1. About @Component
@Component functs similarily to @Configuration.

They both indicate that the annotated class has one or more beans need to be registered to Spring-IOC-Container.

The class annotated by @Component, we call it Component of Spring. It is a concept that contains several beans.

Component class needs to be auto-scanned by Spring for registering those beans of the component class.

2. About @Bean
@Bean is used to annotate the method of component-class(as mentioned above). It indicate the instance retured by the annotated method needs to be registered to Spring-IOC-Container.

3. Conclusion
The difference between them two is relatively obivious, they are used in different circumstances. The general usage is:

    // @Configuration is implemented by @Component
    @Configuration
    public ComponentClass {

      @Bean
      public FirstBean FirstBeanMethod() {
        return new FirstBean();
      }

      @Bean
      public SecondBean SecondBeanMethod() {
        return new SecondBean();
      }
    }

VARCHAR to DECIMAL

Implemented using Custom Function. This will check whether the string value can be converted to Decimal safely

CREATE FUNCTION [dbo].[TryParseAsDecimal]
(
    @Value      NVARCHAR(4000)
    ,@Precision INT
    ,@Scale     INT
)

RETURNS BIT
AS
BEGIN

    IF(ISNUMERIC(@Value) =0) BEGIN
        RETURN CAST(0 AS BIT)
    END
    SELECT @Value = REPLACE(@Value,',','') --Removes the comma

    --This function validates only the first part eg '1234567.8901111111'
    --It validates only the values before the '.' ie '1234567.'
    DECLARE @Index          INT
    DECLARE @Part1Length    INT 
    DECLARE @Part1          VARCHAR(4000)   

    SELECT @Index = CHARINDEX('.', @Value, 0)
    IF (@Index>0) BEGIN
        --If decimal places, extract the left part only and cast it to avoid leading zeros (eg.'0000000001' => '1')
        SELECT @Part1 =LEFT(@Value, @Index-1);
        SELECT @Part1=SUBSTRING(@Part1, PATINDEX('%[^0]%', @Part1+'.'), LEN(@Part1));
        SELECT @Part1Length = LEN(@Part1);
    END
    ELSE BEGIN
        SELECT @Part1 =CAST(@Value AS DECIMAL);
        SELECT @Part1Length= LEN(@Part1)
    END 

    IF (@Part1Length > (@Precision-@Scale)) BEGIN
        RETURN CAST(0 AS BIT)
    END

    RETURN CAST(1 AS BIT)

END

Regex for string contains?

I'm a few years late, but why not this?

[Tt][Ee][Ss][Tt]