Programs & Examples On #Document set

getResourceAsStream() is always returning null

A call to Class#getResourceAsStream(String) delegates to the class loader and the resource is searched in the class path. In other words, you current code won't work and you should put abc.txt in WEB-INF/classes, or in WEB-INF/lib if packaged in a jar file.

Or use ServletContext.getResourceAsStream(String) which allows servlet containers to make a resource available to a servlet from any location, without using a class loader. So use this from a Servlet:

this.getServletContext().getResourceAsStream("/WEB-INF/abc.txt") ;

But is there a way I can call getServletContext from my Web Service?

If you are using JAX-WS, then you can get a WebServiceContext injected:

@Resource
private WebServiceContext wsContext;

And then get the ServletContext from it:

ServletContext sContext= wsContext.getMessageContext()
                             .get(MessageContext.SERVLET_CONTEXT));

AngularJS $watch window resize inside directive

You shouldn't need a $watch. Just bind to resize event on window:

DEMO

'use strict';

var app = angular.module('plunker', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){

         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);

How do I run a PowerShell script when the computer starts?

enter image description hereA relatively short path to specifying a Powershell script to execute at startup in Windows could be:

  1. Click the Windows-button (Windows-button + r)
  2. Enter this:

shell:startup

  1. Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut

  2. Create a shortcut to your script, e.g:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "C:\Users\someuser\Documents\WindowsPowerShell\Scripts\somesscript.ps1"

Note the use of -NoProfile In case you put a lot of initializing in your $profile file, it is inefficient to load this up to just run a Powershell script. The -NoProfile will skip loading your profile file and is smart to specify, if it is not necessary to run it before the Powershell script is to be executed.

Here you see such a shortcut created (.lnk file with a Powershell icon with shortcut glyph):

How to emulate a do-while loop in Python?

The way I've done this is as follows...

condition = True
while condition:
     do_stuff()
     condition = (<something that evaluates to True or False>)

This seems to me to be the simplistic solution, I'm surprised I haven't seen it here already. This can obviously also be inverted to

while not condition:

etc.

Can I set the height of a div based on a percentage-based width?

I made a CSS approach to this that is sized by the viewport width, but maxes out at 100% of the viewport height. It doesn't require box-sizing:border-box. If a pseudo element cannot be used, the pseudo-code's CSS can be applied to a child. Demo

.container {
  position: relative;
  max-width:100vh;
  max-height:100%;
  margin:0 auto;
  overflow: hidden;
}
.container:before {
  content: "";
  display: block;
  margin-top: 100%;
}
.child {
  position: absolute;
  top: 0;
  left: 0;
}

Support table for viewport units

I wrote about this approach and others in a CSS-Tricks article on scaling responsive animations that you should check out.

How to make a div with a circular shape?

HTML div elements, unlike SVG circle primitives, are always rectangular.

You could use round corners (i.e. CSS border-radius) to make it look round. On square elements, a value of 50% naturally forms a circle. Use this, or even a SVG inside your HTML:

_x000D_
_x000D_
document.body.innerHTML+='<i></i>'.repeat(4);
_x000D_
i{border-radius:50%;display:inline-block;background:#F48024;}
svg {fill:#F48024;width:60px;height:60px;}
i:nth-of-type(1n){width:30px;height:30px;}
i:nth-of-type(2n){width:60px;height:60px;}
_x000D_
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
  <circle cx="60" cy="60" r="60"/>
</svg>
_x000D_
_x000D_
_x000D_

Convert string to List<string> in one line?

Use Split() function to slice them and ToList() to return them as a list.

var names = "Brian,Joe,Chris";
List<string> nameList = names.Split(',').ToList();

Using stored procedure output parameters in C#

In your C# code, you are using transaction for the command. Just commit the transaction and after that access your parameter value, you will get the value. Worked for me. :)

Drawing an image from a data URL to a canvas

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

How to configure PHP to send e-mail?

Usually a good place to start when you run into problems is the manual. The page on configuring email explains that there's a big difference between the PHP mail command running on MSWindows and on every other operating system; it's a good idea when posting a question to provide relevant information on how that part of your system is configured and what operating system it is running on.

Your PHP is configured to talk to an SMTP server - the default for an MSWindows machine, but either you have no MTA installed or it's blocking connections. While for a commercial website running your own MTA robably comes quite high on the list of things to do, it is not a trivial exercise - you really need to know what you're doing to get one configured and running securely. It would make a lot more sense in your case to use a service configured and managed by someone else.

Since you'll be connecting to a remote MTA using a gmail address, then you should probably use Gmail's server; you will need SMTP authenticaton and probably SSL support - neither of which are supported by the mail() function in PHP. There's a simple example here using swiftmailer with gmail or here's an example using phpmailer

Convert byte to string in Java

you can use

the character equivalent to 0x63 is 'c' but byte equivalent to it is 99

System.out.println("byte "+(char)0x63); 

How do I change the number of open files limit in Linux?

If you are using Linux and you got the permission error, you will need to raise the allowed limit in the /etc/limits.conf or /etc/security/limits.conf file (where the file is located depends on your specific Linux distribution).

For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the limits.conf file.

* hard nofile 10000

Then logout and relogin to your system and you should be able to do:

ulimit -n 10000

without a permission error.

How to display data from database into textbox, and update it

Wrap your all statements in !IsPostBack condition on page load.

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      // all statements
   }
}

This will fix your issue.

Simple 3x3 matrix inverse code (C++)

Don't try to do this yourself if you're serious about getting edge cases right. So while they many naive/simple methods are theoretically exact, they can have nasty numerical behavior for nearly singular matrices. In particular you can get cancelation/round-off errors that cause you to get arbitrarily bad results.

A "correct" way is Gaussian elimination with row and column pivoting so that you're always dividing by the largest remaining numerical value. (This is also stable for NxN matrices.). Note that row pivoting alone doesn't catch all the bad cases.

However IMO implementing this right and fast is not worth your time - use a well tested library and there are a heap of header only ones.

How to list all methods for an object in Ruby?

Module#instance_methods

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod’s superclasses are returned.

module A
  def method1()  end
end
class B
  def method2()  end
end
class C < B
  def method3()  end
end

A.instance_methods                #=> [:method1]
B.instance_methods(false)         #=> [:method2]
C.instance_methods(false)         #=> [:method3]
C.instance_methods(true).length   #=> 43

Regular Expression for password validation

Pattern satisfy, these below criteria

  1. Password Length 8 and Maximum 15 character
  2. Require Unique Chars
  3. Require Digit
  4. Require Lower Case
  5. Require Upper Case
^(?!.*([A-Za-z0-9]))(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$

Pass array to ajax request in $.ajax()

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});

Batch file to copy files from one folder to another folder

You can use esentutl to copy (mainly big) files with a progress bar:

esentutl /y "my.file" /d "another.file" /o

the progress bar looks like this:

enter image description here

Your branch is ahead of 'origin/master' by 3 commits

This message from git means that you have made three commits in your local repo, and have not published them to the master repository. The command to run for that is git push {local branch name} {remote branch name}.

The command git pull (and git pull --rebase) are for the other situation when there are commit on the remote repo that you don't have in your local repo. The --rebase option means that git will move your local commit aside, synchronise with the remote repo, and then try to apply your three commit from the new state. It may fail if there is conflict, but then you'll be prompted to resolve them. You can also abort the rebase if you don't know how to resolve the conflicts by using git rebase --abort and you'll get back to the state before running git pull --rebase.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

Select all DIV text with single mouse click

UPDATE 2017:

To select the node's contents call:

window.getSelection().selectAllChildren(
    document.getElementById(id)
);

This works on all modern browsers including IE9+ (in standards mode).

Runnable Example:

_x000D_
_x000D_
function select(id) {_x000D_
  window.getSelection()_x000D_
    .selectAllChildren(_x000D_
      document.getElementById("target-div") _x000D_
    );_x000D_
}
_x000D_
#outer-div  { padding: 1rem; background-color: #fff0f0; }_x000D_
#target-div { padding: 1rem; background-color: #f0fff0; }_x000D_
button      { margin: 1rem; }
_x000D_
<div id="outer-div">_x000D_
  <div id="target-div">_x000D_
    Some content for the _x000D_
    <br>Target DIV_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
_x000D_
_x000D_
_x000D_


The original answer below is obsolete since window.getSelection().addRange(range); has been deprecated

Original Answer:

All of the examples above use:

    var range = document.createRange();
    range.selectNode( ... );

but the problem with that is that it selects the Node itself including the DIV tag etc.

To select the Node's text as per the OP question you need to call instead:

    range.selectNodeContents( ... )

So the full snippet would be:

    function selectText( containerid ) {

        var node = document.getElementById( containerid );

        if ( document.selection ) {
            var range = document.body.createTextRange();
            range.moveToElementText( node  );
            range.select();
        } else if ( window.getSelection ) {
            var range = document.createRange();
            range.selectNodeContents( node );
            window.getSelection().removeAllRanges();
            window.getSelection().addRange( range );
        }
    }

What is output buffering?

As name suggest here memory buffer used to manage how the output of script appears.

Here is one very good tutorial for the topic

Delete all but the most recent X files in bash

(ls -t|head -n 5;ls)|sort|uniq -u|xargs rm

This version supports names with spaces:

(ls -t|head -n 5;ls)|sort|uniq -u|sed -e 's,.*,"&",g'|xargs rm

Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

In bootstrap how to add borders to rows without adding up?

On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:

First give all of the rows children a border on the right and bottom

.borders div{
    border-right:1px solid #999;
    border-bottom:1px solid #999;
}

Next give the first child of each or a left border

.borders div:first-child{
    border-left:
    1px solid #999;
}

Last make sure to clear the borders for their child elements

.borders div > div{
    border:0;
}

HTML:

<div class="row borders">
    <div class="col-xs-5 col-md-2">Email</div>
    <div class="col-xs-7 col-md-4">[email protected]</div>
    <div class="col-xs-5 col-md-2">Phone</div>
    <div class="col-xs-7 col-md-4">555-123-4567</div>
</div>

Why doesn't catching Exception catch RuntimeException?

class Test extends Thread
{
    public void run(){  
        try{  
            Thread.sleep(10000);  
        }catch(InterruptedException e){  
            System.out.println("test1");
            throw new RuntimeException("Thread interrupted..."+e);  
        }  

    }  

    public static void main(String args[]){  
        Test t1=new Test1();  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
            System.out.println("test2");
            System.out.println("Exception handled "+e);
        }  

    }  
}

Its output doesn't contain test2 , so its not handling runtime exception. @jon skeet, @Jan Zyka

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

How to save an HTML5 Canvas as an image on a server?

I just made an imageCrop and Upload feature with

https://www.npmjs.com/package/react-image-crop

to get the ImagePreview ( the cropped image rendering in a canvas)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

I prefer sending data in blob with content type image/jpeg rather than toDataURL ( a huge base64 string`

My implementation for uploading to Azure Blob using SAS URL

axios.post(azure_sas_url, image_in_blob, {
   headers: {
      'x-ms-blob-type': 'BlockBlob',
      'Content-Type': 'image/jpeg'
   }
})

How to check db2 version

db2ls command will display the db2level along with the install path and install date.

To determine the specific product installed:

db2ls -p -q -b <installpath>

on db2ls command.

The following will appear:

Install Path       Level   Fix Pack   Special Install Number   Install Date    Installer UID
--------------------------------------------------------------------------------------------
/opt/ibm/db2/V9.7  9.7.0.7        7                      Thu Aug  1 12:25:53 2013 CDT     0

visit IBM Website

How to compare if two structs, slices or maps are equal?

Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb

func compare(a, b T) bool {
  if &a == &b {
    return true
  }
  if a.X != b.X || a.Y != b.Y {
    return false
  }
  if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
    return false
  }
  for i, v := range a.Z {
    if b.Z[i] != v {
      return false
    }
  }
  for k, v := range a.M {
    if b.M[k] != v {
      return false
    }
  }
  return true
}

Procedure expects parameter which was not supplied

I came across this error today when null values were passed to my stored procedure's parameters. I was able easily fix by altering the stored procedure by adding default value = null.

VSCode regex find & replace submatch math?

To augment Benjamin's answer with an example:

Find        Carrots(With)Dip(Are)Yummy
Replace     Bananas$1Mustard$2Gross
Result      BananasWithMustardAreGross

Anything in the parentheses can be a regular expression.

Reading CSV file and storing values into an array

I usually use this parser from codeproject, since there's a bunch of character escapes and similar that it handles for me.

How to get the primary IP address of the local machine on Linux and OS X?

I just utilize Network Interface Names, my custom command is

[[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' 

in my own notebook

[flying@lempstacker ~]$ cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 
[flying@lempstacker ~]$ [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
192.168.2.221
[flying@lempstacker ~]$

but if the network interface owns at least one ip, then it will show all ip belong to it

for example

Ubuntu 16.10

root@yakkety:~# sed -r -n 's@"@@g;s@^VERSION=(.*)@\1@p' /etc/os-release
16.04.1 LTS (Xenial Xerus)
root@yakkety:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
178.62.236.250
root@yakkety:~#

Debian Jessie

root@jessie:~# sed -r -n 's@"@@g;s@^PRETTY_NAME=(.*)@\1@p' /etc/os-release
Debian GNU/Linux 8 (jessie)
root@jessie:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
192.81.222.54
root@jessie:~# 

CentOS 6.8

[root@centos68 ~]# cat /etc/redhat-release 
CentOS release 6.8 (Final)
[root@centos68 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
162.243.17.224
10.13.0.5
[root@centos68 ~]# ip route get 1 | awk '{print $NF;exit}'
162.243.17.224
[root@centos68 ~]#

Fedora 24

[root@fedora24 ~]# cat /etc/redhat-release 
Fedora release 24 (Twenty Four)
[root@fedora24 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
104.131.54.185
10.17.0.5
[root@fedora24 ~]# ip route get 1 | awk '{print $NF;exit}'
104.131.54.185
[root@fedora24 ~]#

It seems like that command ip route get 1 | awk '{print $NF;exit}' provided by link is more accurate, what's more, it more shorter.

do <something> N times (declarative syntax)

Using Array.from and .forEach.

_x000D_
_x000D_
let length = 5;_x000D_
Array.from({length}).forEach((v, i) => {_x000D_
  console.log(`#${i}`);_x000D_
});
_x000D_
_x000D_
_x000D_

Java 8, Streams to find the duplicate elements

A multiset is a structure maintaining the number of occurrences for each element. Using Guava implementation:

Set<Integer> duplicated =
        ImmutableMultiset.copyOf(numbers).entrySet().stream()
                .filter(entry -> entry.getCount() > 1)
                .map(Multiset.Entry::getElement)
                .collect(Collectors.toSet());

Index of Currently Selected Row in DataGridView

Try it:

int rc=dgvDataRc.CurrentCell.RowIndex;** //for find the row index number
MessageBox.Show("Current Row Index is = " + rc.ToString());

I hope it will help you.

How can I fix "Design editor is unavailable until a successful build" error?

If you are in corporate setting where there is a proxy server, double check your proxy settings.

  1. Go File -> Settings
  2. Search for Proxy.
  3. Fill out as appropreate.
  4. Test connection.

If you think you fat-fingered the password, there is a Clear passwords button you can click to where you can re-enter your creds. HTH

How to export specific request to file using postman?

If you want to export it as a file just do Any Collection (...) -> Export. There you should be able to choose collection version format and it will be exported in JSN file.

Declaration of Methods should be Compatible with Parent Methods in PHP

childClass::customMethod() has different arguments, or a different access level (public/private/protected) than parentClass::customMethod().

What does the keyword "transient" mean in Java?

Transient variables in Java are never serialized.

iPhone: How to get current milliseconds?

Try this :

NSDate * timestamp = [NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSS"];

NSString *newDateString = [dateFormatter stringFromDate:timestamp];
timestamp = (NSDate*)newDateString;

In this example, dateWithTimeIntervalSince1970 is used in combination of the formatter @"YYYY-MM-dd HH:mm:ss.SSS" that will return the date with year, month, day and the time with hours, minutes, seconds, and milliseconds. See the example : "2015-12-02 04:43:15.008". I used the NSString to be sure that the format will be has written before.

Found 'OR 1=1/* sql injection in my newsletter database

The specific value in your database isn't what you should be focusing on. This is likely the result of an attacker fuzzing your system to see if it is vulnerable to a set of standard attacks, instead of a targeted attack exploiting a known vulnerability.

You should instead focus on ensuring that your application is secure against these types of attacks; OWASP is a good resource for this.

If you're using parameterized queries to access the database, then you're secure against Sql injection, unless you're using dynamic Sql in the backend as well.

If you're not doing this, you're vulnerable and you should resolve this immediately.

Also, you should consider performing some sort of validation of e-mail addresses.

add created_at and updated_at fields to mongoose schemas

You can use this plugin very easily. From the docs:

var timestamps = require('mongoose-timestamp');
var UserSchema = new Schema({
    username: String
});
UserSchema.plugin(timestamps);
mongoose.model('User', UserSchema);
var User = mongoose.model('User', UserSchema)

And also set the name of the fields if you wish:

mongoose.plugin(timestamps,  {
  createdAt: 'created_at', 
  updatedAt: 'updated_at'
});

How do I declare a namespace in JavaScript?

Sample:

var namespace = {};
namespace.module1 = (function(){

    var self = {};
    self.initialized = false;

    self.init = function(){
        setTimeout(self.onTimeout, 1000)
    };

    self.onTimeout = function(){
        alert('onTimeout')
        self.initialized = true;
    };

    self.init(); /* If it needs to auto-initialize, */
    /* You can also call 'namespace.module1.init();' from outside the module. */
    return self;
})()

You can optionally declare a local variable, same, like self and assign local.onTimeout if you want it to be private.

JQuery Ajax POST in Codeigniter

In codeigniter there is no need to sennd "data" in ajax post method.. here is the example .

   searchThis = 'This text will be search';
    $.ajax({
      type: "POST",
      url: "<?php echo site_url();?>/software/search/"+searchThis,
      dataType: "html",
      success:function(data){
        alert(data);
      },

    });

Note : in url , software is the controller name , search is the function name and searchThis is the variable that i m sending.

Here is the controller.

    public function search(){
    $search = $this->uri->segment(3);
      echo '<p>'.$search.'</p>';
    }

I hope you can get idea for your work .

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.

-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory

-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder

-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf

-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.

If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop

Create sample .php file and put below code and run on wamp or xampp server

$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);

This code working for me in windows-8 operating system

sending mail from Batch file

We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file

blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt

Or you can put that file in as the body

blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"

WordPress path url in js script file

    wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
    wp_enqueue_script('custom-js');

    $wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
    wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );

and in custom.js

alert(wnm_custom.template_url);

Python pip install module is not found. How to link python to pip location?

how did you install easy_install/pip? make sure that you installed it for the upgraded version of python. what could have happened here is that the old (default) python install might be linked to your pip install. you might wanna try running the default version and importing the newly installed modules.

What is the difference between compileSdkVersion and targetSdkVersion?

As a oneliner guide:

minSdkVersion <= targetSdkVersion <= compileSdkVersion

Ideally:

minSdkVersion (lowest possible) <= targetSdkVersion == compileSdkVersion (latest SDK)

Read more from this great post by Ian Lake

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

How to use ConcurrentLinkedQueue?

Just use it as you would a non-concurrent collection. The Concurrent[Collection] classes wrap the regular collections so that you don't have to think about synchronizing access.

Edit: ConcurrentLinkedList isn't actually just a wrapper, but rather a better concurrent implementation. Either way, you don't have to worry about synchronization.

Adding multiple class using ng-class

With multiple conditions

<div ng-class="{'class1' : con1 || can2, 'class2' : con3 && con4}">
Hello World!
</div>

How do I install Java on Mac OSX allowing version switching?

Manually switching system-default version without 3rd party tools:

As detailed in this older answer, on macOS /usr/bin/java is a wrapper tool that will use Java version pointed by JAVA_HOME or if that variable is not set will look for Java installations under /Library/Java/JavaVirtualMachines/ and will use the one with highest version. It determines versions by looking at Contents/Info.plist under each package.

Armed with this knowledge you can:

  • control which version the system will use by renaming Info.plist in versions you don't want to use as default (that file is not used by the actual Java runtime itself).
  • control which version to use for specific tasks by setting $JAVA_HOME

I've just verified this is still true with OpenJDK & Mojave.

On a brand new system, there is no Java version installed:

$ java -version
No Java runtime present, requesting install.

Cancel this, download OpenJDK 11 & 12ea on https://jdk.java.net ; install OpenJDK11:

$ cd /Library/Java/JavaVirtualMachines/
$ sudo tar xzf ~/Downloads/openjdk-11.0.1_osx-x64_bin.tar.gz

System java is now 11:

$ java -version
openjdk version "11.0.1" 2018-10-16
[...]

Install OpenJDK12 (early access at the moment):

$ sudo tar xzf ~/Downloads/openjdk-12-ea+17_osx-x64_bin.tar.gz 

System java is now 12:

$ java -version
openjdk version "12-ea" 2019-03-19
[...]

Now let's "hide" OpenJDK 12 from system java wrapper:

$ cd jdk-12.jdk/Contents/
$ sudo mv Info.plist Info.plist.disabled

System java is back to 11:

$ java -version
openjdk version "11.0.1" 2018-10-16
[...]

And you can still use version 12 punctually by manually setting JAVA_HOME:

$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
$ java -version
openjdk version "12-ea" 2019-03-19
[...]

#1214 - The used table type doesn't support FULLTEXT indexes

From official reference

Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.

https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html

InnoDB with MySQL 5.5 does not support Full-text indexes.

Accessing Objects in JSON Array (JavaScript)

Use a loop

for(var i = 0; i < obj.length; ++i){
   //do something with obj[i]
   for(var ind in obj[i]) {
        console.log(ind);
        for(var vals in obj[i][ind]){
            console.log(vals, obj[i][ind][vals]);
        }
   }
}

Demo: http://jsfiddle.net/maniator/pngmL/

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Just use simple properties.

var tomorrow = currentDateTime.Date + 1;  
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
                            .Where(x =>  x.DateTimeStart >= currentDateTime.Date 
                                   and x.DateTimeStart < tomorrow);

If future dates are not possible in your app, then >= x.DateTimeStart >= currentDateTime.Date is sufficient.

if you have more complex date comparisons, then check Canonical functions and if you have EF6+ DB functions

More Generally - For people searching for issues Supported Linq methods in EF can explain similar issues with linq statements that work on Memory base Lists but not in EF.

C char array initialization

Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer.

Your code will result in compiler errors. Your first code fragment:

char buf[10] ; buf = ''

is doubly illegal. First, in C, there is no such thing as an empty char. You can use double quotes to designate an empty string, as with:

char* buf = ""; 

That will give you a pointer to a NUL string, i.e., a single-character string with only the NUL character in it. But you cannot use single quotes with nothing inside them--that is undefined. If you need to designate the NUL character, you have to specify it:

char buf = '\0';

The backslash is necessary to disambiguate from character '0'.

char buf = 0;

accomplishes the same thing, but the former is a tad less ambiguous to read, I think.

Secondly, you cannot initialize arrays after they have been defined.

char buf[10];

declares and defines the array. The array identifier buf is now an address in memory, and you cannot change where buf points through assignment. So

buf =     // anything on RHS

is illegal. Your second and third code fragments are illegal for this reason.

To initialize an array, you have to do it at the time of definition:

char buf [10] = ' ';

will give you a 10-character array with the first char being the space '\040' and the rest being NUL, i.e., '\0'. When an array is declared and defined with an initializer, the array elements (if any) past the ones with specified initial values are automatically padded with 0. There will not be any "random content".

If you declare and define the array but don't initialize it, as in the following:

char buf [10];

you will have random content in all the elements.

Regular expression for validating names and surnames?

I would think you would be better off excluding the characters you don't want with a regex. Trying to get every umlaut, accented e, hyphen, etc. will be pretty insane. Just exclude digits (but then what about a guy named "George Forman the 4th") and symbols you know you don't want like @#$%^ or what have you. But even then, using a regex will only guarantee that the input matches the regex, it will not tell you that it is a valid name

EDIT after clarifying that this is trying to prevent XSS: A regex on a name field is obviously not going to stop XSS on it's own. However, this article has a section on filtering that is a starting point if you want to go that route.

http://tldp.org/HOWTO/Secure-Programs-HOWTO/cross-site-malicious-content.html

s/[\<\>\"\'\%\;\(\)\&\+]//g;

resize2fs: Bad magic number in super-block while trying to open

On Centos 7, in answer to the original question where resize2fs fails with "bad magic number" try using fsadm as follows:

fsadm resize /dev/the-device-name-returned-by-df

Then:

df 

... to confirm the size changes have worked.

Making PHP var_dump() values display one line per value

Yes, try wrapping it with <pre>, e.g.:

echo '<pre>' , var_dump($variable) , '</pre>';

Disabling browser print options (headers, footers, margins) from page?

This worked for me with about 1cm margin

@page 
{
    size:  auto;   /* auto is the initial value */
    margin: 0mm;  /* this affects the margin in the printer settings */
}
html
{
    background-color: #FFFFFF; 
    margin: 0mm;  /* this affects the margin on the html before sending to printer */
}
body
{
    padding:30px; /* margin you want for the content */
}

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

How to call a method daily, at specific time, in C#?

As others have said you can use a console app to run when scheduled. What others haven't said is that you can this app trigger a cross process EventWaitHandle which you are waiting on in your main application.

Console App:

class Program
{
    static void Main(string[] args)
    {
        EventWaitHandle handle = 
            new EventWaitHandle(true, EventResetMode.ManualReset, "GoodMutexName");
        handle.Set();
    }
}

Main App:

private void Form1_Load(object sender, EventArgs e)
{
    // Background thread, will die with application
    ThreadPool.QueueUserWorkItem((dumby) => EmailWait());
}

private void EmailWait()
{
    EventWaitHandle handle = 
        new EventWaitHandle(false, EventResetMode.ManualReset, "GoodMutexName");

    while (true)
    {
        handle.WaitOne();

        SendEmail();

        handle.Reset();
    }
}

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I first tried Mohammed Emad's answer - no joy. Then I tried

git clean -x -d -f

which brought me to a new "Roslyn" error which I was able to fix by manually editing my .csproj.

Interestingly, after I'd read down a bit further down the page on the Roslyn question, I found another suggestion with even more votes (Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r). Thinking I'd rather implement that than manually edit .csproj, I backed out my .csproj changes, only to find my solution was still working.

So after all that, I'm wondering if Mohammed's answer (on this page) would have done the trick, had I simply done the git clean first.

Add missing dates to pandas dataframe

An alternative approach is resample, which can handle duplicate dates in addition to missing dates. For example:

df.resample('D').mean()

resample is a deferred operation like groupby so you need to follow it with another operation. In this case mean works well, but you can also use many other pandas methods like max, sum, etc.

Here is the original data, but with an extra entry for '2013-09-03':

             val
date           
2013-09-02     2
2013-09-03    10
2013-09-03    20    <- duplicate date added to OP's data
2013-09-06     5
2013-09-07     1

And here are the results:

             val
date            
2013-09-02   2.0
2013-09-03  15.0    <- mean of original values for 2013-09-03
2013-09-04   NaN    <- NaN b/c date not present in orig
2013-09-05   NaN    <- NaN b/c date not present in orig
2013-09-06   5.0
2013-09-07   1.0

I left the missing dates as NaNs to make it clear how this works, but you can add fillna(0) to replace NaNs with zeroes as requested by the OP or alternatively use something like interpolate() to fill with non-zero values based on the neighboring rows.

correct way of comparing string jquery operator =

First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"

Spring Boot: Cannot access REST Controller on localhost (404)

for me, I was adding spring-web instead of the spring-boot-starter-web into my pom.xml

when i replace it from spring-web to spring-boot-starter-web, all maping is shown in the console log.

Select columns based on string match - dplyr::select

You can try:

select(data, matches("search_string"))

It is more general than contains - you can use regex (e.g. "one_string|or_the_other").

For more examples, see: http://rpackages.ianhowson.com/cran/dplyr/man/select.html.

DataTables: Cannot read property style of undefined

It can also happen when drawing a new (other) table. I solved this by first removing the previous table:

$("#prod_tabel_ph").remove();

SQL SERVER: Get total days between two dates

if you want to do same thing Store Procedure then you need to apply below code.

select  (datediff(dd,'+CHAR(39)+ convert(varchar(10),@FromDate  ,101)+ 
 CHAR(39)+','+CHAR(39)+ convert(varchar(10),@ToDate  ,101) + CHAR(39) +')) 
 Daysdiff

where @fromdate and @todate is Parameter of the SP

Why is a ConcurrentModificationException thrown and how to debug it

In Java 8, you can use lambda expression:

map.keySet().removeIf(key -> key condition);

Angular js init ng-model from default values

If you can't rework your app to do what @blesh suggests (pull JSON data down with $http or $resource and populate $scope), you can use ng-init instead:

<input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">

See also AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Find Nth occurrence of a character in a string

Here's another, maybe simpler implementation of string IndexOfNth() with strings implementation.

Here's the string match version:

public static int IndexOfNth(this string source, string matchString, 
                             int charInstance, 
                             StringComparison stringComparison = StringComparison.CurrentCulture)
{
    if (string.IsNullOrEmpty(source))
        return -1;

    int lastPos = 0;
    int count = 0;

    while (count < charInstance )
    {
        var len = source.Length - lastPos;
        lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
        if (lastPos == -1)
            break;

        count++;
        if (count == charInstance)
            return lastPos;

        lastPos += matchString.Length;
    }
    return -1;
}

and the char match version:

public static int IndexOfNth(string source, char matchChar, int charInstance)        
{
    if (string.IsNullOrEmpty(source))
        return -1;

    if (charInstance < 1)
        return -1;

    int count = 0;
    for (int i = 0; i < source.Length; i++)
    {
        if (source[i] == matchChar)
        {
            count++;
            if (count == charInstance)                 
                return i;                 
        }
    }
    return -1;
}

I think for such a low level implementation you'd want to stay away from using LINQ, RegEx or recursion to reduce overhead.

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

Android/Eclipse: how can I add an image in the res/drawable folder?

Drop in the image in /res/drawable folder. Then in Eclipse Menu, do ->Project -> Clean. This will do a clean build if set to build automatically.

SQL Server: how to create a stored procedure

Create this way.

Create procedure dept_count(dept_name varchar(20),d_count integer)
   begin
     select count(*) into d_count
     from instructor
     where instructor.dept_name=dept_count.dept_name
   end

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

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

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

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

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

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

Tell Ruby Program to Wait some amount of time

sleep 6 will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes) or sleep(6.hours).

How to get JSON Key and Value?

First, I see you're using an explicit $.parseJSON(). If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.

To iterate through the first item in the array you've got there, use code like this:

var firstItem = response.d[0];

for(key in firstItem) {
  console.log(key + ':' + firstItem[key]);
}

If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d and then use this code inside that outer loop.

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

I use to always add a new target on my solutions for achieving this.

<Target Name="clean_folders">
  <RemoveDir Directories=".\ProjectName\bin" />
  <RemoveDir Directories=".\ProjectName\obj" />
  <RemoveDir Directories="$(ProjectVarName)\bin" />
  <RemoveDir Directories="$(ProjectVarName)\obj" />
</Target>

And you can call it from command line

msbuild /t:clean_folders

This can be your batch file.

msbuild /t:clean_folders
PAUSE

Android Stop Emulator from Command Line

To automate this, you can use any script or app that can send a string to a socket. I personally like nc (netcat) under cygwin. As I said before, I use it like this:

$ echo kill | nc -w 2 localhost 5554

(that means to send "kill" string to the port 5554 on localhost, and terminate netcat after 2 seconds.)

Simple way to repeat a string

If you are worried about performance, just use a StringBuilder inside the loop and do a .toString() on exit of the Loop. Heck, write your own Util Class and reuse it. 5 Lines of code max.

in angularjs how to access the element that triggered the event?

you can get easily like this first write event on element

ng-focus="myfunction(this)"

and in your js file like below

$scope.myfunction= function (msg, $event) {
    var el = event.target
    console.log(el);
}

I have used it as well.

Pandas Merge - How to avoid duplicating columns

I use the suffixes option in .merge():

dfNew = df.merge(df2, left_index=True, right_index=True,
                 how='outer', suffixes=('', '_y'))
dfNew.drop(dfNew.filter(regex='_y$').columns.tolist(),axis=1, inplace=True)

Thanks @ijoseph

How to change the scrollbar color using css

You can use the following attributes for webkit, which reach into the shadow DOM:

::-webkit-scrollbar              { /* 1 */ }
::-webkit-scrollbar-button       { /* 2 */ }
::-webkit-scrollbar-track        { /* 3 */ }
::-webkit-scrollbar-track-piece  { /* 4 */ }
::-webkit-scrollbar-thumb        { /* 5 */ }
::-webkit-scrollbar-corner       { /* 6 */ }
::-webkit-resizer                { /* 7 */ }

Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.

http://jsfiddle.net/hmartiro/Xck2A/1/

Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.

What are projection and selection?

Exactly.

Projection means choosing which columns (or expressions) the query shall return.

Selection means which rows are to be returned.

if the query is

select a, b, c from foobar where x=3;

then "a, b, c" is the projection part, "where x=3" the selection part.

How to Return partial view of another controller by controller?

The control searches for a view in the following order:

  • First in shared folder
  • Then in the folder matching the current controller (in your case it's Views/DEF)

As you do not have xxx.cshtml in those locations, it returns a "view not found" error.

Solution: You can use the complete path of your view:

Like

 PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

How to compare numbers in bash?

I solved this by using a small function to convert version strings to plain integer values that can be compared:

function versionToInt() {
  local IFS=.
  parts=($1)
  let val=1000000*parts[0]+1000*parts[1]+parts[2]
  echo $val
}

This makes two important assumptions:

  1. Input is a "normal SemVer string"
  2. Each part is between 0-999

For example

versionToInt 12.34.56  # --> 12034056
versionToInt 1.2.3     # -->  1002003

Example testing whether npm command meets minimum requirement ...

NPM_ACTUAL=$(versionToInt $(npm --version))  # Capture npm version
NPM_REQUIRED=$(versionToInt 4.3.0)           # Desired version
if [ $NPM_ACTUAL \< $NPM_REQUIRED ]; then
  echo "Please update to npm@latest"
  exit 1
fi

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

currently unable to handle this request HTTP ERROR 500

I found this was caused by adding a new scope variable to the login scope

Reading a text file in MATLAB line by line

Just read it in to MATLAB in one block

fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);

You can then process it using logical addressing

ind50 = data{2}>=50 ;

ind50 is then an index of the rows where column 2 is greater than 50. So

data{1}(ind50)

will list all the strings for the rows of interest. Then just use fprintf to write out your data to the new file

Convert JSONObject to Map

use Jackson (https://github.com/FasterXML/jackson) from http://json.org/

HashMap<String,Object> result =
       new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);

Flutter does not find android sdk

You have to set ANDROID_HOME variable to SDK.

Create a new variable by the name and set it to the installation directory.

Make sure SDK is not below 2 subfolders from c drive or any windows root drive.

"Could not find a valid gem in any repository" (rubygame and others)

check your DNS settings ...I was facing similar problem ... when I checked my /etc/resolve.config file ,the name server was missing ... after adding it the problem gets resolved

Microsoft Excel mangles Diacritics in .csv files?

Prepending a BOM (\uFEFF) worked for me (Excel 2007), in that Excel recognised the file as UTF-8. Otherwise, saving it and using the import wizard works, but is less ideal.

How to override the [] operator in Python?

You need to use the __getitem__ method.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

And if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

how to access parent window object using jquery?

or you can use another approach:

$( "#serverMsg", window.opener.document )

CSS transition shorthand with multiple properties?

Syntax:

transition: <property> || <duration> || <timing-function> || <delay> [, ...];

Note that the duration must come before the delay, if the latter is specified.

Individual transitions combined in shorthand declarations:

-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;

Or just transition them all:

-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;

Here is a straightforward example. Here is another one with the delay property.


Edit: previously listed here were the compatibilities and known issues regarding transition. Removed for readability.

Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.

If you still want to be sure, refer to http://caniuse.com/css-transitions

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.

multiple packages in context:component-scan, spring config

The following approach is correct:

<context:component-scan base-package="x.y.z.service, x.y.z.controller" /> 

Note that the error complains about x.y.z.dao.daoservice.LoginDAO, which is not in the packages mentioned above, perhaps you forgot to add it:

<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" /> 

Using an array as needles in strpos

str_replace is considerably faster.

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

Th part of an URI after the # is called "fragment" and is by definition only available/processed on client side (see https://en.wikipedia.org/wiki/Fragment_identifier).

On the client side, this can be accessed using javaScript with window.location.hash.

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

CSS height 100% percent not working

Night's answer is correct

 html, body {margin:0;padding:0;height:100%;}

Also check that your div or element is NOT inside another one (with height less than 100%) Hope this helps someone else.

Where are my postgres *.conf files?

As I don't have access to postgres account (so can't run SHOW config_file) and my postgres is installed on Windows, none of the answers helped me, so I'm sharing my file location for future Windows readers:

C:\Program Files\PostgreSQL\9.5\data

What is the best way to get the minimum or maximum value from an Array of numbers?

The theoretical answers from everyone else are all neat, but let's be pragmatic. ActionScript provides the tools you need so that you don't even have to write a loop in this case!

First, note that Math.min() and Math.max() can take any number of arguments. Also, it's important to understand the apply() method available to Function objects. It allows you to pass arguments to the function using an Array. Let's take advantage of both:

var myArray:Array = [2,3,3,4,2,2,5,6,7,2];
var maxValue:Number = Math.max.apply(null, myArray);
var minValue:Number = Math.min.apply(null, myArray);

Here's the best part: the "loop" is actually run using native code (inside Flash Player), so it's faster than searching for the minimum or maximum value using a pure ActionScript loop.

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

Apache Cordova - uninstall globally

This can happen when the cordova was installed globally on a different version of the node.

Being necessary to manually delete yourself as suggested in the previous comment:

which cordova

it will output something like this

/usr/local/bin/

then removing by

rm -rf /usr/local/bin/cordova

sql delete statement where date is greater than 30 days

GETDATE() didn't work for me using mySQL 8

ERROR 1305 (42000): FUNCTION mydatabase.GETDATE does not exist

but this does:

DELETE FROM table_name WHERE date_column < CURRENT_DATE - 30;

AttributeError: 'module' object has no attribute 'urlopen'

import urllib.request as ur

filehandler = ur.urlopen ('http://www.google.com')
for line in filehandler:
    print(line.strip())

How to "test" NoneType in python?

So how can I question a variable that is a NoneType?

Use is operator, like this

if variable is None:

Why this works?

Since None is the sole singleton object of NoneType in Python, we can use is operator to check if a variable has None in it or not.

Quoting from is docs,

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

Since there can be only one instance of None, is would be the preferred way to check None.


Hear it from the horse's mouth

Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Why is Event.target not Element in Typescript?

With typescript we can leverage type aliases, like so:

type KeyboardEvent = {
  target: HTMLInputElement,
  key: string,
};
const onKeyPress = (e: KeyboardEvent) => {
  if ('Enter' === e.key) { // Enter keyboard was pressed!
    submit(e.target.value);
    e.target.value = '';
    return;
  }
  // continue handle onKeyPress input events...
};

How to Set Active Tab in jQuery Ui

Just to clarify in complete detail. This is what works with the current version of jQuery Ui

$( "#tabs" ).tabs( "option", "active", # );

where # is the index of the tab you want to make active.

jquery change button color onclick

I would just create a separate CSS class:

.ButtonClicked {
    background-color:red;
}

And then add the class on click:

$('#ButtonId').on('click',function(){
    !$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});

This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ? and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.

You can also create the ability to have an "on/off" switch feel by toggling the class:

$('#ButtonId').on('click',function(){
    $(this).toggleClass('ButtonClicked');
});

Shown by this jsFiddle. Just food for thought.

How to list active / open connections in Oracle?

select
  username,
  osuser,
  terminal,
  utl_inaddr.get_host_address(terminal) IP_ADDRESS
from
  v$session
where
  username is not null
order by
  username,
  osuser;

How to read pickle file?

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break

@synthesize vs @dynamic, what are the differences?

As others have said, in general you use @synthesize to have the compiler generate the getters and/ or settings for you, and @dynamic if you are going to write them yourself.

There is another subtlety not yet mentioned: @synthesize will let you provide an implementation yourself, of either a getter or a setter. This is useful if you only want to implement the getter for some extra logic, but let the compiler generate the setter (which, for objects, is usually a bit more complex to write yourself).

However, if you do write an implementation for a @synthesize'd accessor it must still be backed by a real field (e.g., if you write -(int) getFoo(); you must have an int foo; field). If the value is being produce by something else (e.g. calculated from other fields) then you have to use @dynamic.

How to join two tables by multiple columns in SQL?

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score
FROM Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum

Problem with converting int to string in Linq to entities

One more solution:

c.ContactId + ""

Just add empty string and it will be converted to string.

VIM Disable Automatic Newline At End Of File

Try to add in .vimrc

set binary

What are enums and why are they useful?

Enum? Why should it be used? I think it's more understood when you will use it. I have the same experience.

Say you have a create, delete, edit and read database operation.

Now if you create an enum as an operation:

public enum operation {
    create("1")
    delete("2")
    edit("3")
    read("4")

    // You may have is methods here
    public boolean isCreate() {
        return this.equals(create);
    }
    // More methods like the above can be written

}

Now, you may declare something like:

private operation currentOperation;

// And assign the value for it 
currentOperation = operation.create

So you can use it in many ways. It's always good to have enum for specific things as the database operation in the above example can be controlled by checking the currentOperation. Perhaps one can say this can be accomplished with variables and integer values too. But I believe Enum is a safer and a programmer's way.

Another thing: I think every programmer loves boolean, don't we? Because it can store only two values, two specific values. So Enum can be thought of as having the same type of facilities where a user will define how many and what type of value it will store, just in a slightly different way. :)

get data from mysql database to use in javascript

Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?

  1. Send AJAX request to php script
  2. PHP script processes request and builds table
  3. PHP script sends response back to JS in form of encoded HTML
  4. JS takes response and inserts it into the DOM

Difference between Python's Generators and Iterators

Examples from Ned Batchelder highly recommended for iterators and generators

A method without generators that do something to even numbers

def evens(stream):
   them = []
   for n in stream:
      if n % 2 == 0:
         them.append(n)
   return them

while by using a generator

def evens(stream):
    for n in stream:
        if n % 2 == 0:
            yield n
  • We don't need any list nor a return statement
  • Efficient for large/ infinite length stream ... it just walks and yield the value

Calling the evens method (generator) is as usual

num = [...]
for n in evens(num):
   do_smth(n)
  • Generator also used to Break double loop

Iterator

A book full of pages is an iterable, A bookmark is an iterator

and this bookmark has nothing to do except to move next

litr = iter([1,2,3])
next(litr) ## 1
next(litr) ## 2
next(litr) ## 3
next(litr) ## StopIteration  (Exception) as we got end of the iterator

To use Generator ... we need a function

To use Iterator ... we need next and iter

As been said:

A Generator function returns an iterator object

The Whole benefit of Iterator:

Store one element a time in memory

Can I escape a double quote in a verbatim string literal?

Use double quotation marks.

string foo = @"this ""word"" is escaped";

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Query to list all users of a certain group

If the DC is Win2k3 SP2 or above, you can use something like:

(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))

to get the nested group membership.

Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

How do I preserve line breaks when getting text from a textarea?

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).

Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.append(postText);_x000D_
  var card = document.createElement('div');_x000D_
  card.append(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.prepend(card);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Note that, like your original code, the snippet above uses append() and prepend(). As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:

  • element.append(otherElement) can be replaced with element.appendChild(otherElement);
  • element.prepend(otherElement) can be replaced with element.insertBefore(otherElement, element.firstChild);
  • element.append(stringOfText) can be replaced with element.appendChild(document.createTextNode(stringOfText));
  • element.prepend(stringOfText) can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild);
  • as a special case, if element is empty, both element.append(stringOfText) and element.prepend(stringOfText) can simply be replaced with element.textContent = stringOfText.

Here's the same snippet as above, but without using append() or prepend():

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Ps. If you really want to do this without using the CSS white-space property, an alternative solution would be to explicitly replace any newline characters in the text with <br> HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, & and <) in the text before you do this replacement.

Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:

var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');  // <-- THIS FIXES THE LINE BREAKS_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_

Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.

How do I import a namespace in Razor View Page?

Finally found the answer.

@using MyNamespace

For VB.Net:

@Imports Mynamespace

Take a look at @ravy amiry's answer if you want to include a namespace across the app.

How can I return two values from a function in Python?

I would like to return two values from a function in two separate variables.

What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.

Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).

When i tried to to use return i, card, it returns a tuple and this is not what i want.

Actually, it's exactly what you want. All you have to do is take the tuple apart again.

And i want to be able to use these values separately.

So just grab the values out of the tuple.

The easiest way to do this is by unpacking:

a, b = select_choice()

overlay a smaller image on a larger image python OpenCv

Here it is:

def put4ChannelImageOn4ChannelImage(back, fore, x, y):
    rows, cols, channels = fore.shape    
    trans_indices = fore[...,3] != 0 # Where not transparent
    overlay_copy = back[y:y+rows, x:x+cols] 
    overlay_copy[trans_indices] = fore[trans_indices]
    back[y:y+rows, x:x+cols] = overlay_copy

#test
background = np.zeros((1000, 1000, 4), np.uint8)
background[:] = (127, 127, 127, 1)
overlay = cv2.imread('imagee.png', cv2.IMREAD_UNCHANGED)
put4ChannelImageOn4ChannelImage(background, overlay, 5, 5)

How to Convert datetime value to yyyymmddhhmmss in SQL server?

FORMAT() is slower than CONVERT(). This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.

112 = yyyymmdd - no format change needed

108 = hh:mm:ss - remove :

SELECT CONVERT(VARCHAR, GETDATE(), 112) + 
       REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')

The name 'controlname' does not exist in the current context

this error often occurs when you miss runat="server" .

C++: Where to initialize variables in constructor

Option 1 allows you to use a place specified exactly for explicitly initializing member variables.

Python: Passing variables between functions

passing variable from one function as argument to other functions can be done like this

define functions like this

def function1():
global a
a=input("Enter any number\t")

def function2(argument):
print ("this is the entered number - ",argument)

call the functions like this

function1()
function2(a)

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

JQuery .hasClass for multiple values in an if statement

This may be another solution:

if ($('html').attr('class').match(/m320|m768/)) {  
  // do stuff   
}  

according to jsperf.com it's quite fast, too.

How to modify list entries during for loop?

Since the loop below only modifies elements already seen, it would be considered acceptable:

a = ['a',' b', 'c ', ' d ']

for i, s in enumerate(a):
    a[i] = s.strip()

print(a) # -> ['a', 'b', 'c', 'd']

Which is different from:

a[:] = [s.strip() for s in a]

in that it doesn't require the creation of a temporary list and an assignment of it to replace the original, although it does require more indexing operations.

Caution: Although you can modify entries this way, you can't change the number of items in the list without risking the chance of encountering problems.

Here's an example of what I mean—deleting an entry messes-up the indexing from that point on:

b = ['a', ' b', 'c ', ' d ']

for i, s in enumerate(b):
    if s.strip() != b[i]:  # leading or trailing whitespace?
        del b[i]

print(b)  # -> ['a', 'c ']  # WRONG!

(The result is wrong because it didn't delete all the items it should have.)

Update

Since this is a fairly popular answer, here's how to effectively delete entries "in-place" (even though that's not exactly the question):

b = ['a',' b', 'c ', ' d ']

b[:] = [entry for entry in b if entry.strip() == entry]

print(b)  # -> ['a']  # CORRECT

Convert hex string (char []) to int?

Use strtol if you have libc available like the top answer suggests. However if you like custom stuff or are on a microcontroller without libc or so, you may want a slightly optimized version without complex branching.

#include <inttypes.h>


/**
 * xtou64
 * Take a hex string and convert it to a 64bit number (max 16 hex digits).
 * The string must only contain digits and valid hex characters.
 */
uint64_t xtou64(const char *str)
{
    uint64_t res = 0;
    char c;

    while ((c = *str++)) {
        char v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
        res = (res << 4) | (uint64_t) v;
    }

    return res;
} 

The bit shifting magic boils down to: Just use the last 4 bits, but if it is an non digit, then also add 9.

Sort list in C# with LINQ

Like this?

In LINQ:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces.

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

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

PHP Change Array Keys

To have the same key I think they must be in separate nested arrays.

for ($i = 0; $i < count($array); $i++) {
    $newArray[] = ['name' => $array[$i]];
};

Output:

0 => array:1 ["name" => "blabla"]
1 => array:1 ["name" => "blabla"]
2 => array:1 ["name" => "blblll"]

javascript create empty array of a given size

We use Array.from({length: 500}) since 2017.

What does this GCC error "... relocation truncated to fit..." mean?

Minimal example that generates the error

main.S moves an address into %eax (32-bit).

main.S

_start:
    mov $_start, %eax

linker.ld

SECTIONS
{
    /* This says where `.text` will go in the executable. */
    . = 0x100000000;
    .text :
    {
        *(*)
    }
}

Compile on x86-64:

as -o main.o main.S
ld -o main.out -T linker.ld main.o

Outcome of ld:

(.text+0x1): relocation truncated to fit: R_X86_64_32 against `.text'

Keep in mind that:

  • as puts everything on the .text if no other section is specified
  • ld uses the .text as the default entry point if ENTRY. Thus _start is the very first byte of .text.

How to fix it: use this linker.ld instead, and subtract 1 from the start:

SECTIONS
{
    . = 0xFFFFFFFF;
    .text :
    {
        *(*)
    }
}

Notes:

  • we cannot make _start global in this example with .global _start, otherwise it still fails. I think this happens because global symbols have alignment constraints (0xFFFFFFF0 works). TODO where is that documented in the ELF standard?

  • the .text segment also has an alignment constraint of p_align == 2M. But our linker is smart enough to place the segment at 0xFFE00000, fill with zeros until 0xFFFFFFFF and set e_entry == 0xFFFFFFFF. This works, but generates an oversized executable.

Tested on Ubuntu 14.04 AMD64, Binutils 2.24.

Explanation

First you must understand what relocation is with a minimal example: https://stackoverflow.com/a/30507725/895245

Next, take a look at objdump -Sr main.o:

0000000000000000 <_start>:
   0:   b8 00 00 00 00          mov    $0x0,%eax
                        1: R_X86_64_32  .text

If we look into how instructions are encoded in the Intel manual, we see that:

  • b8 says that this is a mov to %eax
  • 0 is an immediate value to be moved to %eax. Relocation will then modify it to contain the address of _start.

When moving to 32-bit registers, the immediate must also be 32-bit.

But here, the relocation has to modify those 32-bit to put the address of _start into them after linking happens.

0x100000000 does not fit into 32-bit, but 0xFFFFFFFF does. Thus the error.

This error can only happen on relocations that generate truncation, e.g. R_X86_64_32 (8 bytes to 4 bytes), but never on R_X86_64_64.

And there are some types of relocation that require sign extension instead of zero extension as shown here, e.g. R_X86_64_32S. See also: https://stackoverflow.com/a/33289761/895245

R_AARCH64_PREL32

Asked at: How to prevent "main.o:(.eh_frame+0x1c): relocation truncated to fit: R_AARCH64_PREL32 against `.text'" when creating an aarch64 baremetal program?

How to find out when an Oracle table was updated the last time

You would need to add a trigger on insert, update, delete that sets a value in another table to sysdate.

When you run application, it would read the value and save it somewhere so that the next time it is run it has a reference to compare.

Would you consider that "Special Admin Stuff"?

It would be better to describe what you're actually doing so you get clearer answers.

How to count the number of lines of a string in javascript

 <script type="text/javascript">
      var multilinestr = `
        line 1
        line 2
        line 3
        line 4
        line 5
        line 6`;
      totallines = multilinestr.split("\n");
lines = str.split("\n"); 
console.log(lines.length);
</script>

thats works in my case

Error - trustAnchors parameter must be non-empty

Fall into this using Amazon SDK v2, Windows 10 and JDK8. Amazon SDK was complaining about credentials loading.
I solved this by replacing the security/cacert file of JDK8 by the JDK11 one.

Convert list to dictionary using linq and not worrying about duplicates

In case we want all the Person (instead of only one Person) in the returning dictionary, we could:

var _people = personList
.GroupBy(p => p.FirstandLastName)
.ToDictionary(g => g.Key, g => g.Select(x=>x));

convert datetime to date format dd/mm/yyyy

DateTime dt = DateTime.ParseExact(yourObject.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);

Adding items to an object through the .push() method

.push() is a method of the Built-in Array Object

It is not related to jQuery in any way.

You are defining a literal Object with

// Object
var stuff = {};

You can define a literal Array like this

// Array
var stuff = [];

then

stuff.push(element);

Arrays actually get their bracket syntax stuff[index] inherited from their parent, the Object. This is why you are able to use it the way you are in your first example.

This is often used for effortless reflection for dynamically accessing properties

stuff = {}; // Object

stuff['prop'] = 'value'; // assign property of an 
                         // Object via bracket syntax

stuff.prop === stuff['prop']; // true

How to change icon on Google map marker

You have to add the targeted map :

var markers = [
            {
            "title": 'This is title',
            "lat": '-37.801578',
            "lng": '145.060508',
            "map":  map,
            "icon": 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png',
            "description": 'Vikash Rathee. <strong> This is test Description</strong> <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by 

City</a>'
            }
];

Programmatically register a broadcast receiver

Two choices

1) If you want to read Broadcast only when the Activity is visible then,

registerReceiver(...) in onStart() and unregisterReceiver(...) in onStop()

2) If you want to read Broadcast even if Activity is in Background then,

registerReceiver(...) in onCreate(...) and unregisterReceiver(...) in onDestroy()

Bonus:

If you are lazy

If you don't want to write boilerplate code for registering and unregistering a BroadcastReceiver again and again in each Activity then,

  1. Create an abstract Activity
  2. Write boilerplate code in Activity
  3. Leave the implementation as abstract methods

Here is the code snippet:

Abstract Activity

public abstract class BasicActivity extends AppCompatActivity {

    private BroadcastReceiver broadcastReceiver;
    private IntentFilter filter;
    private static final String TAG = "BasicActivity";

    /**********************************************************************
    *                   Boilerplate code
    **********************************************************************/

    @Override
    public void onCreate(Bundle sis){
        super.onCreate(sis);
        broadcastReceiver = getBroadcastReceiver();
        filter = getFilter();
    }

    @Override
    public void onStart(){
        super.onStart();
        register();
    }

    @Override
    public void onStop(){
        super.onStop();
        unregister();
    }

    private void register(){
        registerReceiver(broadcastReceiver,filter);
    }

    private void unregister(){
        unregisterReceiver(broadcastReceiver);
    }

    /**********************************************************************
    *                   Abstract methods
    **********************************************************************/

    public abstract BroadcastReceiver getBroadcastReceiver();

    public abstract IntentFilter getFilter();

}

Using this approach you can write more boilerplate code such as writing common animations, binding to a service, etc.

See full code:

HERE

Where are the recorded macros stored in Notepad++?

If you install Notepad++ on Linux system by wine (In my case desktop Ubuntu 14.04-LTS_X64) the file "shortcuts.xml" is under :

$/home/[USER-NAME]/.wine/drive_c/users/[USER-NAME]/My Documents/.wine/drive_c/Program Files (x86)/Notepad++/shortcuts.xml

Thanks to Harrison and all that have suggestions for that isssue.

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

Python: finding an element in a list

how's this one?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

Usage:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

clk'event vs rising_edge()

The linked comment is incorrect : 'L' to '1' will produce a rising edge.

In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk) will (correctly) not trigger while (clk'event and clk = '1') (incorrectly) will.

Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.

How to pass an array into a SQL Server stored procedure

Based on my experience, by creating a delimited expression from the employeeIDs, there is a tricky and nice solution for this problem. You should only create an string expression like ';123;434;365;' in-which 123, 434 and 365 are some employeeIDs. By calling the below procedure and passing this expression to it, you can fetch your desired records. Easily you can join the "another table" into this query. This solution is suitable in all versions of SQL server. Also, in comparison with using table variable or temp table, it is very faster and optimized solution.

CREATE PROCEDURE dbo.DoSomethingOnSomeEmployees  @List AS varchar(max)
AS
BEGIN
  SELECT EmployeeID 
  FROM EmployeesTable
  -- inner join AnotherTable on ...
  where @List like '%;'+cast(employeeID as varchar(20))+';%'
END
GO

angularjs to output plain text instead of html

<div ng-bind-html="myText"></div> No need to put into html {{}} interpolation tags like you did {{myText}}.

and don't forget to use ngSanitize in module like e.g. var app = angular.module("myApp", ['ngSanitize']);

and add its cdn dependency in index.html page https://cdnjs.com/libraries/angular-sanitize

Search for value in DataGridView in a column

Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[2].Value.ToString().Equals(searchValue))
            {
                row.Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Has anyone gotten HTML emails working with Twitter Bootstrap?

Hi Brian Armstrong, visit this link.

This blog tells you how to integrate Rails with Bootstrap less (using premailer-rails).

If you're using bootstrap sass, you could do the same:

start by importing some Bootstrap sass files into email.css.scss

@import "bootstrap-sprockets";
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "bootstrap/scaffolding";
@import "bootstrap/type";
@import "bootstrap/buttons";
@import "bootstrap/alerts";
@import 'bootstrap/normalize';
@import 'bootstrap/tables';
@import 'bootstrap/progress-bars';

and then in your view <head> section add <%= stylesheet_link_tag "email" %>

C# Wait until condition is true

You can use an async result and a delegate for this. If you read up on the documentation it should make it pretty clear what to do. I can write up some sample code if you like and attach it to this answer.

Action isExcelInteractive = IsExcelInteractive;

private async void btnOk_Click(object sender, EventArgs e)
{
    IAsyncResult result = isExcelInteractive.BeginInvoke(ItIsDone, null);
    result.AsyncWaitHandle.WaitOne();
    Console.WriteLine("YAY");
} 

static void IsExcelInteractive(){
   while (something_is_false) // do your check here
   {
       if(something_is_true)
          return true;
   }
   Thread.Sleep(1);
}

void ItIsDone(IAsyncResult result)
{
   this.isExcelInteractive.EndInvoke(result);
}

Apologies if this code isn't 100% complete, I don't have Visual Studio on this computer, but hopefully it gets you where you need to get to.

Retrofit 2 - Dynamic URL

I wanted to replace only a part of the url, and with this solution, I don't have to pass the whole url, just the dynamic part:

public interface APIService {

  @GET("users/{user_id}/playlists")
  Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}

MySQL high CPU usage

As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:

On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):

$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

How to position the form in the center screen?

The following example centers a frame on the screen:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

Note that this is actually what the setLocationRelativeTo(null) does:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}

FtpWebRequest Download File

Easiest way

The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Advanced options

Use FtpWebRequest, only if you need a greater control, that WebClient does not offer (like TLS/SSL encryption, progress monitoring, ascii/text transfer mode, resuming transfers, etc). Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

Progress monitoring

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar


Downloading folder

If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

How to install wkhtmltopdf on a linux based (shared hosting) web server

I've managed to successfully install wkhtmltopdf-amd64 on my shared hosting account without root access.

Here's what i did:

Downloaded the relevant static binary v0.10.0 from here: http://code.google.com/p/wkhtmltopdf/downloads/list

EDIT: The above has moved to here

via ssh on my shared host typed the following:

$ wget {relavant url to binary from link above}
$ tar -xvf {filename of above wget'd file}

you'll then have the binary on your host and will be able to run it regardless of if its in the /usr/bin/ folder or not. (or at least i was able to)

To test:

$ ./wkhtmltopdf-amd64 http://www.example.com example.pdf
  • Note remember that if you're in the folder in which the executable is, you should probably preface it with ./ just to be sure.

Worked for me anyway

Passing route control with optional parameter after root in express?

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

app.get('/:key?', function(req, res, next) {
    var key = req.params.key;
    if (!key) {
        next();
        return;
    }
    client.get(key, function(err, reply) {
        if(client.get(reply)) {
            res.redirect(reply);
        }
        else {
            res.render('index', {
                link: null
            });
        }
    });
});

There's no problem in calling next() inside the callback.

According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

Navigation Drawer (Google+ vs. YouTube)

Personally I like the navigationDrawer in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.

If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock and works for pre Honeycomb devices. Check it:

SherlockNavigationDrawer github

How do I define the name of image built with docker-compose

Depending on your use case, you can use an image which has already been created and specify it's name in docker-compose.

We have a production use case where our CI server builds a named Docker image. (docker build -t <specific_image_name> .). Once the named image is specified, our docker-compose always builds off of the specific image. This allows a couple of different possibilities:

1- You can ensure that where ever you run your docker-compose from, you will always be using the latest version of that specific image.

2- You can specify multiple named images in your docker-compose file and let them be auto-wired through the previous build step.

So, if your image is already built, you can name the image with docker-compose. Remove build and specify image:

wildfly:
  image: my_custom_wildfly_image
  container_name: wildfly_server
  ports:
   - 9990:9990
   - 80:8080
  environment:
   - MYSQL_HOST=mysql_server
   - MONGO_HOST=mongo_server
   - ELASTIC_HOST=elasticsearch_server
  volumes:
   - /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
  links:
   - mysql:mysql_server
   - mongo:mongo_server
   - elasticsearch:elasticsearch_server

executing a function in sql plus

As another answer already said, call select myfunc(:y) from dual; , but you might find declaring and setting a variable in sqlplus a little tricky:

sql> var y number

sql> begin
  2  select 7 into :y from dual;
  3  end;
  4  /

PL/SQL procedure successfully completed.

sql> print :y

         Y
----------
         7

sql> select myfunc(:y) from dual;

Retrieve WordPress root directory path?

There are 2 answers for this question Url & directory. Either way, the elegant way would be to define two constants for later use.

define (ROOT_URL, get_site_url() );
define (ROOT_DIR, get_theme_root() );

How to access parameters in a Parameterized Build?

Hope the following piece of code works for you:

def item = hudson.model.Hudson.instance.getItem('MyJob')

def value = item.lastBuild.getEnvironment(null).get('foo')

dynamic_cast and static_cast in C++

There are no classes in C, so it's impossible to to write dynamic_cast in that language. C structures don't have methods (as a result, they don't have virtual methods), so there is nothing "dynamic" in it.

iOS 6 apps - how to deal with iPhone 5 screen size?

You need to add a 640x1136 pixels PNG image ([email protected]) as a 4 inch default splash image of your project, and it will use extra spaces (without efforts on simple table based applications, games will require more efforts).

I've created a small UIDevice category in order to deal with all screen resolutions. You can get it here, but the code is as follows:

File UIDevice+Resolutions.h:

enum {
    UIDeviceResolution_Unknown           = 0,
    UIDeviceResolution_iPhoneStandard    = 1,    // iPhone 1,3,3GS Standard Display  (320x480px)
    UIDeviceResolution_iPhoneRetina4    = 2,    // iPhone 4,4S Retina Display 3.5"  (640x960px)
    UIDeviceResolution_iPhoneRetina5     = 3,    // iPhone 5 Retina Display 4"       (640x1136px)
    UIDeviceResolution_iPadStandard      = 4,    // iPad 1,2,mini Standard Display   (1024x768px)
    UIDeviceResolution_iPadRetina        = 5     // iPad 3 Retina Display            (2048x1536px)
}; typedef NSUInteger UIDeviceResolution;

@interface UIDevice (Resolutions)

- (UIDeviceResolution)resolution;

NSString *NSStringFromResolution(UIDeviceResolution resolution);

@end

File UIDevice+Resolutions.m:

#import "UIDevice+Resolutions.h"

@implementation UIDevice (Resolutions)

- (UIDeviceResolution)resolution
{
    UIDeviceResolution resolution = UIDeviceResolution_Unknown;
    UIScreen *mainScreen = [UIScreen mainScreen];
    CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
    CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if (scale == 2.0f) {
            if (pixelHeight == 960.0f)
                resolution = UIDeviceResolution_iPhoneRetina4;
            else if (pixelHeight == 1136.0f)
                resolution = UIDeviceResolution_iPhoneRetina5;

        } else if (scale == 1.0f && pixelHeight == 480.0f)
            resolution = UIDeviceResolution_iPhoneStandard;

    } else {
        if (scale == 2.0f && pixelHeight == 2048.0f) {
            resolution = UIDeviceResolution_iPadRetina;

        } else if (scale == 1.0f && pixelHeight == 1024.0f) {
            resolution = UIDeviceResolution_iPadStandard;
        }
    }

    return resolution;
 }

 @end

This is how you need to use this code.

1) Add the above UIDevice+Resolutions.h & UIDevice+Resolutions.m files to your project

2) Add the line #import "UIDevice+Resolutions.h" to your ViewController.m

3) Add this code to check what versions of device you are dealing with

int valueDevice = [[UIDevice currentDevice] resolution];

    NSLog(@"valueDevice: %d ...", valueDevice);

    if (valueDevice == 0)
    {
        //unknow device - you got me!
    }
    else if (valueDevice == 1)
    {
        //standard iphone 3GS and lower
    }
    else if (valueDevice == 2)
    {
        //iphone 4 & 4S
    }
    else if (valueDevice == 3)
    {
        //iphone 5
    }
    else if (valueDevice == 4)
    {
        //ipad 2
    }
    else if (valueDevice == 5)
    {
        //ipad 3 - retina display
    }

Why is there no String.Empty in Java?

If you really want a String.EMPTY constant, you can create an utility static final class named "Constants" (for example) in your project. This class will maintain your constants, including the empty String...

In the same idea, you can create ZERO, ONE int constants... that don't exist in the Integer class, but like I commented, it would be a pain to write and to read :

for(int i=Constants.ZERO; ...) {
    if(myArray.length > Constants.ONE) {
        System.out.println("More than one element");
    }
}

Etc.

ant warning: "'includeantruntime' was not set"

The answer from Daniel works just perfect. Here is a sample snippet that I added to my build.xml:

<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">
                                                 <!--   ^^^^^^^^^^^^^^^^^^^^^^^^^  -->
        <classpath>
            <path id="application" location="${jar.dir}/${ant.project.name}.jar"/>
            <path id="junit" location="${lib.dir}/junit-4.9b2.jar"/>
        </classpath>
    </javac>
</target>

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

There are multiple solution for this Lazy Initialisation issue -

1) Change the association Fetch type from LAZY to EAGER but this is not a good practice because this will degrade the performance.

2) Use FetchType.LAZY on associated Object and also use Transactional annotation in your service layer method so that session will remain open and when you will call topicById.getComments(), child object(comments) will get loaded.

3) Also, please try to use DTO object instead of entity in controller layer. In your case, session is closed at controller layer. SO better to convert entity to DTO in service layer.

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

Maximum number of threads in a .NET app?

Mitch is right. It depends on resources (memory).

Although Raymond's article is dedicated to Windows threads, not to C# threads, the logic applies the same (C# threads are mapped to Windows threads).

However, as we are in C#, if we want to be completely precise, we need to distinguish between "started" and "non started" threads. Only started threads actually reserve stack space (as we could expect). Non started threads only allocate the information required by a thread object (you can use reflector if interested in the actual members).

You can actually test it for yourself, compare:

    static void DummyCall()
    {
        Thread.Sleep(1000000000);
    }

    static void Main(string[] args)
    {
        int count = 0;
        var threadList = new List<Thread>();
        try
        {
            while (true)
            {
                Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                newThread.Start();
                threadList.Add(newThread);
                count++;
            }
        }
        catch (Exception ex)
        {
        }
    }

with:

   static void DummyCall()
    {
        Thread.Sleep(1000000000);
    }

    static void Main(string[] args)
    {
        int count = 0;
        var threadList = new List<Thread>();
        try
        {
            while (true)
            {
                Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                threadList.Add(newThread);
                count++;
            }
        }
        catch (Exception ex)
        {
        }
    }

Put a breakpoint in the exception (out of memory, of course) in VS to see the value of counter. There is a very significant difference, of course.

super() in Java

The super keyword can be used to call the superclass constructor and to refer to a member of the superclass

When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.

At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.

public class Box {

    int width;
    int height;
    int depth;

    Box(int w, int h, int d) {
        width = w;
        height = h;
        depth = d;
    }

    public static void main(String[] args){
        HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
    }

}

class HeavyBox extends Box {

    int weight;

    HeavyBox(int w, int h, int d, int m) {

        //call the superclass constructor
        super(w, h, d);
        weight = m;
    }

}

JQuery $.ajax() post - data in a java servlet

You don't want a string, you really want a JS map of key value pairs. E.g., change:

 data: myDataVar.toString(),

with:

var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }



var saveData = $.ajax({
      type: 'POST',
      url: "someaction.do?action=saveData",
      data: myKeyVals,
      dataType: "text",
      success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

UPDATE: Code fixed.

Cannot connect to MySQL 4.1+ using old authentication

you can do these line on your mysql query browser or something

SET old_passwords = 0;
UPDATE mysql.user SET Password = PASSWORD('testpass') WHERE User = 'testuser' limit 1;
SELECT LENGTH(Password) FROM mysql.user WHERE User = 'testuser';
FLUSH PRIVILEGES;

note:your username and password

after that it should able to work. I just solved mine too

"Least Astonishment" and the Mutable Default Argument

Why don't you introspect?

I'm really surprised no one has performed the insightful introspection offered by Python (2 and 3 apply) on callables.

Given a simple little function func defined as:

>>> def func(a = []):
...    a.append(5)

When Python encounters it, the first thing it will do is compile it in order to create a code object for this function. While this compilation step is done, Python evaluates* and then stores the default arguments (an empty list [] here) in the function object itself. As the top answer mentioned: the list a can now be considered a member of the function func.

So, let's do some introspection, a before and after to examine how the list gets expanded inside the function object. I'm using Python 3.x for this, for Python 2 the same applies (use __defaults__ or func_defaults in Python 2; yes, two names for the same thing).

Function Before Execution:

>>> def func(a = []):
...     a.append(5)
...     

After Python executes this definition it will take any default parameters specified (a = [] here) and cram them in the __defaults__ attribute for the function object (relevant section: Callables):

>>> func.__defaults__
([],)

O.k, so an empty list as the single entry in __defaults__, just as expected.

Function After Execution:

Let's now execute this function:

>>> func()

Now, let's see those __defaults__ again:

>>> func.__defaults__
([5],)

Astonished? The value inside the object changes! Consecutive calls to the function will now simply append to that embedded list object:

>>> func(); func(); func()
>>> func.__defaults__
([5, 5, 5, 5],)

So, there you have it, the reason why this 'flaw' happens, is because default arguments are part of the function object. There's nothing weird going on here, it's all just a bit surprising.

The common solution to combat this is to use None as the default and then initialize in the function body:

def func(a = None):
    # or: a = [] if a is None else a
    if a is None:
        a = []

Since the function body is executed anew each time, you always get a fresh new empty list if no argument was passed for a.


To further verify that the list in __defaults__ is the same as that used in the function func you can just change your function to return the id of the list a used inside the function body. Then, compare it to the list in __defaults__ (position [0] in __defaults__) and you'll see how these are indeed refering to the same list instance:

>>> def func(a = []): 
...     a.append(5)
...     return id(a)
>>>
>>> id(func.__defaults__[0]) == func()
True

All with the power of introspection!


* To verify that Python evaluates the default arguments during compilation of the function, try executing the following:

def bar(a=input('Did you just see me without calling the function?')): 
    pass  # use raw_input in Py2

as you'll notice, input() is called before the process of building the function and binding it to the name bar is made.

Printing everything except the first field with awk

If you're open to another Perl solution:

perl -ple 's/^(\S+)\s+(.*)/$2 $1/' file

What's the difference between "Solutions Architect" and "Applications Architect"?

Sounds like the same to me! Though I don't totally disagree with Oli. I'd give a selected few people the Software Architect title if they want it but experience tells me the people who would actually deserve the title of Software Architect usually aint that in to titles.

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

Best way to remove from NSMutableArray while iterating?

Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.

new Runnable() but no new thread?

If you want to create a new Thread...you can do something like this...

Thread t = new Thread(new Runnable() { public void run() { 
  // your code goes here... 
}});

how can I enable PHP Extension intl?

You can find the answer here: http://www.dorusomcutean.com/how-to-install-php-7-2-on-windows/

In that blog post, I'm showing how to install PHP on Windows and how to enable extensions. Hope that it helps anyone who encounters this problem again.

How to position a DIV in a specific coordinates?

You can also use position fixed css property.

<!-- html code --> 
<div class="box" id="myElement"></div>

/* css code */
.box {
    position: fixed;
}

// js code

document.getElementById('myElement').style.top = 0; //or whatever 
document.getElementById('myElement').style.left = 0; // or whatever

How to Select Every Row Where Column Value is NOT Distinct

Just for fun, here's another way:

;with counts as (
    select CustomerName, EmailAddress,
      count(*) over (partition by EmailAddress) as num
    from Customers
)
select CustomerName, EmailAddress
from counts
where num > 1

SQL SELECT multi-columns INTO multi-variable

SELECT @variable1 = col1, @variable2 = col2
FROM table1

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

Why I get 'list' object has no attribute 'items'?

More generic way in case qs has more than one dictionaries:

[int(v) for lst in qs for k, v in lst.items()]

--

>>> qs = [{u'a': 15L, u'b': 9L, u'a': 16L}, {u'a': 20, u'b': 35}]
>>> result_list = [int(v) for lst in qs for k, v in lst.items()]
>>> result_list
[16, 9, 20, 35]