Programs & Examples On #Markaby

A library for writing HTML code in pure Ruby. It is an alternative to templating languages such as ERb and HAML.

sql set variable using COUNT

You can use SELECT as lambacck said or add parentheses:

SET @times = (SELECT COUNT(DidWin)as "I Win"
FROM thetable
WHERE DidWin = 1 AND Playername='Me');

How do I implement onchange of <input type="text"> with jQuery?

There is one and only one reliable way to do this, and it is by pulling the value in an interval and comparing it to a cached value.

The reason why this is the only way is because there are multiple ways to change an input field using various inputs (keyboard, mouse, paste, browser history, voiceinput etc.) and you can never detect all of them using standard events in a cross-browser environment.

Luckily, thanks to the event infrastructure in jQuery, it’s quite easy to add your own inputchange event. I did so here:

$.event.special.inputchange = {
    setup: function() {
        var self = this, val;
        $.data(this, 'timer', window.setInterval(function() {
            val = self.value;
            if ( $.data( self, 'cache') != val ) {
                $.data( self, 'cache', val );
                $( self ).trigger( 'inputchange' );
            }
        }, 20));
    },
    teardown: function() {
        window.clearInterval( $.data(this, 'timer') );
    },
    add: function() {
        $.data(this, 'cache', this.value);
    }
};

Use it like: $('input').on('inputchange', function() { console.log(this.value) });

There is a demo here: http://jsfiddle.net/LGAWY/

If you’re scared of multiple intervals, you can bind/unbind this event on focus/blur.

MySQL Like multiple values

More work examples:

SELECT COUNT(email) as count FROM table1 t1 
JOIN (
      SELECT company_domains as emailext FROM table2 WHERE company = 'DELL'
     ) t2 
ON t1.email LIKE CONCAT('%', emailext) WHERE t1.event='PC Global Conference";

Task was count participants at an event(s) with filter if email extension equal to multiple company domains.

How do I auto size columns through the Excel interop objects?

This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.

 public static void AutoFitExcelSheets()
    {
        Microsoft.Office.Interop.Excel.Application _excel = null;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        try
        {
            string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
            _excel = new Microsoft.Office.Interop.Excel.Application();
            _excel.Visible = false;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            excelWorkbook = _excel.Workbooks.Open(ExcelPath,
                   0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                   true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
            {
                string Name = currentSheet.Name;
                Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
                Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
                excelCells.Columns.AutoFit();
            }
        }
        catch (Exception ex)
        {
            ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
        }
        finally
        {
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(excelWorkbook);
            releaseObject(_excel);
        }
    }

Python - IOError: [Errno 13] Permission denied:

It looks like you're trying to replace the extension with the following code:

if (myFile[-4:] == ".asm"):
    newFile = myFile[:4]+".hack"

However, you appear to have the array indexes mixed up. Try the following:

if (myFile[-4:] == ".asm"):
    newFile = myFile[:-4]+".hack"

Note the use of -4 instead of just 4 in the second line of code. This explains why your program is trying to create /Use.hack, which is the first four characters of your file name (/Use), with .hack appended to it.

jquery beforeunload when closing (not leaving) the page?

Try javascript into your Ajax

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Reference link

Example 2:

document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
    window.btn_clicked = true;
};
window.onbeforeunload = function(){
    if(!window.btn_clicked){
        return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
    }
};

Here it will alert the user every time he leaves the page, until he clicks on the button.

DEMO: http://jsfiddle.net/DerekL/GSWbB/show/

How to delete a file or folder?

My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.

In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...

It also wraps shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

Should C# or C++ be chosen for learning Games Programming (consoles)?

It depends

It depends on a lot of things - your goals, your experience, your timeframe, etc.

The majority of game programming isn't language specific. 3D math is 3D math in C# as much as it is in C++. While the APIs may be different, and different 'bookkeeping' may be required, the fundamental logic and math will remain the same.

And it's true that most AAA game engines are C++ with a scripting language on top of them. That is undeniable. However, most AAA engines also have a bunch of in-house tools supporting them, and those may be in anything - Java, C#, C++, etc.

If you want to write a game, and are an experienced developer then C++ and C# have a lot going for them. C# has less housekeeping, while C++ has more available libraries and tools. For anything highly complex, however, you'd be best off trying to use an existing engine as a starting point.

If you want to write a game, and are a new developer then don't write an engine. Use an existing engine, and mod it or use its facilities to write your game. Trust me.

If you want to learn how to write an engine, and are an experienced developer you should probably think about C++. C# is possible as well, but the amount of code and ease of integration of C++ probably puts it over the top.

If you want to learn how to write an engine, and are a new developer I'd probably recommend C#/XNA. You'll get to the game 'stuff' faster, with less headache of learning the ins and outs of C++.

If you want a job in the industry then you need to figure out what kind of job you want. A high-level language can help get a foot in the door dealing with tools and/or web development, which can lead to opportunities on actual game work. Even knowledge of scripting languages can help if you want to go for more of the game designer/scripter position. Chances are that you will not get a job working on core engine stuff immediately, as the skills required to do so are pretty high. Strong C++ development skills are always helpful, especially in real-time or networked scenarios.

AAA game engine development involves some serious brain-twisting code.

If you want to start a professional development house then you probably aren't reading this, but already know that C++ is probably the only viable answer.

If you want to do casual game development then you should probably consider Flash or a similar technology.

How to split the screen with two equal LinearLayouts?

To Split a layout to equal parts

Use Layout Weights. Keep in mind that it is important to set layout_width as 0dp on children to make it work as intended.

on parent layout:

  1. Set weightSum of parent Layout as 1 (android:weightSum="1")

on the child layout:

  1. Set layout_width as 0dp (android:layout_width="0dp")
  2. Set layout_weight as 0.5 [half of weight sum fr equal two] (android:layout_weight="0.5")


To split layout to three equal parts:

  • parent: weightSum 3
  • child: layout_weight: 1

To split layout to four equal parts:

  • parent: weightSum 1
  • child: layout_weight: 0.25

To split layout to n equal parts:

  • parent: weightSum n
  • child: layout_weight: 1


Below is an example layout for splitting layout to two equal parts.

<LinearLayout
    android:id="@+id/layout_top"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="1">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:orientation="vertical">

        <TextView .. />

        <EditText .../>

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:orientation="vertical">

        <TextView ../>

        <EditText ../>

    </LinearLayout>

</LinearLayout>

Change column type in pandas

Starting pandas 1.0.0, we have pandas.DataFrame.convert_dtypes. You can even control what types to convert!

In [40]: df = pd.DataFrame(
    ...:     {
    ...:         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
    ...:         "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
    ...:         "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
    ...:         "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
    ...:         "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
    ...:         "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    ...:     }
    ...: )

In [41]: dff = df.copy()

In [42]: df 
Out[42]: 
   a  b      c    d     e      f
0  1  x   True    h  10.0    NaN
1  2  y  False    i   NaN  100.5
2  3  z    NaN  NaN  20.0  200.0

In [43]: df.dtypes
Out[43]: 
a      int32
b     object
c     object
d     object
e    float64
f    float64
dtype: object

In [44]: df = df.convert_dtypes()

In [45]: df.dtypes
Out[45]: 
a      Int32
b     string
c    boolean
d     string
e      Int64
f    float64
dtype: object

In [46]: dff = dff.convert_dtypes(convert_boolean = False)

In [47]: dff.dtypes
Out[47]: 
a      Int32
b     string
c     object
d     string
e      Int64
f    float64
dtype: object

Why is this HTTP request not working on AWS Lambda?

Yeah, awendt answer is perfect. I'll just show my working code... I had the context.succeed('Blah'); line right after the reqPost.end(); line. Moving it to where I show below solved everything.

console.log('GW1');

var https = require('https');

exports.handler = function(event, context) {

    var body='';
    var jsonObject = JSON.stringify(event);

    // the post options
    var optionspost = {
        host: 'the_host',
        path: '/the_path',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    };

    var reqPost = https.request(optionspost, function(res) {
        console.log("statusCode: ", res.statusCode);
        res.on('data', function (chunk) {
            body += chunk;
        });
        context.succeed('Blah');
    });

    reqPost.write(jsonObject);
    reqPost.end();
};

Working with select using AngularJS's ng-options

I'm learning AngularJS and was struggling with selection as well. I know this question is already answered, but I wanted to share some more code nevertheless.

In my test I have two listboxes: car makes and car models. The models list is disabled until some make is selected. If selection in makes listbox is later reset (set to 'Select Make') then the models listbox becomes disabled again AND its selection is reset as well (to 'Select Model'). Makes are retrieved as a resource while models are just hard-coded.

Makes JSON:

[
{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}
]

services.js:

angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
    return $resource('makes.json', {}, {
        query: {method:'GET', isArray:true}
    });
});

HTML file:

<div ng:controller="MakeModelCtrl">
  <div>Make</div>
  <select id="makeListBox"
      ng-model="make.selected"
      ng-options="make.code as make.name for make in makes"
      ng-change="makeChanged(make.selected)">
  </select>

  <div>Model</div>
  <select id="modelListBox"
     ng-disabled="makeNotSelected"
     ng-model="model.selected"
     ng-options="model.code as model.name for model in models">
  </select>
</div>

controllers.js:

function MakeModelCtrl($scope)
{
    $scope.makeNotSelected = true;
    $scope.make = {selected: "0"};
    $scope.makes = Make.query({}, function (makes) {
         $scope.make = {selected: makes[0].code};
    });

    $scope.makeChanged = function(selectedMakeCode) {
        $scope.makeNotSelected = !selectedMakeCode;
        if ($scope.makeNotSelected)
        {
            $scope.model = {selected: "0"};
        }
    };

    $scope.models = [
      {code:"0", name:"Select Model"},
      {code:"1", name:"Model1"},
      {code:"2", name:"Model2"}
    ];
    $scope.model = {selected: "0"};
}

Paging UICollectionView by cells, not screen

modify Romulo BM answer for velocity listening

func scrollViewWillEndDragging(
    _ scrollView: UIScrollView,
    withVelocity velocity: CGPoint,
    targetContentOffset: UnsafeMutablePointer<CGPoint>
) {
    targetContentOffset.pointee = scrollView.contentOffset
    var indexes = collection.indexPathsForVisibleItems
    indexes.sort()
    var index = indexes.first!
    if velocity.x > 0 {
       index.row += 1
    } else if velocity.x == 0 {
        let cell = self.collection.cellForItem(at: index)!
        let position = self.collection.contentOffset.x - cell.frame.origin.x
        if position > cell.frame.size.width / 2 {
           index.row += 1
        }
    }

    self.collection.scrollToItem(at: index, at: .centeredHorizontally, animated: true )
}

How to completely uninstall Android Studio from windows(v10)?

.android  

check this folder in

C:\Users\user

its have an issue and fix it then restart android studio.

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

How to check for an active Internet connection on iOS or macOS?

There's a nice-looking, ARC- and GCD-using modernization of Reachability here:

Reachability

Add Variables to Tuple

As other answers have noted, you cannot change an existing tuple, but you can always create a new tuple (which may take some or all items from existing tuples and/or other sources).

For example, if all the items of interest are in scalar variables and you know the names of those variables:

def maketuple(variables, names):
  return tuple(variables[n] for n in names)

to be used, e.g, as in this example:

def example():
  x = 23
  y = 45
  z = 67
  return maketuple(vars(), 'x y z'.split())

of course this one case would be more simply expressed as (x, y, z) (or even foregoing the names altogether, (23, 45, 67)), but the maketuple approach might be useful in some more complicated cases (e.g. where the names to use are also determined dynamically and appended to a list during the computation).

Relative Paths in Javascript in an external file

JavaScript file paths

When in script, paths are relative to displayed page

to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:

Solution, which was employed on StackOverflow around Feb 2010:

<script type="text/javascript">
   var imagePath = 'http://sstatic.net/so/img/';
</script>

If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section

Triangle Draw Method

There is no direct method to draw a triangle. You can use drawPolygon() method for this. It takes three parameters in the following form: drawPolygon(int x[],int y[], int number_of_points); To draw a triangle: (Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.) Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100) Do the following inside public void paint(Graphics g):

int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);

Similarly you can draw any shape using as many points as you want.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Check out the example from enable-cors.org:

In your ExpressJS app on node.js, do the following with your routes:

app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
 });

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

The first call (app.all) should be made before all the other routes in your app (or at least the ones you want to be CORS enabled).

[Edit]

If you want the headers to show up for static files as well, try this (make sure it's before the call to use(express.static()):

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

I tested this with your code, and got the headers on assets from the public directory:

var express = require('express')
  , app = express.createServer();

app.configure(function () {
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      next();
    });
    app.use(app.router);
});

app.configure('development', function () {
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler());
});

app.listen(8888);
console.log('express running at http://localhost:%d', 8888);

You could, of course, package the function up into a module so you can do something like

// cors.js

module.exports = function() {
  return function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
  };
}

// server.js

cors = require('./cors');
app.use(cors());

How to execute a JavaScript function when I have its name as a string

Thanks for the very helpful answer. I'm using Jason Bunting's function in my projects.

I extended it to use it with an optional timeout, because the normal way to set a timeout wont work. See abhishekisnot's question

_x000D_
_x000D_
function executeFunctionByName(functionName, context, timeout /*, args */ ) {_x000D_
 var args = Array.prototype.slice.call(arguments, 3);_x000D_
 var namespaces = functionName.split(".");_x000D_
 var func = namespaces.pop();_x000D_
 for (var i = 0; i < namespaces.length; i++) {_x000D_
  context = context[namespaces[i]];_x000D_
 }_x000D_
 var timeoutID = setTimeout(_x000D_
  function(){ context[func].apply(context, args)},_x000D_
  timeout_x000D_
 );_x000D_
    return timeoutID;_x000D_
}_x000D_
_x000D_
var _very = {_x000D_
    _deeply: {_x000D_
        _defined: {_x000D_
            _function: function(num1, num2) {_x000D_
                console.log("Execution _very _deeply _defined _function : ", num1, num2);_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
console.log('now wait')_x000D_
executeFunctionByName("_very._deeply._defined._function", window, 2000, 40, 50 );
_x000D_
_x000D_
_x000D_

What is the difference between Normalize.css and Reset CSS?

Normalize.css :Every browser is coming with some default css styles that will, for example, add padding around a paragraph or title.If you add the normalize style sheet all those browser default rules will be reset so for this instance 0px padding on tags.Here is a couple of links for more details: https://necolas.github.io/normalize.css/ http://nicolasgallagher.com/about-normalize-css/

Border in shape xml

If you want make a border in a shape xml. You need to use:

For the external border,you need to use:

<stroke/>

For the internal background,you need to use:

<solid/>

If you want to set corners,you need to use:

<corners/>

If you want a padding betwen border and the internal elements,you need to use:

<padding/>

Here is a shape xml example using the above items. It works for me

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="2dp" android:color="#D0CFCC" /> 
  <solid android:color="#F8F7F5" /> 
  <corners android:radius="10dp" />
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>

How is Docker different from a virtual machine?

I have used Docker in production environments and staging very much. When you get used to it you will find it very powerful for building a multi container and isolated environments.

Docker has been developed based on LXC (Linux Container) and works perfectly in many Linux distributions, especially Ubuntu.

Docker containers are isolated environments. You can see it when you issue the top command in a Docker container that has been created from a Docker image.

Besides that, they are very light-weight and flexible thanks to the dockerFile configuration.

For example, you can create a Docker image and configure a DockerFile and tell that for example when it is running then wget 'this', apt-get 'that', run 'some shell script', setting environment variables and so on.

In micro-services projects and architecture Docker is a very viable asset. You can achieve scalability, resiliency and elasticity with Docker, Docker swarm, Kubernetes and Docker Compose.

Another important issue regarding Docker is Docker Hub and its community. For example, I implemented an ecosystem for monitoring kafka using Prometheus, Grafana, Prometheus-JMX-Exporter, and Docker.

For doing that, I downloaded configured Docker containers for zookeeper, kafka, Prometheus, Grafana and jmx-collector then mounted my own configuration for some of them using YAML files, or for others, I changed some files and configuration in the Docker container and I build a whole system for monitoring kafka using multi-container Dockers on a single machine with isolation and scalability and resiliency that this architecture can be easily moved into multiple servers.

Besides the Docker Hub site there is another site called quay.io that you can use to have your own Docker images dashboard there and pull/push to/from it. You can even import Docker images from Docker Hub to quay then running them from quay on your own machine.

Note: Learning Docker in the first place seems complex and hard, but when you get used to it then you can not work without it.

I remember the first days of working with Docker when I issued the wrong commands or removing my containers and all of data and configurations mistakenly.

PHP output showing little black diamonds with a question mark

I ran the "detect encoding" code after my collation change in phpmyadmin and now it comes up as Latin_1.

but here is something I came across looking a different data anomaly in my application and how I fixed it:

I just imported a table that has mixed encoding (with diamond question marks in some lines, and all were in the same column.) so here is my fix code. I used utf8_decode process that takes the undefined placeholder and assigns a plain question mark in the place of the "diamond question mark " then I used str_replace to replace the question mark with a space between quotes. here is the [code]

    include 'dbconnectfile.php';

  //// the variable $db comes from my db connect file
   /// inx is my auto increment column
   /// broke_column is the column I need to fix

      $qwy = "select inx,broke_column from Table ";
      $res = $db->query($qwy); 

      while ($data = $res->fetch_row()) {
      for ($m=0; $m<$res->field_count; $m++) {
           if ($m==0){ 
           $id=0;
           $id=$data[$m];
       echo $id;
           }else if ($m==1){ 
             $fix=0;
             $fix=$data[$m];


             $fix = utf8_decode($fix);
             $fixx =str_replace("?"," ",$fix);

        echo $fixx;

        ////I echoed the data to the screen because I like to see something as I execute it :)
            }
            }
         $insert= "UPDATE Table SET broke_column='".$fixx."'  where inx='".$id."'";
          $insresult= $db->query($insert);
      echo"<br>";
        }

        ?>        

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Can I extend a class using more than 1 class in PHP?

Classes are not meant to be just collections of methods. A class is supposed to represent an abstract concept, with both state (fields) and behaviour (methods) which changes the state. Using inheritance just to get some desired behaviour sounds like bad OO design, and exactly the reason why many languages disallow multiple inheritance: in order to prevent "spaghetti inheritance", i.e. extending 3 classes because each has a method you need, and ending up with a class that inherits 100 method and 20 fields, yet only ever uses 5 of them.

Convert Swift string to array

It is even easier in Swift:

let string : String = "Hello  "
let characters = Array(string)
println(characters)
// [H, e, l, l, o,  , , ,  , ]

This uses the facts that

  • an Array can be created from a SequenceType, and
  • String conforms to the SequenceType protocol, and its sequence generator enumerates the characters.

And since Swift strings have full support for Unicode, this works even with characters outside of the "Basic Multilingual Plane" (such as ) and with extended grapheme clusters (such as , which is actually composed of two Unicode scalars).


Update: As of Swift 2, String does no longer conform to SequenceType, but the characters property provides a sequence of the Unicode characters:

let string = "Hello  "
let characters = Array(string.characters)
print(characters)

This works in Swift 3 as well.


Update: As of Swift 4, String is (again) a collection of its Characters:

let string = "Hello  "
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "", "", " ", ""]

jQuery select by attribute using AND and OR operators

In your special case it would be

a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');

React Native Change Default iOS Simulator Device

Get device list with this command

xcrun simctl list devices

Console

== Devices ==
-- iOS 13.5 --
    iPhone 6s (9981E5A5-48A8-4B48-B203-1C6E73243E83) (Shutdown) 
    iPhone 8 (FC540A6C-F374-4113-9E71-1291790C8C4C) (Shutting Down) 
    iPhone 8 Plus (CAC37462-D873-4EBB-9D71-7C6D0C915C12) (Shutdown) 
    iPhone 11 (347EFE28-9B41-4C1A-A4C3-D99B49300D8B) (Shutting Down) 
    iPhone 11 Pro (5AE964DC-201C-48C9-BFB5-4506E3A0018F) (Shutdown) 
    iPhone 11 Pro Max (48EE985A-39A6-426C-88A4-AA1E4AFA0133) (Shutdown) 
    iPhone SE (2nd generation) (48B78183-AFD7-4832-A80E-AF70844222BA) (Shutdown) 
    iPad Pro (9.7-inch) (2DEF27C4-6A18-4477-AC7F-FB31CCCB3960) (Shutdown) 
    iPad (7th generation) (36A4AF6B-1232-4BCB-B74F-226E025225E4) (Shutdown) 
    iPad Pro (11-inch) (2nd generation) (79391BD7-0E55-44C8-B1F9-AF92A1D57274) (Shutdown) 
    iPad Pro (12.9-inch) (4th generation) (ED90A31F-6B20-4A6B-9EE9-CF22C01E8793) (Shutdown) 
    iPad Air (3rd generation) (41AD1CF7-CB0D-4F18-AB1E-6F8B6261AD33) (Shutdown) 
-- tvOS 13.4 --
    Apple TV 4K (51925935-97F4-4242-902F-041F34A66B82) (Shutdown) 
-- watchOS 6.2 --
    Apple Watch Series 5 - 40mm (7C50F2E9-A52B-4E0D-8B81-A811FE995502) (Shutdown) 
    Apple Watch Series 5 - 44mm (F7D8C256-DC9F-4FDC-8E65-63275C222B87) (Shutdown) 

Select Simulator string without ID here is an example.

iPad Pro (12.9-inch) (4th generation)

Final command

iPhone

• iPhone 6s

react-native run-ios --simulator="iPhone 6s"

• iPhone 8

react-native run-ios --simulator="iPhone 8"

• iPhone 8 Plus

react-native run-ios --simulator="iPhone 8 Plus"

• iPhone 11

react-native run-ios --simulator="iPhone 11"

• iPhone 11 Pro

react-native run-ios --simulator="iPhone 11 Pro"

• iPhone 11 Pro Max

react-native run-ios --simulator="iPhone 11 Pro Max"

• iPhone SE (2nd generation)

react-native run-ios --simulator="iPhone SE (2nd generation)"

iPad

• iPad Pro (9.7-inch)

react-native run-ios --simulator="iPad Pro (9.7-inch)"

• iPad (7th generation)

react-native run-ios --simulator="iPad (7th generation)"

• iPad Pro (11-inch) (2nd generation)

react-native run-ios --simulator="iPad Pro (11-inch) (2nd generation)"

• iPad Pro (12.9-inch) 4th generation

react-native run-ios --simulator="iPad Pro (12.9-inch) (4th generation)"

• iPad Air (3rd generation)

react-native run-ios --simulator="iPad Air (3rd generation)"

Read Variable from Web.Config

I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.

However you can read web.config using System.Configuration.ConfigurationManager.AppSettings

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Close all browsers and tabs to ensure that the ActiveX control is not reside in memory. Open a fresh IE9 browser. Select Tools->Manage Add-ons. Change the drop down to "All add-ons" since the default only shows ones that are loaded.

Now select the add-on you wish to remove. There will be a link displayed on the lower left that says "More information". Click it.

This opens a further dialog that allows you to safely un-install the ActiveX control.

If you follow the direction of manually running the 'regsvr32' to remove the OCX it is not sufficient. ActiveX controls are wrapped up as signed CAB files and they extract to multiple DLLs and OCXs potentially. You wish to use IE to safely and correctly unregister every COM DLL and OCX.

There you have it! The problem is that in IE 9 it is somewhat hidden since you have to click the "More information" whereas IE8 you could do it from the same UI.

DateTime.TryParse issue with dates of yyyy-dd-MM format

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

Convert date from String to Date format in Dataframes

The solution proposed above by Sai Kiriti Badam worked for me.

I'm using Azure Databricks to read data captured from an EventHub. This contains a string column named EnqueuedTimeUtc with the following format...

12/7/2018 12:54:13 PM

I'm using a Python notebook and used the following...

import pyspark.sql.functions as func

sports_messages = sports_df.withColumn("EnqueuedTimestamp", func.to_timestamp("EnqueuedTimeUtc", "MM/dd/yyyy hh:mm:ss aaa"))

... to create a new column EnqueuedTimestamp of type "timestamp" with data in the following format...

2018-12-07 12:54:13

Altering a column: null to not null

You will have to do it in two steps:

  1. Update the table so that there are no nulls in the column.
UPDATE MyTable SET MyNullableColumn = 0
WHERE MyNullableColumn IS NULL
  1. Alter the table to change the property of the column
ALTER TABLE MyTable
ALTER COLUMN MyNullableColumn MyNullableColumnDatatype NOT NULL

Write to file, but overwrite it if it exists

If your environment doesn't allow overwriting with >, use pipe | and tee instead as follows:

echo "text" | tee 'Users/Name/Desktop/TheAccount.txt'

Note this will also print to the stdout. In case this is unwanted, you can redirect the output to /dev/null as follows:

echo "text" | tee 'Users/Name/Desktop/TheAccount.txt' > /dev/null

Sort columns of a dataframe by column name

You can use order on the names, and use that to order the columns when subsetting:

test[ , order(names(test))]
  A B C
1 4 1 0
2 2 3 2
3 4 8 4
4 7 3 7
5 8 2 8

For your own defined order, you will need to define your own mapping of the names to the ordering. This would depend on how you would like to do this, but swapping whatever function would to this with order above should give your desired output.

You may for example have a look at Order a data frame's rows according to a target vector that specifies the desired order, i.e. you can match your data frame names against a target vector containing the desired column order.

When to use self over $this?

Additionally since $this:: has not been discussed yet.

For informational purposes only, as of PHP 5.3 when dealing with instantiated objects to get the current scope value, as opposed to using static::, one can alternatively use $this:: like so.

http://ideone.com/7etRHy

class Foo
{
    const NAME = 'Foo';

    //Always Foo::NAME (Foo) due to self
    protected static $staticName = self::NAME;

    public function __construct()
    {
        echo $this::NAME;
    }

    public function getStaticName()
    {
       echo $this::$staticName;
    }
}

class Bar extends Foo
{
    const NAME = 'FooBar';

    /**
     * override getStaticName to output Bar::NAME
     */
    public function getStaticName()
    {
        $this::$staticName = $this::NAME;
        parent::getStaticName();
    }
}

$foo = new Foo; //outputs Foo
$bar = new Bar; //outputs FooBar
$foo->getStaticName(); //outputs Foo
$bar->getStaticName(); //outputs FooBar
$foo->getStaticName(); //outputs FooBar

Using the code above is not common or recommended practice, but is simply to illustrate its usage, and is to act as more of a "Did you know?" in reference to the original poster's question.

It also represents the usage of $object::CONSTANT for example echo $foo::NAME; as opposed to $this::NAME;

How to use null in switch

Some libraries attempt to offer alternatives to the builtin java switch statement. Vavr is one of them, they generalize it to pattern matching.

Here is an example from their documentation:

String s = Match(i).of(
    Case($(1), "one"),
    Case($(2), "two"),
    Case($(), "?")
);

You can use any predicate, but they offer many of them out of the box, and $(null) is perfectly legal. I find this a more elegant solution than the alternatives, but this requires java8 and a dependency on the vavr library...

Lowercase and Uppercase with jQuery

Try this:

var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();

Possible duplicate with: How do I use jQuery to ignore case when selecting

Illegal Escape Character "\"

The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\". Here is an example of a string comparison using the '\' character:

if (invName.substring(j,k).equals("\\")) {...}

You can also perform direct character comparisons using logic similar to the following:

if (invName.charAt(j) == '\\') {...}

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

How can I list ALL grants a user received?

Assuming you want to list grants on all objects a particular user has received:

select * from all_tab_privs_recd where grantee = 'your user'

This will not return objects owned by the user. If you need those, use all_tab_privs view instead.

android : Error converting byte to dex

In My case, I First Clean the project then i press Make Project button as below image, then it start working. Rebuild doesn't work for me.

enter image description here

And I also updating Google Repository is must.

Query an XDocument for elements by name at any depth

Following @Francisco Goldenstein answer, I wrote an extension method

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Mediatel.Framework
{
    public static class XDocumentHelper
    {
        public static IEnumerable<XElement> DescendantElements(this XDocument xDocument, string nodeName)
        {
            return xDocument.Descendants().Where(p => p.Name.LocalName == nodeName);
        }
    }
}

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Accessing a property in a parent Component

I made a generic component where I need a reference to the parent using it. Here's what I came up with:

In my component I made an @Input :

@Input()
parent: any;

Then In the parent using this component:

<app-super-component [parent]="this"> </app-super-component>

In the super component I can use any public thing coming from the parent:

Attributes:

parent.anyAttribute

Functions :

parent[myFunction](anyParameter)

and of course private stuff won't be accessible.

Build Android Studio app via command line

Adding value to all these answers,

many have asked the command for running App in AVD after build sucessful.

adb install -r {path-to-your-bild-folder}/{yourAppName}.apk

How can I call controller/view helper methods from the console in Ruby on Rails?

Inside any controller action or view, you can invoke the console by calling the console method.

For example, in a controller:

class PostsController < ApplicationController
  def new
    console
    @post = Post.new
  end
end

Or in a view:

<% console %>

<h2>New Post</h2>

This will render a console inside your view. You don't need to care about the location of the console call; it won't be rendered on the spot of its invocation but next to your HTML content.

See: http://guides.rubyonrails.org/debugging_rails_applications.html

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Just now I have this situation and I have tried this way which is very easy.

First stop your mysql service using this command:

service mysql stop

and then just again start your mysql service using this command

service mysql start

I hope it may help others... :)

How to select some rows with specific rownames from a dataframe?

Assuming that you have a data frame called students, you can select individual rows or columns using the bracket syntax, like this:

  • students[1,2] would select row 1 and column 2, the result here would be a single cell.
  • students[1,] would select all of row 1, students[,2] would select all of column 2.

If you'd like to select multiple rows or columns, use a list of values, like this:

  • students[c(1,3,4),] would select rows 1, 3 and 4,
  • students[c("stu1", "stu2"),] would select rows named stu1 and stu2.

Hope I could help.

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Difference between require, include, require_once and include_once?

Include / Require you can include the same file more than once also:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

require_once / include_once

is identical to include/require except PHP will check if the file has already been included, and if so, not include (require) it again.

How to remove text from a string?

Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:

var myString = "data-123";
var myNewString = myString.replace("data-", "");

See: .replace() docs on MDN for additional information and usage.

List all liquibase sql types

For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:

https://github.com/liquibase/liquibase/blob/master/liquibase-core/src/main/java/liquibase/datatype/core/BooleanType.java

For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:

https://github.com/liquibase/liquibase/blob/2_0_x/liquibase-core/src/main/java/liquibase/database/typeconversion/core/MySQLTypeConverter.java

Android – Listen For Incoming SMS Messages

Note that on some devices your code wont work without android:priority="1000" in intent filter:

<receiver android:name=".listener.SmsListener">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

And here is some optimizations:

public class SmsListener extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
            for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                String messageBody = smsMessage.getMessageBody();
            }
        }
    }
}

Note:
The value must be an integer, such as "100". Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000.

Here's a link.

Postgresql Select rows where column = array

SELECT  *
FROM    table
WHERE   some_id = ANY(ARRAY[1, 2])

or ANSI-compatible:

SELECT  *
FROM    table
WHERE   some_id IN (1, 2)

The ANY syntax is preferred because the array as a whole can be passed in a bound variable:

SELECT  *
FROM    table
WHERE   some_id = ANY(?::INT[])

You would need to pass a string representation of the array: {1,2}

Counting number of characters in a file through shell script

Credits to user.py et al.


echo "ää" > /tmp/your_file.txt
cat /tmp/your_file.txt | wc -m

results in 3.

In my example the result is expected to be 2 (twice the letter ä). However, echo (or vi) adds a line break \n to the end of the output (or file). So two ä and one Linux line break \n are counted. That's three together.

Working with pipes | is not the shortest variant, but so I have to know less wc parameters by heart. In addition, cat is bullet-proof in my experience.

Tested on Ubuntu 18.04.1 LTS (Bionic Beaver).

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Regular expression for a hexadecimal number?

Not a big deal, but most regex engines support the POSIX character classes, and there's [:xdigit:] for matching hex characters, which is simpler than the common 0-9a-fA-F stuff.

So, the regex as requested (ie. with optional 0x) is: /(0x)?[[:xdigit:]]+/

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I had the following configuration in my httpd.conf that denied executing the wpadmin/setup-config.php file from wordpress. Removing the |-config part solved the problem. I think this httpd.conf is from plesk but it could be some default suggested config from wordpress, i don't know. Anyway, I could safely add it back after the setup finished.

<LocationMatch "(?i:(?:wp-config\\.bak|\\.wp-config\\.php\\.swp|(?:readme|license|changelog|-config|-sample)\\.(?:php|md|txt|htm|html)))">
                        Require all denied
                </LocationMatch>

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

Its because of wrong path provided. It may be that the url contains space and if the case url has to be properly constructed.

The correct url should be in the format with file name included like "http://server name/document library name/new file name"

So if report.xlsx is the file that has to be uploaded at "http://server name/Team/Dev Team" then path comes out to be is "http://server name/Team/Dev Team/report.xlsx". It contains space so it should be reconstructed as "http://server name/Team/Dev%20Team/report.xlsx" and should be used.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

I was so confusing first time, but I propose you final working solution for Windows:

1) Open cmd and go to your Java/jdk/bin directory (just press cd .. to go one folder back and cd NAME_FOLDER to go one folder forward), in my case, final folder: C:\Program Files\Java\jdk1.8.0_73\bin> enter image description here

2) Now type this command keytool -list -v -keystore C:\Users\YOUR_WINDOWS_USER\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

As result you have to get something like this: enter image description here

Testing the type of a DOM element in JavaScript

Although the previous answers work perfectly, I will just add another way where the elements can also be classified using the interface they have implemented.

Refer W3 Org for available interfaces

_x000D_
_x000D_
console.log(document.querySelector("#anchorelem") instanceof HTMLAnchorElement);_x000D_
console.log(document.querySelector("#divelem") instanceof HTMLDivElement);_x000D_
console.log(document.querySelector("#buttonelem") instanceof HTMLButtonElement);_x000D_
console.log(document.querySelector("#inputelem") instanceof HTMLInputElement);
_x000D_
<a id="anchorelem" href="">Anchor element</a>_x000D_
<div id="divelem">Div Element</div>_x000D_
<button id="buttonelem">Button Element</button>_x000D_
<br><input id="inputelem">
_x000D_
_x000D_
_x000D_

The interface check can be made in 2 ways as elem instanceof HTMLAnchorElement or elem.constructor.name == "HTMLAnchorElement", both returns true

How to check for registry value using VbScript

Try something like this:

Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")

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

In VB.NET while trying to connect to Rackspace's SSL port on 465 I encountered the same issue (requires implicit SSL). I made use of https://www.nuget.org/packages/MailKit/ in order to successfully connect.

The following is an example of an HTML email message.

Imports MailKit.Net.Smtp
Imports MailKit
Imports MimeKit

Sub somesub()
    Dim builder As New BodyBuilder()
    Dim mail As MimeMessage
    mail = New MimeMessage()
    mail.From.Add(New MailboxAddress("", c_MailUser))
    mail.To.Add(New MailboxAddress("", c_ToUser))
    mail.Subject = "Mail Subject"
    builder.HtmlBody = "<html><body>Body Text"
    builder.HtmlBody += "</body></html>"
      mail.Body = builder.ToMessageBody()

      Using client As New SmtpClient
        client.Connect(c_MailServer, 465, True)
        client.AuthenticationMechanisms.Remove("XOAUTH2") ' Do not use OAUTH2
        client.Authenticate(c_MailUser, c_MailPassword) ' Use a username / password to authenticate.
        client.Send(mail)
        client.Disconnect(True)
    End Using 

End Sub

GoTo Next Iteration in For Loop in java

As mentioned in all other answers, the keyword continue will skip to the end of the current iteration.

Additionally you can label your loop starts and then use continue [labelname]; or break [labelname]; to control what's going on in nested loops:

loop1: for (int i = 1; i < 10; i++) {
    loop2: for (int j = 1; j < 10; j++) {
        if (i + j == 10)
            continue loop1;

        System.out.print(j);
    }
    System.out.println();
}

Model summary in pytorch

Simplest to remember (not as pretty as Keras):

print(model)

This also work:

repr(model)

If you just want the number of parameters:

sum([param.nelement() for param in model.parameters()])

From: Is there similar pytorch function as model.summary() as keras? (forum.PyTorch.org)

Copying files into the application folder at compile time

You want to use a Post-Build event on your project. You can specify the output there and there are macro values for frequently used things like project path, item name, etc.

React: how to update state.item[1] in state using setState?

First get the item you want, change what you want on that object and set it back on the state. The way you're using state by only passing an object in getInitialState would be way easier if you'd use a keyed object.

handleChange: function (e) {
   item = this.state.items[1];
   item.name = 'newName';
   items[1] = item;

   this.setState({items: items});
}

How to create a simple http proxy in node.js?

Your code doesn't work for binary files because they can't be cast to strings in the data event handler. If you need to manipulate binary files you'll need to use a buffer. Sorry, I do not have an example of using a buffer because in my case I needed to manipulate HTML files. I just check the content type and then for text/html files update them as needed:

app.get('/*', function(clientRequest, clientResponse) {
  var options = { 
    hostname: 'google.com',
    port: 80, 
    path: clientRequest.url,
    method: 'GET'
  };  

  var googleRequest = http.request(options, function(googleResponse) { 
    var body = ''; 

    if (String(googleResponse.headers['content-type']).indexOf('text/html') !== -1) {
      googleResponse.on('data', function(chunk) {
        body += chunk;
      }); 

      googleResponse.on('end', function() {
        // Make changes to HTML files when they're done being read.
        body = body.replace(/google.com/gi, host + ':' + port);
        body = body.replace(
          /<\/body>/, 
          '<script src="http://localhost:3000/new-script.js" type="text/javascript"></script></body>'
        );

        clientResponse.writeHead(googleResponse.statusCode, googleResponse.headers);
        clientResponse.end(body);
      }); 
    }   
    else {
      googleResponse.pipe(clientResponse, {
        end: true
      }); 
    }   
  }); 

  googleRequest.end();
});    

Flutter: Setting the height of the AppBar

You can use PreferredSize:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example',
      home: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(50.0), // here the desired height
          child: AppBar(
            // ...
          )
        ),
        body: // ...
      )
    );
  }
}

Can't find @Nullable inside javax.annotation.*

If you are using Gradle, you could include the dependency like this:

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0'
}

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

The marked answer is completely wrong. All that does is hide the console log statement and does nothing whatsoever do address the actually issue. You can also close your eyes and it will achieve the same result.

The issue is caused by node-gyp and only that. Its purpose is to compile native extensions for certain modules such as bson.

If it fails to do so then the code will fallback to the JS version and kindly tell you so through the informative message:

Failed to load c++ bson extension, using pure JS version

I assume the question is really about how to compile the native C++ extension rather that just not seeing the message so let's address that.

In order for node-gyp to work your node-gyp must be up to date with your node and C++ compiler (that will differ based on your OS). Just as important your module must also be up to date.

First uninstall and reinstall node-gyp

npm un node-gyp -g;npm i node-gyp -g

Now you will need to fully uninstall and reinstall any node module in your app (that includes modules installed by requirements as well) that have bson. That should take care of the error. You can search for 'Release/bson' and find the culprits.

find node_modules/ -type 'f' -exec grep -H 'Release/bson' {} \;

And then uninstall and reinstall these modules.

Easier is to just redo the entire node_modules folder:

 rm -rf node_modules
 npm cache clear
 npm i

If you still experience issues then either 1) your module is out of date - check issue tracker in their repo or 2) you have a potential conflict - sometimes we may have a local node-gyp for example. You can run node-gyp by itself and verify versions.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

You need to go to Help>Eclipse Marketplace . Then type server in the search box it will display Eclipse JST Server Adapters (Apache Tomcat,...) .Select that one and install it .Then go back to Window>Preferences>Server>Runtime Environnement, click add choose Apache tomcat version then add the installation directory .

How do you clone a Git repository into a specific folder?

For Windows user 

1> Open command prompt.
2> Change the directory to destination folder (Where you want to store your project in local machine.)
3> Now go to project setting online(From where you want to clone)
4> Click on clone, and copy the clone command.
5> Now enter the same on cmd .

It will start cloning saving on the selected folder you given .

How to comment out a block of code in Python

At least in VIM you can select the first column of text you want to insert using Block Visual mode (CTRL+V in non-windows VIMs) and then prepend a # before each line using this sequence:

I#<esc>

In Block Visual mode I moves to insert mode with the cursor before the block on its first line. The inserted text is copied before each line in the block.

cordova Android requirements failed: "Could not find an installed version of Gradle"

Solution for Windows (Windows 10) is:

  1. Make sure you have Java 8 installed
  2. Download Gradle binary from https://gradle.org/install/
  3. Create a new directory C:\Gradle with File Explorer
  4. Extract and copy gradle-6.7.1 to C:\Gradle
  5. Configure your PATH environment variable to include the path C:\Gradle\gradle-6.7.1\bin
  6. Run gradle -v to confirm all is okay. C:>Gradle -v

Gradle 6.7.1

Build time: 2020-11-16 17:09:24 UTC Revision: 2972ff02f3210d2ceed2f1ea880f026acfbab5c0

Kotlin: 1.3.72 Groovy: 2.5.12 Ant: Apache Ant(TM) version 1.10.8 compiled on May 10 2020 JVM: 1.8.0_144 (Oracle Corporation 25.144-b01) OS: Windows 10 10.0 x86

C:>

Finally, run [Cordova environments] to check that all is set for development.

C:\Users\opiyog\AndroidStudioProjects\IONIC\SecondApp>cordova requirements

Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed true Android target: installed android-30,android-29,android-28,android-27,android-26,android-25,android-24,android-23,android-22,android-21,android-19 Gradle: installed C:\Gradle\gradle-6.7.1\bin\gradle.BAT

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Source - http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/

Pros

  • Fixed-width layouts are much easier to use and easier to customize in terms of design.
  • Widths are the same for every browser, so there is less hassle with images, forms, video and other content that are fixed-width.
  • There is no need for min-width or max-width, which isn’t supported by every browser anyway.
  • Even if a website is designed to be compatible with the smallest screen resolution, 800×600, the content will still be wide enough at a larger resolution to be easily legible.

Cons

  • A fixed-width layout may create excessive white space for users with larger screen resolutions, thus upsetting “divine proportion,” the “Rule of Thirds,” overall balance and other design principles.
  • Smaller screen resolutions may require a horizontal scroll bar, depending the fixed layout’s width.
  • Seamless textures, patterns and image continuation are needed to accommodate those with larger resolutions.
  • Fixed-width layouts generally have a lower overall score when it comes to usability.

Difference between MEAN.js and MEAN.io

First of all, MEAN is an acronym for MongoDB, Express, Angular and Node.js.

It generically identifies the combined used of these technologies in a "stack". There is no such a thing as "The MEAN framework".

Lior Kesos at Linnovate took advantage of this confusion. He bought the domain MEAN.io and put some code at https://github.com/linnovate/mean

They luckily received a lot of publicity, and theree are more and more articles and video about MEAN. When you Google "mean framework", mean.io is the first in the list.

Unfortunately the code at https://github.com/linnovate/mean seems poorly engineered.

In February I fell in the trap myself. The site mean.io had a catchy design and the Github repo had 1000+ stars. The idea of questioning the quality did not even pass through my mind. I started experimenting with it but it did not take too long to stumble upon things that were not working, and puzzling pieces of code.

The commit history was also pretty concerning. They re-engineered the code and directory structure multiple times, and merging the new changes is too time consuming.

The nice things about both mean.io and mean.js code is that they come with Bootstrap integration. They also come with Facebook, Github, Linkedin etc authentication through PassportJs and an example of a model (Article) on the backend on MongoDB that sync with the frontend model with AngularJS.

According to Linnovate's website:

Linnovate is the leading Open Source company in Israel, with the most experienced team in the country, dedicated to the creation of high-end open source solutions. Linnovate is the only company in Israel which gives an A-Z services for enterprises for building and maintaining their next web project.

From the website it looks like that their core skill set is Drupal (a PHP content management system) and only lately they started using Node.js and AngularJS.

Lately I was reading the Mean.js Blog and things became clearer. My understanding is that the main Javascript developer (Amos Haviv) left Linnovate to work on Mean.js leaving MEAN.io project with people that are novice Node.js developers that are slowing understanding how things are supposed to work.

In the future things may change but for now I would avoid to use mean.io. If you are looking for a boilerplate for a quickstart Mean.js seems a better option than mean.io.

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

How do you completely remove the button border in wpf?

You can use Hyperlink instead of Button, like this:

        <TextBlock>
            <Hyperlink TextDecorations="{x:Null}">
            <Image Width="16"
                   Height="16"
                   Margin="3"
                   Source="/YourProjectName;component/Images/close-small.png" />
            </Hyperlink>
        </TextBlock>

How do I create a foreign key in SQL Server?

I always use this syntax to create the foreign key constraint between 2 tables

Alter Table ForeignKeyTable
Add constraint `ForeignKeyTable_ForeignKeyColumn_FK`
`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`

i.e.

Alter Table tblEmployee
Add constraint tblEmployee_DepartmentID_FK
foreign key (DepartmentID) references tblDepartment (ID)

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Microsoft listed the following methods for getting the a View definition: http://technet.microsoft.com/en-us/library/ms175067.aspx


USE AdventureWorks2012;
GO
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('HumanResources.vEmployee'); 
GO

USE AdventureWorks2012; 
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) 
AS ObjectDefinition; 
GO

EXEC sp_helptext 'HumanResources.vEmployee';

It is more efficient to use if-return-return or if-else-return?

With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.

Check whether specific radio button is checked

Just found a proper working solution for other guys,

_x000D_
_x000D_
// Returns true or false based on the radio button checked_x000D_
$('#test1').prop('checked')_x000D_
_x000D_
_x000D_
$('body').on('change','input[type="radio"]',function () {_x000D_
alert('Test1 checked = ' + $('#test1').prop('checked') + '. Test2 checked = ' + $('#test2').prop('checked') + '. Test3 checked = ' + $('#test3').prop('checked'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="radio" runat="server" name="testGroup" id="test1" /><label for="<%=test1.ClientID %>" style="cursor:hand" runat="server">Test1</label>_x000D_
_x000D_
<input type="radio" runat="server" name="testGroup" id="test2" /><label for="<%=test2.ClientID %>" style="cursor:hand" runat="server">Test2</label>_x000D_
_x000D_
<input type="radio" runat="server" name="testGroup" id="test3" /> <label for="<%=test3.ClientID %>" style="cursor:hand">Test3</label>
_x000D_
_x000D_
_x000D_

and in your method you can use like

return $('#test2').prop('checked');

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

Dim thisMonth As New DateTime(DateTime.Today.Year, DateTime.Today.Month, 1)
Dim firstDayLastMonth As DateTime
Dim lastDayLastMonth As DateTime

firstDayLastMonth = thisMonth.AddMonths(-1)
lastDayLastMonth = thisMonth.AddDays(-1)

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

Something I found was that all the fields have to match EXACTLY.

For example, sending 'cat dog' is not the same as sending 'catdog'.

What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the "Foreign Key" that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.

Once I fixed the 2 fields giving my problems, life was good!

If you need a better explanation, let me know.

How can you run a Java program without main method?

public class X { static {
  System.out.println("Main not required to print this");
  System.exit(0);
}}

Run from the cmdline with java X.

Gradle build without tests

You will have to add -x test

e.g. ./gradlew build -x test

or

gradle build -x test

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

If you want to learn, REALLY want to learn, then time is not of consequence. Just move forward everyday. Let your passion for this stuff drive you forward. And one day you'll see that you are good at C#/.NET.

Insert line break in wrapped cell via code

Yes. The VBA equivalent of AltEnter is to use a linebreak character:

ActiveCell.Value = "I am a " & Chr(10) & "test"

Note that this automatically sets WrapText to True.

Proof:

Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

How to animate the change of image in an UIImageView?

Swift 5 extension:

extension UIImageView{
    func setImage(_ image: UIImage?, animated: Bool = true) {
        let duration = animated ? 0.3 : 0.0
        UIView.transition(with: self, duration: duration, options: .transitionCrossDissolve, animations: {
            self.image = image
        }, completion: nil)
    }
}
 

python: [Errno 10054] An existing connection was forcibly closed by the remote host

This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. (I'm surprised your library doesn't do this automatically.)

Convert nested Python dict to object?

class obj(object):
    def __init__(self, d):
        for a, b in d.items():
            if isinstance(b, (list, tuple)):
               setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])
            else:
               setattr(self, a, obj(b) if isinstance(b, dict) else b)

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = obj(d)
>>> x.b.c
2
>>> x.d[1].foo
'bar'

How to run .APK file on emulator

Steps (These apply for Linux. For other OS, visit here) -

  1. Copy the apk file to platform-tools in android-sdk linux folder.
  2. Open Terminal and navigate to platform-tools folder in android-sdk.
  3. Then Execute this command -

    ./adb install FileName.apk

  4. If the operation is successful (the result is displayed on the screen), then you will find your file in the launcher of your emulator.

For more info can check this link : android videos

Converting PKCS#12 certificate into PEM using OpenSSL

I had a PFX file and needed to create KEY file for NGINX, so I did this:

openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes

Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----. After that NGINX accepted the KEY file.

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

How to automatically close cmd window after batch file execution?

I had this, I added EXIT and initially it didn't work, I guess per requiring the called program exiting advice mentioned in another response here, however it now works without further ado - not sure what's caused this, but the point to note is that I'm calling a data file .html rather than the program that handles it browser.exe, I did not edit anything else but suffice it to say it's much neater just using a bat file to access the main access pages of those web documents and only having title.bat, contents.bat, index.bat in the root folder with the rest of the content in a subfolder.

i.e.: contents.bat reads

cd subfolder
"contents.html"
exit

It also looks better if I change the bat file icons for just those items to suit the context they are in too, but that's another matter, hiding the bat files in the subfolder and creating custom icon shortcuts to them in the root folder with the images called for the customisation also hidden.

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

How to convert an int to string in C?

EDIT: As pointed out in the comment, itoa() is not a standard, so better use sprintf() approach suggested in the rivaling answer!


You can use itoa() function to convert your integer value to a string.

Here is an example:

int num = 321;
char snum[5];

// convert 123 to string [buf]
itoa(num, snum, 10);

// print our string
printf("%s\n", snum);

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

postgresql duplicate key violates unique constraint

In my case carate table script is:

CREATE TABLE public."Survey_symptom_binds"
(
    id integer NOT NULL DEFAULT nextval('"Survey_symptom_binds_id_seq"'::regclass),
    survey_id integer,
    "order" smallint,
    symptom_id integer,
    CONSTRAINT "Survey_symptom_binds_pkey" PRIMARY KEY (id)
)

SO:

SELECT nextval('"Survey_symptom_binds_id_seq"'::regclass),
       MAX(id) 
  FROM public."Survey_symptom_binds"; 
  
SELECT nextval('"Survey_symptom_binds_id_seq"'::regclass) less than MAX(id) !!!

Try to fix the proble:

SELECT setval('"Survey_symptom_binds_id_seq"', (SELECT MAX(id) FROM public."Survey_symptom_binds")+1);

Good Luck every one!

Managing large binary files with Git

I am looking for opinions of how to handle large binary files on which my source code (web application) is dependent. What are your experiences/thoughts regarding this?

I personally have run into synchronisation failures with Git with some of my cloud hosts once my web applications binary data notched above the 3 GB mark. I considered BFT Repo Cleaner at the time, but it felt like a hack. Since then I've begun to just keep files outside of Git purview, instead leveraging purpose-built tools such as Amazon S3 for managing files, versioning and back-up.

Does anybody have experience with multiple Git repositories and managing them in one project?

Yes. Hugo themes are primarily managed this way. It's a little kudgy, but it gets the job done.


My suggestion is to choose the right tool for the job. If it's for a company and you're managing your codeline on GitHub pay the money and use Git-LFS. Otherwise you could explore more creative options such as decentralized, encrypted file storage using blockchain.

Additional options to consider include Minio and s3cmd.

TSQL DATETIME ISO 8601

If you just need to output the date in ISO8601 format including the trailing Z and you are on at least SQL Server 2012, then you may use FORMAT:

SELECT FORMAT(GetUtcDate(),'yyyy-MM-ddTHH:mm:ssZ')

This will give you something like:

2016-02-18T21:34:14Z

Just as @Pxtl points out in a comment FORMAT may have performance implications, a cost that has to be considered compared to any flexibility it brings.

Difference in days between two dates in Java?

Illustration of the problem: (My code is computing delta in weeks, but same issue applies with delta in days)

Here is a very reasonable-looking implementation:

public static final long MILLIS_PER_WEEK = 7L * 24L * 60L * 60L * 1000L;

static public int getDeltaInWeeks(Date latterDate, Date earlierDate) {
    long deltaInMillis = latterDate.getTime() - earlierDate.getTime();
    int deltaInWeeks = (int)(deltaInMillis / MILLIS_PER_WEEK);
    return deltaInWeeks; 
}

But this test will fail:

public void testGetDeltaInWeeks() {
    delta = AggregatedData.getDeltaInWeeks(dateMar09, dateFeb23);
    assertEquals("weeks between Feb23 and Mar09", 2, delta);
}

The reason is:

Mon Mar 09 00:00:00 EDT 2009 = 1,236,571,200,000
Mon Feb 23 00:00:00 EST 2009 = 1,235,365,200,000
MillisPerWeek = 604,800,000
Thus,
(Mar09 - Feb23) / MillisPerWeek =
1,206,000,000 / 604,800,000 = 1.994...

but anyone looking at a calendar would agree that the answer is 2.

Replace all occurrences of a String using StringBuilder?

Yes. It is very simple to use String.replaceAll() method:

package com.test;

public class Replace {

    public static void main(String[] args) {
        String input = "Hello World";
        input = input.replaceAll("o", "0");
        System.out.println(input);
    }
}

Output:

Hell0 W0rld

If you really want to use StringBuilder.replace(int start, int end, String str) instead then here you go:

public static void main(String args[]) {
    StringBuilder sb = new StringBuilder("This is a new StringBuilder");

    System.out.println("Before: " + sb);

    String from = "new";
    String to = "replaced";
    sb = sb.replace(sb.indexOf(from), sb.indexOf(from) + from.length(), to);

    System.out.println("After: " + sb);
}

Output:

Before: This is a new StringBuilder
After: This is a replaced StringBuilder

Swing/Java: How to use the getText and setText string properly

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 

How to append the output to a file?

Yeah.

command >> file to redirect just stdout of command.

command >> file 2>&1 to redirect stdout and stderr to the file (works in bash, zsh)

And if you need to use sudo, remember that just

sudo command >> /file/requiring/sudo/privileges does not work, as privilege elevation applies to command but not shell redirection part. However, simply using tee solves the problem:

command | sudo tee -a /file/requiring/sudo/privileges

How to hide a mobile browser's address bar?

The easiest way to archive browser address bar hiding on page scroll is to add "display": "standalone", to manifest.json file.

Find CRLF in Notepad++

On the Replace dialog, you want to set the search mode to "Extended". Normal or Regular Expression modes wont work.

Then just find "\r\n" (or just \n for unix files or just \r for mac format files), and set the replace to whatever you want.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

SQL-92:

DELETE Field FROM Table WHERE Field IN (SELECT TOP 1 Field FROM Table ORDER BY Field DESC)

Access nested dictionary items via a list of keys?

Using reduce is clever, but the OP's set method may have issues if the parent keys do not pre-exist in the nested dictionary. Since this is the first SO post I saw for this subject in my google search, I would like to make it slightly better.

The set method in ( Setting a value in a nested python dictionary given a list of indices and value ) seems more robust to missing parental keys. To copy it over:

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

Also, it can be convenient to have a method that traverses the key tree and get all the absolute key paths, for which I have created:

def keysInDict(dataDict, parent=[]):
    if not isinstance(dataDict, dict):
        return [tuple(parent)]
    else:
        return reduce(list.__add__, 
            [keysInDict(v,parent+[k]) for k,v in dataDict.items()], [])

One use of it is to convert the nested tree to a pandas DataFrame, using the following code (assuming that all leafs in the nested dictionary have the same depth).

def dict_to_df(dataDict):
    ret = []
    for k in keysInDict(dataDict):
        v = np.array( getFromDict(dataDict, k), )
        v = pd.DataFrame(v)
        v.columns = pd.MultiIndex.from_product(list(k) + [v.columns])
        ret.append(v)
    return reduce(pd.DataFrame.join, ret)

How to check that Request.QueryString has a specific value or not in ASP.NET?

To check for an empty QueryString you should use Request.QueryString.HasKeys property.

To check if the key is present: Request.QueryString.AllKeys.Contains()

Then you can get ist's Value and do any other check you want, such as isNullOrEmpty, etc.

Android Material Design Button Styles

I tried a lot of answer & third party libs, but none was keeping the border and raised effect on pre-lollipop while having the ripple effect on lollipop without drawback. Here is my final solution combining several answers (border/raised are not well rendered on gifs due to grayscale color depth) :

Lollipop

enter image description here

Pre-lollipop

enter image description here

build.gradle

compile 'com.android.support:cardview-v7:23.1.1'

layout.xml

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card"
    card_view:cardElevation="2dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardMaxElevation="8dp"
    android:layout_margin="6dp"
    >
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="0dp"
        android:background="@drawable/btn_bg"
        android:text="My button"/>
</android.support.v7.widget.CardView>

drawable-v21/btn_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
    <item android:drawable="?attr/colorPrimary"/>
</ripple>

drawable/btn_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorPrimaryDark" android:state_pressed="true"/>
    <item android:drawable="@color/colorPrimaryDark" android:state_focused="true"/>
    <item android:drawable="@color/colorPrimary"/>
</selector>

Activity's onCreate

    final CardView cardView = (CardView) findViewById(R.id.card);
    final Button button = (Button) findViewById(R.id.button);
    button.setOnTouchListener(new View.OnTouchListener() {
        ObjectAnimator o1 = ObjectAnimator.ofFloat(cardView, "cardElevation", 2, 8)
                .setDuration
                        (80);
        ObjectAnimator o2 = ObjectAnimator.ofFloat(cardView, "cardElevation", 8, 2)
                .setDuration
                        (80);

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    o1.start();
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    o2.start();
                    break;
            }
            return false;
        }
    });

jQuery select child element by class with unknown path

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

SQL Server procedure declare a list

That is not possible with a normal query since the in clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic query

declare @myList varchar(100)
set @myList = '(1,2,5,7,10)'
exec('select * from DBTable where id IN ' + @myList)

Missing maven .m2 folder

If the default .m2 is unable to find, maybe someone changed the default path. Issue the following command to find out where is the Maven local repository,

mvn help:evaluate -Dexpression=settings.localRepository

The above command will scan for projects and run some tasks. Final outcome will be like below

enter image description here

As you can see in the picture the maven local repository is C:\Users\INOVA\.m2\repository

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I had the same problem and I solved it. My problem was that I was using a listview, with an array adapter and with filter. On the method performFiltering I was messing with the array that have the data and it was the problem since this method is not running on the UI thread and EVENTUALLY it raises some problems.

PHP foreach loop key value

You can access your array keys like so:

foreach ($array as $key => $value)

What is the significance of load factor in HashMap?

Actually, from my calculations, the "perfect" load factor is closer to log 2 (~ 0.7). Although any load factor less than this will yield better performance. I think that .75 was probably pulled out of a hat.

Proof:

Chaining can be avoided and branch prediction exploited by predicting if a bucket is empty or not. A bucket is probably empty if the probability of it being empty exceeds .5.

Let s represent the size and n the number of keys added. Using the binomial theorem, the probability of a bucket being empty is:

P(0) = C(n, 0) * (1/s)^0 * (1 - 1/s)^(n - 0)

Thus, a bucket is probably empty if there are less than

log(2)/log(s/(s - 1)) keys

As s reaches infinity and if the number of keys added is such that P(0) = .5, then n/s approaches log(2) rapidly:

lim (log(2)/log(s/(s - 1)))/s as s -> infinity = log(2) ~ 0.693...

How to change the name of a Django app?

Follow these steps to change an app's name in Django:

  1. Rename the folder which is in your project root
  2. Change any references to your app in their dependencies, i.e. the app's views.py, urls.py , 'manage.py' , and settings.py files.
  3. Edit the database table django_content_type with the following command: UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
  4. Also if you have models, you will have to rename the model tables. For postgres use ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName. For mysql too I think it is the same (as mentioned by @null_radix)
  5. (For Django >= 1.7) Update the django_migrations table to avoid having your previous migrations re-run: UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'. Note: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.
  6. If your models.py 's Meta Class has app_name listed, make sure to rename that too (mentioned by @will).
  7. If you've namespaced your static or templates folders inside your app, you'll also need to rename those. For example, rename old_app/static/old_app to new_app/static/new_app.
  8. For renaming django models, you'll need to change django_content_type.name entry in DB. For postgreSQL use UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'

Meta point (If using virtualenv): Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as ImportError: No module named ... this might be the culprit. (thanks to @danyamachine for providing this).

Other references: you might also want to refer the below links for a more complete picture

  1. Renaming an app with Django and South
  2. How do I migrate a model out of one django app and into a new one?
  3. How to change the name of a Django app?
  4. Backwards migration with Django South
  5. Easiest way to rename a model using Django/South?
  6. Python code (thanks to A.Raouf) to automate the above steps (Untested code. You have been warned!)
  7. Python code (thanks to rafaponieman) to automate the above steps (Untested code. You have been warned!)

Declaring an HTMLElement Typescript

In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.

It’s just syntax sugar, there is no difference between:

var el: HTMLElement = document.getElementById('content');

and:

var el = document.getElementById('content');

On the other hand, because you specify the type you get all the information of your HTMLElement object.

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

How to mount a single file in a volume

For me, the issue was that I had a broken symbolic link on the file I was trying to mount into the container

What is the difference between substr and substring?

let str = "Hello World"

console.log(str.substring(1, 3))  // el -> Excludes the last index
console.log(str.substr(1, 3))  // ell -> Includes the last index

Python: avoiding pylint warnings about too many arguments

You could try using Python's variable arguments feature:

def myfunction(*args):
    for x in args:
        # Do stuff with specific argument here

What's the function like sum() but for multiplication? product()?

Update:

In Python 3.8, the prod function was added to the math module. See: math.prod().

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce  # Required in Python 3
import operator
def prod(iterable):
    return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

Note, the use of log() requires that all the inputs are positive.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

If emails is the pandas dataframe and emails.message the column for email text

## Helper functions
def get_text_from_email(msg):
    '''To get the content from email objects'''
    parts = []
    for part in msg.walk():
        if part.get_content_type() == 'text/plain':
            parts.append( part.get_payload() )
    return ''.join(parts)

def split_email_addresses(line):
    '''To separate multiple email addresses'''
    if line:
        addrs = line.split(',')
        addrs = frozenset(map(lambda x: x.strip(), addrs))
    else:
        addrs = None
    return addrs 

import email
# Parse the emails into a list email objects
messages = list(map(email.message_from_string, emails['message']))
emails.drop('message', axis=1, inplace=True)
# Get fields from parsed email objects
keys = messages[0].keys()
for key in keys:
    emails[key] = [doc[key] for doc in messages]
# Parse content from emails
emails['content'] = list(map(get_text_from_email, messages))
# Split multiple email addresses
emails['From'] = emails['From'].map(split_email_addresses)
emails['To'] = emails['To'].map(split_email_addresses)

# Extract the root of 'file' as 'user'
emails['user'] = emails['file'].map(lambda x:x.split('/')[0])
del messages

emails.head()

Difference between return and exit in Bash functions

First of all, return is a keyword and exit is a function.

That said, here's a simplest of explanations.

return

It returns a value from a function.

exit

It exits out of or abandons the current shell.

How to return JSON with ASP.NET & jQuery

Try to use this , it works perfectly for me

  // 

   varb = new List<object>();

 // Example 

   varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});

 // JSON  + Serializ

public string Json()
        {  
            return (new JavaScriptSerializer()).Serialize(varb);
        }


//  Jquery SIDE 

  var datasets = {
            "Products": {
                label: "Products",
                data: <%= getJson() %> 
            }

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

This code simply worked for me

System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox 54\\firefox.exe");
String Firefoxdriverpath = "C:\\Users\\Hp\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", Firefoxdriverpath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

Use ISNULL(field, 0) It can also be used with aggregates:

ISNULL(count(field), 0)

However, you might consider changing count(field) to count(*)

Edit:

try:

closedcases = ISNULL(
   (select count(closed) from ticket       
    where assigned_to = c.user_id and closed is not null       
    group by assigned_to), 0), 

opencases = ISNULL(
    (select count(closed) from ticket 
     where assigned_to = c.user_id and closed is null 
     group by assigned_to), 0),

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

The remote certificate is invalid according to the validation procedure

Even shorter version of the solution from Dominic Zukiewicz:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

You need to specify the @Provider that @Produces(MediaType.APPLICATION_XML) from B.class
An add the package of your MessageBodyWriter<B.class> to your /WEB_INF/web.xml as:

<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
your.providers.package
</param-value>
</init-param>

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How do you configure HttpOnly cookies in tomcat / java webapps?

Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.

private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
    if (response.containsHeader("SET-COOKIE")) {
        String sessionid = request.getSession().getId();
        String contextPath = request.getContextPath();
        String secure = "";
        if (request.isSecure()) {
            secure = "; Secure"; 
        }
        response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
                         + "; Path=" + contextPath + "; HttpOnly" + secure);
    }
}

Setting the default Java character encoding

I think a better approach than setting the platform's default character set, especially as you seem to have restrictions on affecting the application deployment, let alone the platform, is to call the much safer String.getBytes("charsetName"). That way your application is not dependent on things beyond its control.

I personally feel that String.getBytes() should be deprecated, as it has caused serious problems in a number of cases I have seen, where the developer did not account for the default charset possibly changing.

Show default value in Spinner in android

I found a solution by extending ArrayAdapter and Overriding the getView method.

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * A SpinnerAdapter which does not show the value of the initial selection initially,
 * but an initialText.
 * To use the spinner with initial selection instead call notifyDataSetChanged().
 */
public class SpinnerAdapterWithInitialText<T> extends ArrayAdapter<T> {

    private Context context;
    private int resource;

    private boolean initialTextWasShown = false;
    private String initialText = "Please select";

    /**
     * Constructor
     *
     * @param context The current context.
     * @param resource The resource ID for a layout file containing a TextView to use when
     *                 instantiating views.
     * @param objects The objects to represent in the ListView.
     */
    public SpinnerAdapterWithInitialText(@NonNull Context context, int resource, @NonNull T[] objects) {
        super(context, resource, objects);
        this.context = context;
        this.resource = resource;
    }

    /**
     * Returns whether the user has selected a spinner item, or if still the initial text is shown.
     * @param spinner The spinner the SpinnerAdapterWithInitialText is assigned to.
     * @return true if the user has selected a spinner item, false if not.
     */
    public boolean selectionMade(Spinner spinner) {
        return !((TextView)spinner.getSelectedView()).getText().toString().equals(initialText);
    }

    /**
     * Returns a TextView with the initialText the first time getView is called.
     * So the Spinner has an initialText which does not represent the selected item.
     * To use the spinner with initial selection instead call notifyDataSetChanged(),
     * after assigning the SpinnerAdapterWithInitialText.
     */
    @Override
    public View getView(int position, View recycle, ViewGroup container) {
        if(initialTextWasShown) {
            return super.getView(position, recycle, container);
        } else {
            initialTextWasShown = true;
            LayoutInflater inflater = LayoutInflater.from(context);
            final View view = inflater.inflate(resource, container, false);

            ((TextView) view).setText(initialText);

            return view;
        }
    }
}

What Android does when initialising the Spinner, is calling getView for the selected item before calling getView for all items in T[] objects. The SpinnerAdapterWithInitialText returns a TextView with the initialText, the first time it is called. All the other times it calls super.getView which is the getView method of ArrayAdapter which is called if you are using the Spinner normally.

To find out whether the user has selected a spinner item, or if the spinner still displays the initialText, call selectionMade and hand over the spinner the adapter is assigned to.

Is there a difference between using a dict literal and a dict constructor?

the dict() literal is nice when you are copy pasting values from something else (none python) For example a list of environment variables. if you had a bash file, say

FOO='bar'
CABBAGE='good'

you can easily paste then into a dict() literal and add comments. It also makes it easier to do the opposite, copy into something else. Whereas the {'FOO': 'bar'} syntax is pretty unique to python and json. So if you use json a lot, you might want to use {} literals with double quotes.

Export to csv/excel from kibana

I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.

Check for file exists or not in sql server?

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END

How to set selected item of Spinner by value, not by position?

Here is how to do it if you are using a SimpleCursorAdapter (where columnName is the name of the db column that you used to populate your spinner):

private int getIndex(Spinner spinner, String columnName, String searchString) {

    //Log.d(LOG_TAG, "getIndex(" + searchString + ")");

    if (searchString == null || spinner.getCount() == 0) {

        return -1; // Not found
    }
    else {

        Cursor cursor = (Cursor)spinner.getItemAtPosition(0);

        int initialCursorPos = cursor.getPosition(); //  Remember for later

        int index = -1; // Not found
        for (int i = 0; i < spinner.getCount(); i++) {

            cursor.moveToPosition(i);
            String itemText = cursor.getString(cursor.getColumnIndex(columnName));

            if (itemText.equals(searchString)) {
                index = i; // Found!
                break;
            }
        }

        cursor.moveToPosition(initialCursorPos); // Leave cursor as we found it.

        return index;
    }
}

Also (a refinement of Akhil's answer) this is the corresponding way to do it if you are filling your Spinner from an array:

private int getIndex(Spinner spinner, String searchString) {

    if (searchString == null || spinner.getCount() == 0) {

        return -1; // Not found

    }
    else {

        for (int i = 0; i < spinner.getCount(); i++) {
            if (spinner.getItemAtPosition(i).toString().equals(searchString)) {
                return i; // Found!
            }
        }

        return -1; // Not found
    }
};

How do you stash an untracked file?

To stash your working directory including untracked files (especially those that are in the .gitignore) then you probably want to use this cmd:

git stash --include-untracked

(Alternatively, you can use the shorthand -u instead of --include-untracked)

More details:

Update 17 May 2018:

New versions of git now have git stash --all which stashes all files, including untracked and ignored files.
git stash --include-untracked no longer touches ignored files (tested on git 2.16.2).

Original answer below:

Warning, doing this will permanently delete your files if you have any directory/* entries in your gitignore file.

As of version 1.7.7 you can use git stash --include-untracked or git stash save -u to stash untracked files without staging them.

Add (git add) the file and start tracking it. Then stash. Since the entire contents of the file are new, they will be stashed, and you can manipulate it as necessary.

Meaning of "referencing" and "dereferencing" in C

Referencing means taking the address of an existing variable (using &) to set a pointer variable. In order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer, without the asterisk:

int  c1;
int* p1;
c1 = 5;
p1 = &c1;
//p1 references c1

Dereferencing a pointer means using the * operator (asterisk character) to retrieve the value from the memory address that is pointed by the pointer: NOTE: The value stored at the address of the pointer must be a value OF THE SAME TYPE as the type of variable the pointer "points" to, but there is no guarantee this is the case unless the pointer was set correctly. The type of variable the pointer points to is the type less the outermost asterisk.

int n1;
n1 = *p1;

Invalid dereferencing may or may not cause crashes:

  • Dereferencing an uninitialized pointer can cause a crash
  • Dereferencing with an invalid type cast will have the potential to cause a crash.
  • Dereferencing a pointer to a variable that was dynamically allocated and was subsequently de-allocated can cause a crash
  • Dereferencing a pointer to a variable that has since gone out of scope can also cause a crash.

Invalid referencing is more likely to cause compiler errors than crashes, but it's not a good idea to rely on the compiler for this.

References:

http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators

& is the reference operator and can be read as “address of”.
* is the dereference operator and can be read as “value pointed by”.

http://www.cplusplus.com/doc/tutorial/pointers/

& is the reference operator    
* is the dereference operator

http://en.wikipedia.org/wiki/Dereference_operator

The dereference operator * is also called the indirection operator.

go to link on button click - jquery

$('.button1').click(function() {
   document.location.href='/index.php?id=' + $(this).attr('id');
});

Bootstrap 3 and Youtube in Modal

I have solved it on wordpress template:

$videoLink ="http://www.youtube.com/watch?v=yRuVYkA8i1o;".   
<?php
    parse_str( parse_url( $videoLink, PHP_URL_QUERY ), $my_array_of_vars );
    $youtube_ID = $my_array_of_vars['v'];    
?> 
<a class="video" data-toggle="modal" data-target="#myModal" rel="<?php echo $youtube_ID;?>">
    <img src="<?php bloginfo('template_url');?>/assets/img/play.png" />
</a>

<div class="modal fade video-lightbox" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">    
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body"></div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script> 
    jQuery(document).ready(function ($) {
        var $midlayer = $('.modal-body');     
        $('#myModal').on('show.bs.modal', function (e) {
            var $video = $('a.video');
            var vid = $video.attr('rel');
            var iframe = '<iframe />';  
            var url = "//youtube.com/embed/"+vid+"?autoplay=1&autohide=1&modestbranding=1&rel=0&hd=1";
            var width_f = '100%';
            var height_f = 400;
            var frameborder = 0;
            jQuery(iframe, {
                name: 'videoframe',
                id: 'videoframe',
                src: url,
                width:  width_f,
                height: height_f,
                frameborder: 0,
                class: 'youtube-player',
                type: 'text/html',
                allowfullscreen: true
            }).appendTo($midlayer);   
        });

        $('#myModal').on('hide.bs.modal', function (e) {
            $('div.modal-body').html('');
        }); 
    });
</script>

Outline radius?

As others have said, only firefox supports this. Here is a work around that does the same thing, and even works with dashed outlines.

example

_x000D_
_x000D_
.has-outline {_x000D_
    display: inline-block;_x000D_
    background: #51ab9f;_x000D_
    border-radius: 10px;_x000D_
    padding: 5px;_x000D_
    position: relative;_x000D_
}_x000D_
.has-outline:after {_x000D_
  border-radius: 10px;_x000D_
  padding: 5px;_x000D_
  border: 2px dashed #9dd5cf;_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  top: -2px;_x000D_
  left: -2px;_x000D_
  bottom: -2px;_x000D_
  right: -2px;_x000D_
}
_x000D_
<div class="has-outline">_x000D_
  I can haz outline_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the use of ObservableCollection in .net?

ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.

The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections

class Handler
{
    private ObservableCollection<string> collection;

    public Handler()
    {
        collection = new ObservableCollection<string>();
        collection.CollectionChanged += HandleChange;
    }

    private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
    {
        foreach (var x in e.NewItems)
        {
            // do something
        }

        foreach (var y in e.OldItems)
        {
            //do something
        }
        if (e.Action == NotifyCollectionChangedAction.Move)
        {
            //do something
        }
    }
}

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Jquery in React is not defined

Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:

fetch('http://jsonplaceholder.typicode.com/posts') 
  .then((response) => { return response.json(); }) 
  .then((myJson) => { 
     this.setState({data: myJson}); // for example
});

Java: Array with loop

int[] nums = new int[100];

int sum = 0;

// Fill it with numbers using a for-loop for (int i = 0; i < nums.length; i++)

{ 
     nums[i] = i + 1;
    sum += n;
}

System.out.println(sum);

Input Type image submit form value?

Some browsers (IIRC it is just some versions of Internet Explorer) only send the co-ordinates of the image map (in name.x and name.y) and ignore the value. This is a bug.

The workarounds are to either:

  • Have only one submit button and use a hidden input to sent the value
  • Use regular submit buttons instead of image maps
  • Use unique names instead of values and check for the presence of name.x / name.y

Calling C++ class methods via a function pointer

Read this for detail :

// 1 define a function pointer and initialize to NULL

int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;

// C++

class TMyClass
{
public:
   int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
   int DoMore(float a, char b, char c) const
         { cout << "TMyClass::DoMore" << endl; return a-b+c; };

   /* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore

// Calling Function using Function Pointer

(*this.*pt2ConstMember)(12, 'a', 'b');

symfony2 : failed to write cache directory

If the folder is already writable so thats not the problem.

You can also just navigate to /www/projet_etienne/app/cache/ and manualy remove the folders in there (dev, dev_new, dev_old).

Make sure to SAVE a copy of those folder somewhere to put back if this doesn't fix the problem

I know this is not the way it should be done but it worked for me a couple of times now.

Check difference in seconds between two times

DateTime has a Subtract method and an overloaded - operator for just such an occasion:

DateTime now = DateTime.UtcNow;
TimeSpan difference = now.Subtract(otherTime); // could also write `now - otherTime`
if (difference.TotalSeconds > 5) { ... }

Base64 length calculation?

If there is someone interested in achieve the @Pedro Silva solution in JS, I just ported this same solution for it:

const getBase64Size = (base64) => {
  let padding = base64.length
    ? getBase64Padding(base64)
    : 0
  return ((Math.ceil(base64.length / 4) * 3 ) - padding) / 1000
}

const getBase64Padding = (base64) => {
  return endsWith(base64, '==')
    ? 2
    : 1
}

const endsWith = (str, end) => {
  let charsFromEnd = end.length
  let extractedEnd = str.slice(-charsFromEnd)
  return extractedEnd === end
}

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

Reflection: How to Invoke Method with parameters

I would use it like this, its way shorter and it won't give any problems

        dynamic result = null;
        if (methodInfo != null)
        {
            ParameterInfo[] parameters = methodInfo.GetParameters();
            object classInstance = Activator.CreateInstance(type, null);
            result = methodInfo.Invoke(classInstance, parameters.Length == 0 ? null : parametersArray);
        }

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

Difference between System.DateTime.Now and System.DateTime.Today

DateTime dt = new DateTime();// gives 01/01/0001 12:00:00 AM
DateTime dt = DateTime.Now;// gives today date with current time
DateTime dt = DateTime.Today;// gives today date and 12:00:00 AM time

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

Printing 1 to 1000 without loop or conditionals

#include <stdio.h>
int main(int argc, char** argv)
{
printf("numbers from 1 to 1000\n");
}

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

Unable to install pyodbc on Linux

I used this:

yum install unixODBC.x86_64

Depending on the version of centos could change the package, you can search like this:

yum search unixodbc

Convert Datetime column from UTC to local time in select statement

I found the one off function way to be too slow when there is a lot of data. So I did it through joining to a table function that would allow for a calculation of the hour diff. It is basically datetime segments with the hour offset. A year would be 4 rows. So the table function

dbo.fn_getTimeZoneOffsets('3/1/2007 7:00am', '11/5/2007 9:00am', 'EPT')

would return this table:

startTime          endTime   offset  isHr2
3/1/07 7:00     3/11/07 6:59    -5    0
3/11/07 7:00    11/4/07 6:59    -4    0
11/4/07 7:00    11/4/07 7:59    -5    1
11/4/07 8:00    11/5/07 9:00    -5    0

It does account for daylight savings. A sample of how it is uses is below and the full blog post is here.

select mt.startTime as startUTC, 
    dateadd(hh, tzStart.offset, mt.startTime) as startLocal, 
    tzStart.isHr2
from MyTable mt 
inner join dbo.fn_getTimeZoneOffsets(@startViewUTC, @endViewUTC, @timeZone)  tzStart
on mt.startTime between tzStart.startTime and tzStart.endTime

Creating a LINQ select from multiple tables

change

select op) 

to

select new { op, pg })

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

An other example would be on the "created_on" column where you want to let the database handle the date creation

How do I get the width and height of a HTML5 canvas?

None of those worked for me. Try this.

console.log($(canvasjQueryElement)[0].width)

How does the ARM architecture differ from x86?

Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.

As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.

There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).

ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.

At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).

Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.

ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.

Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.

So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

How to find foreign key dependencies in SQL Server?

Because your question is geared towards a single table, you can use this:

EXEC sp_fkeys 'TableName'

I found it on SO here:

https://stackoverflow.com/a/12956348/652519

I found the information I needed pretty quickly. It lists the foreign key's table, column and name.

EDIT

Here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

Sort an ArrayList based on an object field

Modify the DataNode class so that it implements Comparable interface.

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

then just use

Collections.sort(nodeList);

What is the difference between parseInt(string) and Number(string) in JavaScript?

The first one takes two parameters:

parseInt(string, radix)

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the
    radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature
    is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

The other function you mentioned takes only one parameter:

Number(object)

The Number() function converts the object argument to a number that represents the object's value.

If the value cannot be converted to a legal number, NaN is returned.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem with exactly the same error message. In the end the error was, that I still called the maps v2 javascript. I had to replace:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=####################" type="text/javascript"></script>

with

<script src="http://maps.googleapis.com/maps/api/js?key=####################&sensor=false" type="text/javascript"></script>

after this, it worked fine. took me a while ;-)

Creating a SOAP call using PHP with an XML body

First off, you have to specify you wish to use Document Literal style:

$client = new SoapClient(NULL, array(
    'location' => 'https://example.com/path/to/service',
    'uri' => 'http://example.com/wsdl',
    'trace' => 1,
    'use' => SOAP_LITERAL)
);

Then, you need to transform your data into a SoapVar; I've written a simple transform function:

function soapify(array $data)
{
        foreach ($data as &$value) {
                if (is_array($value)) {
                        $value = soapify($value);
                }
        }

        return new SoapVar($data, SOAP_ENC_OBJECT);
}

Then, you apply this transform function onto your data:

$data = soapify(array(
    'Acquirer' => array(
        'Id' => 'MyId',
        'UserId' => 'MyUserId',
        'Password' => 'MyPassword',
    ),
));

Finally, you call the service passing the Data parameter:

$method = 'Echo';

$result = $client->$method(new SoapParam($data, 'Data'));

HTML5 placeholder css padding

I have tested almost all methods given here in this page for my Angular app. Only I found solution via &nbsp; that inserts spaces i.e.

Angular Material

add &nbsp; in the placeholder, like

<input matInput type="text" placeholder="&nbsp;&nbsp;Email">

Non Angular Material

Add padding to your input field, like below. Click Run Code Snippet to see demo

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container m-3 d-flex flex-column align-items-center justify-content-around" style="height:100px;">
<input type="text" class="pl-0" placeholder="Email with no Padding" style="width:240px;">
<input type="text" class="pl-3" placeholder="Email with 1 rem padding" style="width:240px;">
</div>
_x000D_
_x000D_
_x000D_

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

I faced a similar problem. The problem in my case was, Number of rows in X was not equal to number of rows in y.

i.e. number of entries in feature columns was not equal to number of entires in target variable since I had dropped some rows from freature columns.

how to create a logfile in php?

create a logfile in php, to do it you need to pass data on function and it will create log file for you.

function wh_log($log_msg)
{
    $log_filename = "log";
    if (!file_exists($log_filename)) 
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
} 
// call to function
wh_log("this is my log message");

Vue.js getting an element within a component

Composition API

Template refs section tells how this has been unified:

  • within template, use ref="myEl"; :ref= with a v-for
  • within script, have a const myEl = ref(null) and expose it from setup

The reference carries the DOM element from mounting onwards.

Constructor in an Interface?

A work around you can try is defining a getInstance() method in your interface so the implementer is aware of what parameters need to be handled. It isn't as solid as an abstract class, but it allows more flexibility as being an interface.

However this workaround does require you to use the getInstance() to instantiate all objects of this interface.

E.g.

public interface Module {
    Module getInstance(Receiver receiver);
}

How can I create an array with key value pairs?

You can create the single value array key-value as

$new_row = array($row["datasource_id"]=>$row["title"]);

inside while loop, and then use array_merge function in loop to combine the each new $new_row array.

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

Eclipse internal error while initializing Java tooling

I faced the same issue. Switching back to the predefined work-space from the Switch workspace option in eclipse solved my issue.

What's the HTML to have a horizontal space between two objects?

CSS

div.horizontalgap {
  float: left;
  overflow: hidden;
  height: 1px;
  width: 0px;
}

Usage in HTML (for a 10px horizontal gap)

<div class="horizontalgap" style="width:10px"></div>

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

How to get value at a specific index of array In JavaScript?

Just use indexer

var valueAtIndex1 = myValues[1];

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

Nullable DateTime conversion

You might want to do it like this:

DateTime? lastPostDate =  (DateTime?)(reader.IsDbNull(3) ? null : reader[3]); 

The problem you are having is that the ternary operator wants a viable cast between the left and right sides. And null can't be cast to DateTime.

Note the above works because both sides of the ternary are object's. The object is explicitly cast to DateTime? which works: as long as reader[3] is in fact a date.