Programs & Examples On #Couchapp

CouchApps are JavaScript and HTML5 applications served directly from CouchDB.

What is the simplest way to swap each pair of adjoining chars in a string with Python?

The usual way to swap two items in Python is:

a, b = b, a

So it would seem to me that you would just do the same with an extended slice. However, it is slightly complicated because strings aren't mutable; so you have to convert to a list and then back to a string.
Therefore, I would do the following:

>>> s = 'badcfe'
>>> t = list(s)
>>> t[::2], t[1::2] = t[1::2], t[::2]
>>> ''.join(t)
'abcdef'

Django - what is the difference between render(), render_to_response() and direct_to_template()?

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

render() is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext that I will most definitely be using from now on.


2020 EDIT: It should be noted that render_to_response() was removed in Django 3.0

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response

render_to_response(template[, dictionary][, context_instance][, mimetype])¶

render_to_response is your standard render function used in the tutorials and such. To use RequestContext you'd have to specify context_instance=RequestContext(request)


https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template

direct_to_template is a generic view that I use in my views (as opposed to in my urls) because like the new render() function, it automatically uses RequestContext and all its context_processors.

But direct_to_template should be avoided as function based generic views are deprecated. Either use render or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/

I'm happy I haven't typed RequestContext in a long, long time.

cut or awk command to print first field of first row

Specify NR if you want to capture output from selected rows:

awk 'NR==1{print $1}' /etc/*release

An alternative (ugly) way of achieving the same would be:

awk '{print $1; exit}'

An efficient way of getting the first string from a specific line, say line 42, in the output would be:

awk 'NR==42{print $1; exit}'

how to set image from url for imageView

You can use either Picasso or Glide.

Picasso.with(context)
   .load(your_url)
   .into(imageView);


Glide.with(context)
   .load(your_url)
   .into(imageView);

How to return multiple values?

You can do something like this:

public class Example
{
    public String name;
    public String location;

    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once
    }
}

CSS customized scroll bar in div

I think you have to use ::-wekbit-scrollbar for all the scrollbars, and you can use:

<style>
.mydiv {
height:100px;
overflow:auto;
}
     /* width */
    .mydiv::-webkit-scrollbar {
      width: 20px;
    }
    
    /* Track */
    .mydiv::-webkit-scrollbar-track {
      box-shadow: inset 0 0 5px grey; 
      border-radius: 10px;
    }
     
    /* Handle */
    .mydiv::-webkit-scrollbar-thumb {
      background: red;
      border-radius: 10px;
    }
    
    /* Handle on hover */
    .mydiv::-webkit-scrollbar-thumb:hover {
      background: #b30000; 
    }
</style>
<body>
<div class="mydiv"> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> </div>
</body>

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:

SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
    ON pe.grantee_principal_id = pr.principal_id;

Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.

jquery <a> tag click event

That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid and grab them via:

var uids = $(".uid").map(function() {
    return this.value;
}).get();

Demo: http://jsfiddle.net/karim79/FtcnJ/

EDIT: say your output looks like the following (notice, IDs have changed to classes)

<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>

You can target the 'uid' relative to the clicked anchor like this:

$("a.aaf").click(function() {
    alert($(this).next('.uid').val());
});

Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.

Sending websocket ping/pong frame from browser

Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.

Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.

What is the use of the init() usage in JavaScript?

JavaScript doesn't have a built-in init() function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init() function for initialisation stuff.

A particular init() function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.

What any given init() does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.

function init() {
  // initialisation stuff here
}

// elsewhere in code
init();

How to disable an Android button?

With Kotlin you can do,

// to disable clicks
myButton.isClickable = false 

// to disable button
myButton.isEnabled = false

// to enable clicks
myButton.isClickable = true 

// to enable button
myButton.isEnabled = true

JOptionPane Yes or No window

You are writing if(true) so it will always show "Hello " message.

You should take decision on the basis of value of n returned.

How to encode URL parameters?

Using new ES6 Object.entries(), it makes for a fun little nested map/join:

_x000D_
_x000D_
const encodeGetParams = p => _x000D_
  Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");_x000D_
_x000D_
const params = {_x000D_
  user: "María Rodríguez",_x000D_
  awesome: true,_x000D_
  awesomeness: 64,_x000D_
  "ZOMG+&=*(": "*^%*GMOZ"_x000D_
};_x000D_
_x000D_
console.log("https://example.com/endpoint?" + encodeGetParams(params))
_x000D_
_x000D_
_x000D_

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For me this setting was working.
In my windows 8.1 the path for php7 is

C:\user\test\tools\php7\php.exe

settings.json

 {  
 "php.executablePath":"/user/test/tools/php7/php.exe",
 "php.validate.executablePath": "/user/test/tools/php7/php.exe"
 }

see also https://github.com/microsoft/vscode/issues/533

Proper way to rename solution (and directories) in Visual Studio

Using the "Find in Files" function of Notepad++ worked fine for me (ctrl + H, Find in Files).

http://notepad-plus-plus.org/download/v6.2.2.html

How to use UIVisualEffectView to Blur Image?

If anyone would like the answer in Swift :

var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.

var blurView = UIVisualEffectView(effect: blurEffect)

blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!

Update :

As of now, it's available under the IB so you don't have to code anything for it :)

SQL DELETE with JOIN another table for WHERE condition

I think, from your description, the following would suffice:

DELETE FROM guide_category 
WHERE id_guide NOT IN (SELECT id_guide FROM guide)

I assume, that there are no referential integrity constraints on the tables involved, are there?

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

How to use multiple databases in Laravel

In Laravel 5.1, you specify the connection:

$users = DB::connection('foo')->select(...);

Default, Laravel uses the default connection. It is simple, isn't it?

Read more here: http://laravel.com/docs/5.1/database#accessing-connections

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

Overriding css style?

Instead of override you can add another class to the element and then you have an extra abilities. for example:

HTML

<div class="style1 style2"></div>

CSS

//only style for the first stylesheet
.style1 {
   width: 100%;      
}
//only style for second stylesheet
.style2 {
   width: 50%;     
}
//override all
.style1.style2 { 
   width: 70%;
}

How can I check the extension of a file?

Some of the answers above don't account for folder names with periods. (folder.mp3 is a valid folder name). You should make sure the "file" isn't actually a folder before checking the extension.


Checking the extension of a file:

import os

file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
    file_extension = os.path.splitext(file_path)[1]
    if file_extension.lower() == ".mp3":
        print("It's an mp3")
    if file_extension.lower() == ".flac":
        print("It's a flac")

Output:

It's an mp3

Checking the extension of all files in a folder:

import os

directory = "C:/folder"
for file in os.listdir(directory):
    file_path = os.path.join(directory, file)
    if os.path.isfile(file_path):
        file_extension = os.path.splitext(file_path)[1]
        print(file, "ends in", file_extension)

Output:

abc.txt ends in .txt
file.mp3 ends in .mp3
song.flac ends in .flac

Comparing file extension against multiple types:

import os

file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
    file_extension = os.path.splitext(file_path)[1]
    if file_extension.lower() in {'.mp3', '.flac', '.ogg'}:
        print("It's a music file")
    elif file_extension.lower() in {'.jpg', '.jpeg', '.png'}:
        print("It's an image file")

Output:

It's a music file

How can I determine the status of a job?

-- Microsoft SQL Server 2008 Standard Edition:
IF EXISTS(SELECT 1 
          FROM msdb.dbo.sysjobs J 
          JOIN msdb.dbo.sysjobactivity A 
              ON A.job_id=J.job_id 
          WHERE J.name=N'Your Job Name' 
          AND A.run_requested_date IS NOT NULL 
          AND A.stop_execution_date IS NULL
         )
    PRINT 'The job is running!'
ELSE
    PRINT 'The job is not running.'

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Here are two other solutions

When a module is not yours - try to install types from @types:

npm install -D @types/module-name

If the above install errors - try changing import statements to require:

// import * as yourModuleName from 'module-name';
const yourModuleName = require('module-name');

Getting the base url of the website and globally passing it to twig in Symfony 2

In one situation involving a multi-domain application, app.request.getHttpHost helped me out. It returns something like example.com or subdomain.example.com (or example.com:8000 when the port is not standard). This was in Symfony 3.4.

How to set a ripple effect on textview or imageview on Android?

for circle ripple : android:background="?attr/selectableItemBackgroundBorderless"

for rectangle ripple : android:background="?attr/selectableItemBackground"

How to secure phpMyAdmin

Most likely, somewhere on your webserver will be an Alias directive like this;

Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"

In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.

Just change the alias directive and you should be good to go.

Getting HTML elements by their attribute names

Yes, the function is querySelectorAll (or querySelector for a single element), which allows you to use CSS selectors to find elements.

document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.

(Complete list of attribute selectors on MDN.)

This finds all elements with the attribute property. It would be better to specify a tag name if possible:

document.querySelectorAll('span[property]');

You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:

var withProperty = [],
    els = document.getElementsByTagName('span'), // or '*' for all types of element
    i = 0;

for (i = 0; i < els.length; i++) {
    if (els[i].hasAttribute('property')) {
        withProperty.push(els[i]);
    }
}

Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.

For anyone dealing with ancient browsers, note that querySelectorAll was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.

How to list all databases in the mongo shell?

For database list:

show databases
show dbs

For table/collection list:

show collections
show tables
db.getCollectionNames()

'tuple' object does not support item assignment

The second line should have been pixels[0], with an S. You probably have a tuple named pixel, and tuples are immutable. Construct new pixels instead:

image = Image.open('balloon.jpg')

pixels = [(pix[0] + 20,) + pix[1:] for pix in image.getdata()]

image.putdate(pixels)

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

How to configure PostgreSQL to accept all incoming connections

0.0.0.0/0 for all IPv4 addresses

::0/0 for all IPv6 addresses

all to match any IP address

samehost to match any of the server's own IP addresses

samenet to match any address in any subnet that the server is directly connected to.

e.g.

host    all             all             0.0.0.0/0            md5

Error Code: 1005. Can't create table '...' (errno: 150)

Error Code: 1005

I had a similar issue, so here are few things that I did try (not in any order, except for the solution :) )

  1. Changed the foreign key names (it didn't work)
  2. Reduced the foreign key length
  3. Verified the datatypes (darn nothing wrong)
  4. Check indexes
  5. Check the collations (everything fine, darn again)
  6. Truncated the table, of no good use
  7. Dropped the table and re-created
  8. Tried to see if any circular reference is being created --- all fine
  9. Finally, I saw that I had two editors open. One that in PhpStorm (JetBrains) and the other MySQL workbench. It seems that the PhpStorm / MySQL Workbench creates some kind of edit lock.

    I closed PhpStorm just to check if locking was the case (it could have been the other way around). This solved my problem.

Get unique values from arraylist in java

If you have an array of a some kind of object (bean) you can do this:

List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);

like said Mathias Schwarz above, but you have to provide your aBean with the methods hashCode() and equals(Object obj) that can be done easily in Eclipse by dedicated menu 'Generate hashCode() and equals()' (while in the bean Class). Set will evaluate the overridden methods to discriminate equals objects.

Hard reset of a single file

Reference to HEAD is not necessary.

git checkout -- file.js is sufficient

How can you tell when a layout has been drawn?

When onMeasure is called the view gets its measured width/height. After this, you can call layout.getMeasuredHeight().

AddRange to a Collection

Or you can just make an ICollection extension like this:

 public static ICollection<T> AddRange<T>(this ICollection<T> @this, IEnumerable<T> items)
    {
        foreach(var item in items)
        {
            @this.Add(item);
        }

        return @this;
    }

Using it would be just like using it on a list:

collectionA.AddRange(IEnumerable<object> items);

Javascript how to parse JSON array

Something more to the point for me..

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';  
var contact = JSON.parse(jsontext);  
document.write(contact.surname + ", " + contact.firstname);  
document.write(contact.phone[1]);  
// Output:  
// Aaberg, Jesper  
// 555-0100

Reference: https://docs.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript

Uncaught TypeError: data.push is not a function

I think you set it as

var data = []; 

but after some time you made it like:

data = 'some thing which is not an array'; 

then data.push('') will not work as it is not an array anymore.

Python: import module from another directory at the same level in project hierarchy

I faced the same issues. To solve this, I used export PYTHONPATH="$PWD". However, in this case, you will need to modify imports in your Scripts dir depending on the below:

Case 1: If you are in the user_management dir, your scripts should use this style from Modules import LDAPManager to import module.

Case 2: If you are out of the user_management 1 level like main, your scripts should use this style from user_management.Modules import LDAPManager to import modules.

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

You can make use of java.util.Date instead of Timestamp :

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

Installing and Running MongoDB on OSX

Updated answer (9/2/2019):

Homebrew has removed mongodb formula from its core repository, see this pull request.

The new way to install mongodb using Homebrew is as follows:

~> brew tap mongodb/brew
~> brew install mongodb-community

After installation you can start the mongodb service by following the caveats:

~> brew info mongodb-community
mongodb/brew/mongodb-community: stable 4.2.0
High-performance, schema-free, document-oriented database
https://www.mongodb.com/
Not installed
From: https://github.com/mongodb/homebrew-brew/blob/master/Formula/mongodb-community.rb
==> Caveats
To have launchd start mongodb/brew/mongodb-community now and restart at login:
  brew services start mongodb/brew/mongodb-community
Or, if you don't want/need a background service you can just run:
  mongod --config /usr/local/etc/mongod.conf

Deprecated answer (8/27/2019):

I assume you are using Homebrew. You can see the additional information that you need using brew info $FORMULA

~> brew info mongo                                                           255
mongodb: stable 2.4.6, devel 2.5.1
http://www.mongodb.org/
/usr/local/Cellar/mongodb/2.4.5-x86_64 (20 files, 287M) *
  Built from source
From: https://github.com/mxcl/homebrew/commits/master/Library/Formula/mongodb.rb
==> Caveats
To reload mongodb after an upgrade:
    launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist

Caveats is what you need to follow after installation.

Get Android API level of phone currently running my application

try this :Float.valueOf(android.os.Build.VERSION.RELEASE) <= 2.1

HTML <select> selected option background-color CSS style

This syntax will work in XHTML and does not work in IE6, but this is a non-javascript way:

option[selected] { background: #f00; }

If you want to do this on-the-fly, then you would have to go with javascript, the way others have suggested....

Why do people say that Ruby is slow?

Ruby is slower than C++ at a number of easily measurable tasks (e.g., doing code that is heavily dependent on floating point). This is not very surprising, but enough justification for some people to say that “Ruby is Slow” without qualification. They don't count the fact that it is far easier and safer to write Ruby code than C++.

The best fix is to use targeted modules written in another language (e.g., C, C++, Fortran) in your Ruby code. Those can do the heavy lifting and your scripts can focus on higher level coordination issues.

App installation failed due to application-identifier entitlement

This is solved easily by removing you previous app from your device. And start to reinstall again. This works fine for me.

UnicodeEncodeError: 'latin-1' codec can't encode character

You are trying to store a Unicode codepoint \u201c using an encoding ISO-8859-1 / Latin-1 that can't describe that codepoint. Either you might need to alter the database to use utf-8, and store the string data using an appropriate encoding, or you might want to sanitise your inputs prior to storing the content; i.e. using something like Sam Ruby's excellent i18n guide. That talks about the issues that windows-1252 can cause, and suggests how to process it, plus links to sample code!

TypeError: can't use a string pattern on a bytes-like object in re.findall()

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

See Convert bytes to a Python String

What are some good Python ORM solutions?

We use Elixir alongside SQLAlchemy and have liked it so far. Elixir puts a layer on top of SQLAlchemy that makes it look more like the "ActiveRecord pattern" counter parts.

Linux command (like cat) to read a specified quantity of characters

Here's a simple script that wraps up using the dd approach mentioned here:

extract_chars.sh

#!/usr/bin/env bash

function show_help()
{
  IT="
extracts characters X to Y from stdin or FILE
usage: X Y {FILE}

e.g. 

2 10 /tmp/it     => extract chars 2-10 from /tmp/it
EOF
  "
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

FROM=$1
TO=$2
COUNT=`expr $TO - $FROM + 1`

if [ -z "$3" ]
then
  dd skip=$FROM count=$COUNT bs=1 2>/dev/null
else
  dd skip=$FROM count=$COUNT bs=1 if=$3 2>/dev/null 
fi

Excel formula to get cell color

No, you can only get to the interior color of a cell by using a Macro. I am afraid. It's really easy to do (cell.interior.color) so unless you have a requirement that restricts you from using VBA, I say go for it.

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.

But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:

{ Id: 1, 
name:'john', 
phones:[{title:'home',number:111111,...},
        {title:'office',number:22222,...}]
}

sends

{ Id: 1, 
name:'john', 
phones:[object object]
phones:[object object]
}

Container is running beyond memory limits

While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:

aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json

Where myConfig.json should say:

[
  {
    "Classification": "spark",
    "Properties": {
      "maximizeResourceAllocation": "true"
    }
  }
]

Scroll to the top of the page after render in react.js

If all want to do is something simple here is a solution that will work for everybody

add this mini function

scrollTop()
{
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    });
}

call the function as following from the footer of the page

<a className="scroll-to-top rounded" style={{display: "inline"}} onClick={this.scrollTop}>TOP</a>

if you want to add nice styles here is the css

_x000D_
_x000D_
.scroll-to-top {_x000D_
  position: fixed;_x000D_
  right: 1rem;_x000D_
  bottom: 1rem;_x000D_
  display: none;_x000D_
  width: 2.75rem;_x000D_
  height: 2.75rem;_x000D_
  text-align: center;_x000D_
  color: #fff;_x000D_
  background: rgba(90, 92, 105, 0.5);_x000D_
  line-height: 46px;_x000D_
}
_x000D_
_x000D_
_x000D_

MongoDB not equal to

If you want to do multiple $ne then do

db.users.find({name : {$nin : ["mary", "dick", "jane"]}})

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

for win xp

Steps

  1. [windows key] + R, type services.msc, search for the running instance of "Windows Presentation Foundation (WPF) Font Cache". For my case its 4.0. Stop the service.
  2. [windows key] + R, type C:\Documents and Settings\LocalService\Local Settings\Application Data\, delete all font cache files.
  3. Start the "Windows Presentation Foundation (WPF) Font Cache" service.

How should I load files into my Java application?

What are you loading the files for - configuration or data (like an input file) or as a resource?

  • If as a resource, follow the suggestion and example given by Will and Justin
  • If configuration, then you can use a ResourceBundle or Spring (if your configuration is more complex).
  • If you need to read a file in order to process the data inside, this code snippet may help BufferedReader file = new BufferedReader(new FileReader(filename)) and then read each line of the file using file.readLine(); Don't forget to close the file.

Laravel 5 – Clear Cache in Shared Hosting Server

Used this page a few times to copy and paste quick commands into composer, so I wrote a command that does these commands in one single artisan command.

namespace App\Console\Commands\Admin;

use Illuminate\Console\Command;

class ClearEverything extends Command
{

    protected $signature = 'traqza:clear-everything';

    protected $description = 'Clears routes, config, cache, views, compiled, and caches config.';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $validCommands = array('route:clear', 'config:clear', 'cache:clear', 'view:clear', 'clear-compiled', 'config:cache');
        foreach ($validCommands as $cmd) {
            $this->call('' . $cmd . '');

        }
    }
}

Place in app\Console\Commands\Admin folder

then run command in composer php artisan traqza:clear-everything

Happy coding.

Github -> https://github.com/Traqza/clear-everything

Compile to stand alone exe for C# app in Visual Studio 2010

You just compile it. In the bin\Release (or bin\Debug) folder, the .exe will be in there.

If you're asking how to make an executable which does not rely on the .NET framework at all, then that's a lot harder and you'll need to purchase something like RemoteSoft's Salamader. In general, it's not really worth the bother: Windows Vista comes with .NET framework 2.0 pre-installed already so if you're worried about that, you can just target the 2.0 framework (then only XP users would have to install the framework).

How to include a Font Awesome icon in React's render()

as 'Praveen M P' said you can install font-awesome as a package. if you have yarn you can run:

 yarn add font-awesome

If you don't have yarn do as Praveen said and do:

npm install --save font-awesome

this will add the package to your projects dependencies and install the package in your node_modules folder. in your App.js file add

import 'font-awesome/css/font-awesome.min.css'

What is deserialize and serialize in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.

Say, you have an object:

{foo: [1, 4, 7, 10], bar: "baz"}

serializing into JSON will convert it into a string:

'{"foo":[1,4,7,10],"bar":"baz"}'

which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}.

How to hide Bootstrap modal with javascript?

What we found was that there was just a slight delay between the call to our server code and the return to the success call back. If we wrapped the call to the server in the $("#myModal").on('hidden.bs.modal', function (e) handler and then called the $("#myModal").modal("hide"); method, the browser would hide the modal and then invoke the server side code.

Again, not elegant but functional.

 function myFunc(){
        $("#myModal").on('hidden.bs.modal', function (e) {
            // Invoke your server side code here.
        });
        $("#myModal").modal("hide");
 };

As you can see, when myFunc is invoked, it will hide the modal and then invoke the server side code.

How to call servlet through a JSP page

there isn't method to call Servlet. You should make mapping in web.xml and then trigger this mapping.

Example: web.xml:

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>test.HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

This mapping means that every call to http://yoursite/yourwebapp/hello trigger this servlet For example this jsp:

<jsp:forward page="/hello"/> 

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.

Unable to open project... cannot be opened because the project file cannot be parsed

Goto PhoneGapTest>>platform Then delete the folder ios after that go to terminal then type: sudo phonegap build ios after that you can run the project

ALTER TABLE, set null in not null column, PostgreSQL 9.1

Execute the command in this format:

ALTER [ COLUMN ] column { SET | DROP } NOT NULL

How do I enable --enable-soap in php on linux?

In case that you have Ubuntu in your machine, the following steps will help you:

  1. Check first in your php testing file if you have soap (client / server)or not by using phpinfo(); and check results in the browser. In case that you have it, it will seems like the following image ( If not go to step 2 ):

enter image description here

  1. Open your terminal and paste: sudo apt-get install php-soap.

  2. Restart your apache2 server in terminal : service apache2 restart.

  3. To check use your php test file again to be seems like mine in step 1.

How can I overwrite file contents with new content in PHP?

Use file_put_contents()

file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo

Alternatively, if you're stuck with fopen() you can use the w or w+ modes:

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Just ran into this problem myself. OSx Lion hides scrollbars while not in use to make it seem more "slick", but at the same time the issue you addressed comes up: people sometimes cannot see whether a div has a scroll feature or not.

The fix: In your css include -

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 7px;
}

::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: rgba(0, 0, 0, .5);
  box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}

_x000D_
_x000D_
/* always show scrollbars */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
  -webkit-appearance: none;_x000D_
  width: 7px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
  border-radius: 4px;_x000D_
  background-color: rgba(0, 0, 0, .5);_x000D_
  box-shadow: 0 0 1px rgba(255, 255, 255, .5);_x000D_
}_x000D_
_x000D_
_x000D_
/* css for demo */_x000D_
_x000D_
#container {_x000D_
  height: 4em;_x000D_
  /* shorter than the child */_x000D_
  overflow-y: scroll;_x000D_
  /* clip height to 4em and scroll to show the rest */_x000D_
}_x000D_
_x000D_
#child {_x000D_
  height: 12em;_x000D_
  /* taller than the parent to force scrolling */_x000D_
}_x000D_
_x000D_
_x000D_
/* === ignore stuff below, it's just to help with the visual. === */_x000D_
_x000D_
#container {_x000D_
  background-color: #ffc;_x000D_
}_x000D_
_x000D_
#child {_x000D_
  margin: 30px;_x000D_
  background-color: #eee;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="child">Example</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

customize the apperance as needed. Source

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

HTTP POST Returns Error: 417 "Expectation Failed."

For Powershell it is

[System.Net.ServicePointManager]::Expect100Continue = $false

Java - Writing strings to a CSV file

I see you already have a answer but here is another answer, maybe even faster A simple class to pass in a List of objects and retrieve either a csv or excel or password protected zip csv or excel. https://github.com/ernst223/spread-sheet-exporter

SpreadSheetExporter spreadSheetExporter = new SpreadSheetExporter(List<Object>, "Filename");
File fileCSV = spreadSheetExporter.getCSV();

How to remove unique key from mysql table

First you need to know the exact name of the INDEX (Unique key in this case) to delete or update it.
INDEX names are usually same as column names. In case of more than one INDEX applied on a column, MySQL automatically suffixes numbering to the column names to create unique INDEX names.

For example if 2 indexes are applied on a column named customer_id

  1. The first index will be named as customer_id itself.
  2. The second index will be names as customer_id_2 and so on.

To know the name of the index you want to delete or update

SHOW INDEX FROM <table_name>

as suggested by @Amr

To delete an index

ALTER TABLE <table_name> DROP INDEX <index_name>;

The property 'Id' is part of the object's key information and cannot be modified

Just hoping this helps someone else, after struggling for hours with this because i knew i wasnt updating the PK and i definitely had a PK. I had the PK value databound to a menu bar to show the current PK value and this was causing the issue.

How to scanf only integer and repeat reading if the user enters non-numeric characters?

char check1[10], check2[10];
int foo;

do{
  printf(">> ");
  scanf(" %s", check1);
  foo = strtol(check1, NULL, 10); // convert the string to decimal number
  sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number

If the input is number, you can use foo as your input.

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

Image vs Bitmap class

The Bitmap class is an implementation of the Image class. The Image class is an abstract class;

The Bitmap class contains 12 constructors that construct the Bitmap object from different parameters. It can construct the Bitmap from another bitmap, and the string address of the image.

See more in this comprehensive sample.

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

ieshims.dll is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.

I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.

What is the idiomatic Go equivalent of C's ternary operator?

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2
}

However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.

I used an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()

This ensures that both branches are not evaluated as well.

How to move Jenkins from one PC to another

This worked for me to move from Ubuntu 12.04 (Jenkins ver. 1.628) to Ubuntu 16.04 (Jenkins ver. 1.651.2). I first installed Jenkins from the repositories.

  1. Stop both Jenkins servers
  2. Copy JENKINS_HOME (e.g. /var/lib/jenkins) from the old server to the new one. From a console in the new server:

    rsync -av username@old-server-IP:/var/lib/jenkins/ /var/lib/jenkins/

  3. Start your new Jenkins server

You might not need this, but I had to

  • Manage Jenkins and Reload Configuration from Disk.
  • Disconnect and connect all the slaves again.
  • Check that in the Configure System > Jenkins Location, the Jenkins URL is correctly assigned to the new Jenkins server.

Is there an easy way to reload css without reloading the page?

Possibly not applicable for your situation, but here's the jQuery function I use for reloading external stylesheets:

/**
 * Forces a reload of all stylesheets by appending a unique query string
 * to each stylesheet URL.
 */
function reloadStylesheets() {
    var queryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        this.href = this.href.replace(/\?.*|$/, queryString);
    });
}

How to run Java program in command prompt

You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

Contain form within a bootstrap popover?

like this Working demo http://jsfiddle.net/7e2XU/21/show/# * Update: http://jsfiddle.net/kz5kjmbt/

 <div class="container">
    <div class="row" style="padding-top: 240px;"> <a href="#" class="btn btn-large btn-primary" rel="popover" data-content='
<form id="mainForm" name="mainForm" method="post" action="">
    <p>
        <label>Name :</label>
        <input type="text" id="txtName" name="txtName" />
    </p>
    <p>
        <label>Address 1 :</label>
        <input type="text" id="txtAddress" name="txtAddress" />
    </p>
    <p>
        <label>City :</label>
        <input type="text" id="txtCity" name="txtCity" />
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit" />
    </p>
</form>
 data-placement="top" data-original-title="Fill in form">Open form</a>

    </div>
</div>

JavaScript code:

    $('a[rel=popover]').popover({
      html: 'true',
      placement: 'right'
    })

ScreenShot

working updated fiddle screenshot

Sound alarm when code finishes

On Windows

import winsound
duration = 1000  # milliseconds
freq = 440  # Hz
winsound.Beep(freq, duration)

Where freq is the frequency in Hz and the duration is in milliseconds.

On Linux and Mac

import os
duration = 1  # seconds
freq = 440  # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))

In order to use this example, you must install sox.

On Debian / Ubuntu / Linux Mint, run this in your terminal:

sudo apt install sox

On Mac, run this in your terminal (using macports):

sudo port install sox

Speech on Mac

import os
os.system('say "your program has finished"')

Speech on Linux

import os
os.system('spd-say "your program has finished"')

You need to install the speech-dispatcher package in Ubuntu (or the corresponding package on other distributions):

sudo apt install speech-dispatcher

How can I get the Google cache age of any URL or web page?

its too simple, you can just type "cache:" before the URL of the page. for example if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page

this will show you the last webcache of the page.see here:

enter image description here

But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.

How to run Rake tasks from within Rake tasks?

task :build_all do
  [ :debug, :release ].each do |t|
    $build_type = t
    Rake::Task["build"].execute
  end
end

How to set alignment center in TextBox in ASP.NET?

Add the css styling text-align: center to the control.

Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:

<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

How to do a scatter plot with empty circles in Python?

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

example image

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

example image

What are some good SSH Servers for windows?

VanDyke VShell is the best Windows SSH Server I've ever worked with. It is kind of expensive though ($250). If you want a free solution, freeSSHd works okay. The CYGWIN solution is always an option, I've found, however, that it is a lot of work & overhead just to get SSH.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Xcode 12.3

I solved this problem by setting Validate Workspace to Yes

enter image description here

Creating dummy variables in pandas for python

For my case, dmatrices in patsy solved my problem. Actually, this function is designed for the generation of dependent and independent variables from a given DataFrame with an R-style formula string. But it can be used for the generation of dummy features from the categorical features. All you need to do would be drop the column 'Intercept' that is generated by dmatrices automatically regardless of your original DataFrame.

import pandas as pd
from patsy import dmatrices

df_original = pd.DataFrame({
   'A': ['red', 'green', 'red', 'green'],
   'B': ['car', 'car', 'truck', 'truck'],
   'C': [10,11,12,13],
   'D': ['alice', 'bob', 'charlie', 'alice']},
   index=[0, 1, 2, 3])

_, df_dummyfied = dmatrices('A ~ A + B + C + D', data=df_original, return_type='dataframe')
df_dummyfied = df_dummyfied.drop('Intercept', axis=1)

df_dummyfied.columns    
Index([u'A[T.red]', u'B[T.truck]', u'D[T.bob]', u'D[T.charlie]', u'C'], dtype='object')

df_dummyfied
   A[T.red]  B[T.truck]  D[T.bob]  D[T.charlie]     C
0       1.0         0.0       0.0           0.0  10.0
1       0.0         0.0       1.0           0.0  11.0
2       1.0         1.0       0.0           1.0  12.0
3       0.0         1.0       0.0           0.0  13.0

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

Can someone post a well formed crossdomain.xml sample?

This is what I've been using for development:

<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

This is a very liberal approach, but is fine for my application.

As others have pointed out below, beware the risks of this.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

RESTful URL design for search

Although having the parameters in the path has some advantages, there are, IMO, some outweighing factors.

  • Not all characters needed for a search query are permitted in a URL. Most punctuation and Unicode characters would need to be URL encoded as a query string parameter. I'm wrestling with the same problem. I would like to use XPath in the URL, but not all XPath syntax is compatible with a URI path. So for simple paths, /cars/doors/driver/lock/combination would be appropriate to locate the 'combination' element in the driver's door XML document. But /car/doors[id='driver' and lock/combination='1234'] is not so friendly.

  • There is a difference between filtering a resource based on one of its attributes and specifying a resource.

    For example, since

    /cars/colors returns a list of all colors for all cars (the resource returned is a collection of color objects)

    /cars/colors/red,blue,green would return a list of color objects that are red, blue or green, not a collection of cars.

    To return cars, the path would be

    /cars?color=red,blue,green or /cars/search?color=red,blue,green

  • Parameters in the path are more difficult to read because name/value pairs are not isolated from the rest of the path, which is not name/value pairs.

One last comment. I prefer /garages/yyy/cars (always plural) to /garage/yyy/cars (perhaps it was a typo in the original answer) because it avoids changing the path between singular and plural. For words with an added 's', the change is not so bad, but changing /person/yyy/friends to /people/yyy seems cumbersome.

How to generate .angular-cli.json file in Angular Cli?

As far as I know Angular-cli file can't be created via a command like Package-lock file, If you want to create it, you have to do it manually.

  1. You can type ng new to create a new angular project

  2. Locate its .angular-cli.json file

  3. Copy all its content

  4. Create a folder in your original project, and name it .angular-cli.json

  5. Paste what copied from new project in newly created angular cli file of original project.

  6. Locate this line in angular cli file you created, and change the name field to original project's name. You can find the project name in package.json file

project": {
  "name": "<name of the project>"
},

However, in newer angular version now it uses angular.json instead of angular-cli.json.

How to increase the vertical split window size in Vim

CTRL-W >

and

CTRL-W <

to make the window wider or narrower.

Object creation on the stack/heap?

C++ has Automatic variables - not Stack variables.

Automatic variable means that C++ compiler handles memory allocation / free by itself. C++ can automatically handle objects of any class - no matter whether it has dynamically allocated members or not. It's achieved by strong guarantee of C++ that object's destructor will be called automatically when execution is going out of scope where automatic variable was declared. Inside of a C++ object can be a lot of dynamic allocations with new in constructor, and when such an object is declared as an automatic variable - all dynamic allocations will be performed, and freed then in destructor.

Stack variables in C can't be dynamically allocated. Stack in C can store pointers, or fixed arrays or structs - all of fixed size, and these things are being allocated in memory in linear order. When a C program frees a stack variable - it just moves stack pointer back and nothing more.

Even though C++ programs can use Stack memory segment for storing primitive types, function's args, or other, - it's all decided by C++ compiler, not by program developer. Thus, it is conceptually wrong to equal C++ automatic variables and C stack variables.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

I just had this problem now and solved it.

Although you installed mysql-server, the daemon needs to be running in order for the client to connect to it.

First check to see if mysql server is running:

netstat -tap | grep mysql

You should see something like this:

$ sudo netstat -tap | grep mysql
tcp        0      0 localhost:mysql         *:*          LISTEN     6639/mysqld     

If you don't have the server running, start the daemon by the following command:

/etc/init.d/mysql restart

This should solve your problem if it's installed.

Jenkins/Hudson - accessing the current build number?

Jenkins Pipeline also provides the current build number as the property number of the currentBuild. It can be read as currentBuild.number.

For example:

// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"

Other properties of currentBuild are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.

List of phone number country codes

Here is a JS function that converts "Country Code" (ISO3) to Telephone "Calling Code":

function country_iso3_to_country_calling_code(country_iso3) {
        if(country_iso3 == 'AFG') return '93';
        if(country_iso3 == 'ALB') return '355';
        if(country_iso3 == 'DZA') return '213';
        if(country_iso3 == 'ASM') return '1684';
        if(country_iso3 == 'AND') return '376';
        if(country_iso3 == 'AGO') return '244';
        if(country_iso3 == 'AIA') return '1264';
        if(country_iso3 == 'ATA') return '672';
        if(country_iso3 == 'ATG') return '1268';
        if(country_iso3 == 'ARG') return '54';
        if(country_iso3 == 'ARM') return '374';
        if(country_iso3 == 'ABW') return '297';
        if(country_iso3 == 'AUS') return '61';
        if(country_iso3 == 'AUT') return '43';
        if(country_iso3 == 'AZE') return '994';
        if(country_iso3 == 'BHS') return '1242';
        if(country_iso3 == 'BHR') return '973';
        if(country_iso3 == 'BGD') return '880';
        if(country_iso3 == 'BRB') return '1246';
        if(country_iso3 == 'BLR') return '375';
        if(country_iso3 == 'BEL') return '32';
        if(country_iso3 == 'BLZ') return '501';
        if(country_iso3 == 'BEN') return '229';
        if(country_iso3 == 'BMU') return '1441';
        if(country_iso3 == 'BTN') return '975';
        if(country_iso3 == 'BOL') return '591';
        if(country_iso3 == 'BIH') return '387';
        if(country_iso3 == 'BWA') return '267';
        if(country_iso3 == 'BVT') return '_55';
        if(country_iso3 == 'BRA') return '55';
        if(country_iso3 == 'IOT') return '1284';
        if(country_iso3 == 'BRN') return '673';
        if(country_iso3 == 'BGR') return '359';
        if(country_iso3 == 'BFA') return '226';
        if(country_iso3 == 'BDI') return '257';
        if(country_iso3 == 'KHM') return '855';
        if(country_iso3 == 'CMR') return '237';
        if(country_iso3 == 'CAN') return '1';
        if(country_iso3 == 'CPV') return '238';
        if(country_iso3 == 'CYM') return '1345';
        if(country_iso3 == 'CAF') return '236';
        if(country_iso3 == 'TCD') return '235';
        if(country_iso3 == 'CHL') return '56';
        if(country_iso3 == 'CHN') return '86';
        if(country_iso3 == 'CXR') return '618';
        if(country_iso3 == 'CCK') return '61';
        if(country_iso3 == 'COL') return '57';
        if(country_iso3 == 'COM') return '269';
        if(country_iso3 == 'COG') return '242';
        if(country_iso3 == 'COD') return '243';
        if(country_iso3 == 'COK') return '682';
        if(country_iso3 == 'CRI') return '506';
        if(country_iso3 == 'HRV') return '385';
        if(country_iso3 == 'CUB') return '53';
        if(country_iso3 == 'CYP') return '357';
        if(country_iso3 == 'CZE') return '420';
        if(country_iso3 == 'DNK') return '45';
        if(country_iso3 == 'DJI') return '253';
        if(country_iso3 == 'DMA') return '1767';
        if(country_iso3 == 'DOM') return '1';
        if(country_iso3 == 'ECU') return '593';
        if(country_iso3 == 'EGY') return '20';
        if(country_iso3 == 'SLV') return '503';
        if(country_iso3 == 'GNQ') return '240';
        if(country_iso3 == 'ERI') return '291';
        if(country_iso3 == 'EST') return '372';
        if(country_iso3 == 'ETH') return '251';
        if(country_iso3 == 'FLK') return '500';
        if(country_iso3 == 'FRO') return '298';
        if(country_iso3 == 'FJI') return '679';
        if(country_iso3 == 'FIN') return '358';
        if(country_iso3 == 'FRA') return '33';
        if(country_iso3 == 'GUF') return '594';
        if(country_iso3 == 'PYF') return '689';
        if(country_iso3 == 'GAB') return '241';
        if(country_iso3 == 'GMB') return '220';
        if(country_iso3 == 'GEO') return '995';
        if(country_iso3 == 'DEU') return '49';
        if(country_iso3 == 'GHA') return '233';
        if(country_iso3 == 'GIB') return '350';
        if(country_iso3 == 'GRC') return '30';
        if(country_iso3 == 'GRL') return '299';
        if(country_iso3 == 'GRD') return '1473';
        if(country_iso3 == 'GLP') return '590';
        if(country_iso3 == 'GUM') return '1671';
        if(country_iso3 == 'GTM') return '502';
        if(country_iso3 == 'GIN') return '224';
        if(country_iso3 == 'GNB') return '245';
        if(country_iso3 == 'GUY') return '592';
        if(country_iso3 == 'HTI') return '509';
        if(country_iso3 == 'HMD') return '61';
        if(country_iso3 == 'VAT') return '3';
        if(country_iso3 == 'HND') return '504';
        if(country_iso3 == 'HKG') return '852';
        if(country_iso3 == 'HUN') return '36';
        if(country_iso3 == 'ISL') return '354';
        if(country_iso3 == 'IND') return '91';
        if(country_iso3 == 'IDN') return '62';
        if(country_iso3 == 'IRN') return '98';
        if(country_iso3 == 'IRQ') return '964';
        if(country_iso3 == 'IRL') return '353';
        if(country_iso3 == 'ISR') return '972';
        if(country_iso3 == 'ITA') return '39';
        if(country_iso3 == 'CIV') return '225';
        if(country_iso3 == 'JAM') return '1876';
        if(country_iso3 == 'JPN') return '81';
        if(country_iso3 == 'JOR') return '962';
        if(country_iso3 == 'KAZ') return '7';
        if(country_iso3 == 'KEN') return '254';
        if(country_iso3 == 'KIR') return '686';
        if(country_iso3 == 'PRK') return '850';
        if(country_iso3 == 'KOR') return '82';
        if(country_iso3 == 'KWT') return '965';
        if(country_iso3 == 'KGZ') return '7';
        if(country_iso3 == 'LAO') return '856';
        if(country_iso3 == 'LVA') return '371';
        if(country_iso3 == 'LBN') return '961';
        if(country_iso3 == 'LSO') return '266';
        if(country_iso3 == 'LBR') return '231';
        if(country_iso3 == 'LBY') return '218';
        if(country_iso3 == 'LIE') return '423';
        if(country_iso3 == 'LTU') return '370';
        if(country_iso3 == 'LUX') return '352';
        if(country_iso3 == 'MAC') return '853';
        if(country_iso3 == 'MKD') return '389';
        if(country_iso3 == 'MDG') return '261';
        if(country_iso3 == 'MWI') return '265';
        if(country_iso3 == 'MYS') return '60';
        if(country_iso3 == 'MDV') return '960';
        if(country_iso3 == 'MLI') return '223';
        if(country_iso3 == 'MLT') return '356';
        if(country_iso3 == 'MHL') return '692';
        if(country_iso3 == 'MTQ') return '596';
        if(country_iso3 == 'MRT') return '222';
        if(country_iso3 == 'MUS') return '230';
        if(country_iso3 == 'MYT') return '262';
        if(country_iso3 == 'MEX') return '52';
        if(country_iso3 == 'FSM') return '691';
        if(country_iso3 == 'MDA') return '373';
        if(country_iso3 == 'MCO') return '377';
        if(country_iso3 == 'MNG') return '976';
        if(country_iso3 == 'MSR') return '1664';
        if(country_iso3 == 'MAR') return '212';
        if(country_iso3 == 'MOZ') return '258';
        if(country_iso3 == 'MMR') return '95';
        if(country_iso3 == 'NAM') return '264';
        if(country_iso3 == 'NRU') return '674';
        if(country_iso3 == 'NPL') return '977';
        if(country_iso3 == 'NLD') return '31';
        if(country_iso3 == 'ANT') return '599';
        if(country_iso3 == 'NCL') return '687';
        if(country_iso3 == 'NZL') return '64';
        if(country_iso3 == 'NIC') return '505';
        if(country_iso3 == 'NER') return '227';
        if(country_iso3 == 'NGA') return '234';
        if(country_iso3 == 'NIU') return '683';
        if(country_iso3 == 'NFK') return '672';
        if(country_iso3 == 'MNP') return '1670';
        if(country_iso3 == 'NOR') return '47';
        if(country_iso3 == 'OMN') return '968';
        if(country_iso3 == 'PAK') return '92';
        if(country_iso3 == 'PLW') return '680';
        if(country_iso3 == 'PSE') return '970';
        if(country_iso3 == 'PAN') return '507';
        if(country_iso3 == 'PNG') return '675';
        if(country_iso3 == 'PRY') return '595';
        if(country_iso3 == 'PER') return '51';
        if(country_iso3 == 'PHL') return '63';
        if(country_iso3 == 'PCN') return '870';
        if(country_iso3 == 'POL') return '48';
        if(country_iso3 == 'PRT') return '351';
        if(country_iso3 == 'PRI') return '1';
        if(country_iso3 == 'QAT') return '974';
        if(country_iso3 == 'REU') return '262';
        if(country_iso3 == 'ROM') return '40';
        if(country_iso3 == 'RUS') return '7';
        if(country_iso3 == 'RWA') return '250';
        if(country_iso3 == 'SHN') return '290';
        if(country_iso3 == 'KNA') return '1869';
        if(country_iso3 == 'LCA') return '1758';
        if(country_iso3 == 'SPM') return '508';
        if(country_iso3 == 'VCT') return '1758';
        if(country_iso3 == 'WSM') return '685';
        if(country_iso3 == 'SMR') return '378';
        if(country_iso3 == 'STP') return '239';
        if(country_iso3 == 'SAU') return '966';
        if(country_iso3 == 'SEN') return '221';
        if(country_iso3 == 'SRB') return '381';
        if(country_iso3 == 'SYC') return '248';
        if(country_iso3 == 'SLE') return '232';
        if(country_iso3 == 'SGP') return '65';
        if(country_iso3 == 'SVK') return '421';
        if(country_iso3 == 'SVN') return '386';
        if(country_iso3 == 'SLB') return '677';
        if(country_iso3 == 'SOM') return '252';
        if(country_iso3 == 'ZAF') return '27';
        if(country_iso3 == 'SGS') return '44';
        if(country_iso3 == 'ESP') return '34';
        if(country_iso3 == 'LKA') return '94';
        if(country_iso3 == 'SDN') return '249';
        if(country_iso3 == 'SUR') return '597';
        if(country_iso3 == 'SJM') return '47';
        if(country_iso3 == 'SWZ') return '268';
        if(country_iso3 == 'SWE') return '46';
        if(country_iso3 == 'CHE') return '41';
        if(country_iso3 == 'SYR') return '963';
        if(country_iso3 == 'TWN') return '886';
        if(country_iso3 == 'TJK') return '992';
        if(country_iso3 == 'TZA') return '255';
        if(country_iso3 == 'THA') return '66';
        if(country_iso3 == 'TLS') return '670';
        if(country_iso3 == 'TGO') return '228';
        if(country_iso3 == 'TKL') return '690';
        if(country_iso3 == 'TON') return '676';
        if(country_iso3 == 'TTO') return '1868';
        if(country_iso3 == 'TUN') return '216';
        if(country_iso3 == 'TUR') return '90';
        if(country_iso3 == 'TKM') return '993';
        if(country_iso3 == 'TCA') return '1649';
        if(country_iso3 == 'TUV') return '688';
        if(country_iso3 == 'UGA') return '256';
        if(country_iso3 == 'UKR') return '380';
        if(country_iso3 == 'ARE') return '971';
        if(country_iso3 == 'GBR') return '44';
        if(country_iso3 == 'USA') return '1';
        if(country_iso3 == 'UMI') return '1340';
        if(country_iso3 == 'URY') return '598';
        if(country_iso3 == 'UZB') return '998';
        if(country_iso3 == 'VUT') return '678';
        if(country_iso3 == 'VEN') return '58';
        if(country_iso3 == 'VNM') return '84';
        if(country_iso3 == 'VGB') return '1284';
        if(country_iso3 == 'VIR') return '1340';
        if(country_iso3 == 'WLF') return '681';
        if(country_iso3 == 'YEM') return '260';
        if(country_iso3 == 'ZMB') return '260';
        if(country_iso3 == 'ZWE') return '263';


    }

How can one tell the version of React running at runtime in the browser?

For an app created with create-react-app I managed to see the version:

  1. Open Chrome Dev Tools / Firefox Dev Tools,
  2. Search and open main.XXXXXXXX.js file where XXXXXXXX is a builds hash /could be different,
  3. Optional: format source by clicking on the {} to show the formatted source,
  4. Search as text inside the source for react-dom,
  5. in Chrome was found: "react-dom": "^16.4.0",
  6. in Firefox was found: 'react-dom': '^16.4.0'

The app was deployed without source map.

How do you get the current page number of a ViewPager for Android?

There is no any method getCurrentItem() in viewpager.i already checked the API

Extend a java class from one file in another java file

Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them. The closes thing to an include statement java has is 'import'. Since classes are broken up into namespaces like foo.bar.Baz, if you're in the qux package and you want to use the Baz class without having to use its full name of foo.bar.Baz, then you need to use an import statement at the beginning of your java file like so: import foo.bar.Baz

Cannot delete directory with Directory.Delete(path, true)

I'm surprised that no one thought of this simple non-recursive method, which can delete directories containing read only files, without needing to change read only attribute of each of them.

Process.Start("cmd.exe", "/c " + @"rmdir /s/q C:\Test\TestDirectoryContainingReadOnlyFiles"); 

(Change a bit to not to fire a cmd window momentarily, which is available all over the internet)

How can you detect the version of a browser?

This is a Update on Fzs2 & kennebec For New Edge Chromium

_x000D_
_x000D_
function get_browser() {
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 
    if(/trident/i.test(M[1])){
        tem=/\brv[ :]+(\d+)/g.exec(ua) || []; 
        return {name:'IE',version:(tem[1]||'')};
        }   
    if(M[1]==='Chrome'){
        tem=ua.match(/\bEdg\/(\d+)/)
        if(tem!=null)   {return {name:'Edge(Chromium)', version:tem[1]};}
        tem=ua.match(/\bOPR\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }   
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
    return {
      name: M[0],
      version: M[1]
    };
 }

var browser=get_browser(); // browser.name = 'Edge(Chromium)'
                           // browser.version = '86'

console.log(browser);
_x000D_
_x000D_
_x000D_

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

When the project was originally created, the click-once signing certificate was added on the signing tab of the project's properties. This signs the click-once manifest when you build it. Between then and now, that certificate is no longer available. Either this wasn't the machine you originally built it on or it got cleaned up somehow. You need to re-add that certificate to your machine or chose another certificate.

What encoding/code page is cmd.exe using?

I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.

To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.

This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:

  • C sources encoded in UTF-8, using normal char[] C strings, and standard C library APIs.
  • In any code page, everything is processed internally as UTF-8 in your code, including the main() routine argv[], with standard input and output automatically converted to the right code page.
  • All stdio.h file functions support UTF-8 pathnames > 260 characters, up to 64 KBytes actually.
  • The same sources can compile and link successfully in Windows using Visual C++ and MsvcLibX and Visual C++ C library, and in Linux using gcc and Linux standard C library, with no need for #ifdef ... #endif blocks.
  • Adds include files common in Linux, but missing in Visual C++. Ex: unistd.h
  • Adds missing functions, like those for directory I/O, symbolic link management, etc, all with UTF-8 support of course :-).

More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.

The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.

Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv

This MsvcLibX library is by no means complete, and contributions for improving it are welcome!

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

How to programmatically empty browser cache?

The best idea is to make js file generation with name + some hash with version, if you do need to clear cache, just generate new files with new hash, this will trigger browser to load new files

Unlocking tables if thread is lost

With Sequel Pro:

Restarting the app unlocked my tables. It resets the session connection.

NOTE: I was doing this for a site on my local machine.

How to hide keyboard in swift on pressing return key?

you should connect the UITextfied with a delegate of view controller to make this function called

Eclipse: How do you change the highlight color of the currently selected method/expression?

After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:

General -> Editors -> Text Editors -> Annotations

Look for Occurences from the Annotation types list.

Then, be sure that Text as highlighted is selected, then choose the desired color.


And, a picture is worth a thousand words...

Preferences dialog
(source: coobird.net)

Image showing occurences highlighted in orange.
(source: coobird.net)

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

Create parameterized VIEW in SQL Server 2008

As astander has mentioned, you can do that with a UDF. However, for large sets using a scalar function (as oppoosed to a inline-table function) the performance will stink as the function is evaluated row-by-row. As an alternative, you could expose the same results via a stored procedure executing a fixed query with placeholders which substitutes in your parameter values.

(Here's a somewhat dated but still relevant article on row-by-row processing for scalar UDFs.)

Edit: comments re. degrading performance adjusted to make it clear this applies to scalar UDFs.

How to set an button align-right with Bootstrap?

UPDATE: For Bootstrap 5

The class name is now "float-end" instead of "pull-right"

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg float-end">
      Large button
    </button>
</div>

For Bootstrap 4 and under

Just add a simple pull-right class to the button, and make sure the container div is clearfixed:

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg pull-right">
      Large button
    </button>
</div>

How to force HTTPS using a web.config file

For those using ASP.NET MVC. You can use the RequireHttpsAttribute to force all responses to be HTTPS:

GlobalFilters.Filters.Add(new RequireHttpsAttribute());

Other things you may also want to do to help secure your site:

  1. Force Anti-Forgery tokens to use SSL/TLS:

    AntiForgeryConfig.RequireSsl = true;
    
  2. Require Cookies to require HTTPS by default by changing the Web.config file:

    <system.web>
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  3. Use the NWebSec.Owin NuGet package and add the following line of code to enable Strict Transport Security (HSTS) across the site. Don't forget to add the Preload directive below and submit your site to the HSTS Preload site. More information here and here. Note that if you are not using OWIN, there is a Web.config method you can read up on on the NWebSec site.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHsts(options => options.MaxAge(days: 720).Preload());
    
  4. Use the NWebSec.Owin NuGet package and add the following line of code to enable Public Key Pinning (HPKP) across the site. More information here and here.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHpkp(options => options
        .Sha256Pins(
            "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
            "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
        .MaxAge(days: 30));
    
  5. Include the https scheme in any URL's used. Content Security Policy (CSP) HTTP header and Subresource Integrity (SRI) do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js">
    </script>
    
  6. Use the ASP.NET MVC Boilerplate Visual Studio project template to generate a project with all of this and much more built in. You can also view the code on GitHub.

Can't find the 'libpq-fe.h header when trying to install pg gem

I finally solved this problem, but not using the previously described methods.

Using brew install postgresql, I find out that it had already been installed, but not linked.

  1. Find out where PostgreSQL is installed, and delete it,

  2. Then brew install postgresql again,

  3. brew link postgresql

  4. gem install pg

Printing with "\t" (tabs) does not result in aligned columns

In continuation of the comments by Péter and duncan, I normally use a quick padding method, something like -

public String rpad(String inStr, int finalLength)
{
    return (inStr + "                          " // typically a sufficient length spaces string.
        ).substring(0, finalLength);
}

similarly you can have a lpad() as well

How to convert string representation of list to a list?

You may run into such problem while dealing with scraped data stored as Pandas DataFrame.

This solution works like charm if the list of values is present as text.

def textToList(hashtags):
    return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')

hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)

Output: ['A', 'B', 'C', 'D']

No external library required.

CSS background image URL failing to load

source URL for image can be a URL on a website like http://www.google.co.il/images/srpr/nav_logo73.png or https://https.openbsd.org/images/tshirt-26_front.gif or if you want to use a local file try this: url("file:///MacintoshHDOriginal/Users/lowri/Desktop/acgnx/image s/images/acgn-site-background-X_07.jpg")

Get Selected value from dropdown using JavaScript

Working jsbin: http://jsbin.com/ANAYeDU/4/edit

Main bit:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}

CSS height 100% percent not working

Set the containing element/div to a height. Otherwise your asking the browser to set the height to 100% of an unknown value and it can't.

More info here: http://webdesign.about.com/od/csstutorials/f/set-css-height-100-percent.htm

What is the difference between join and merge in Pandas?

From this documentation

pandas provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects:

merge(left, right, how='inner', on=None, left_on=None, right_on=None,
      left_index=False, right_index=False, sort=True,
      suffixes=('_x', '_y'), copy=True, indicator=False)

And :

DataFrame.join is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. Here is a very basic example: The data alignment here is on the indexes (row labels). This same behavior can be achieved using merge plus additional arguments instructing it to use the indexes:

result = pd.merge(left, right, left_index=True, right_index=True,
how='outer')

Is it possible to insert HTML content in XML document?

Just put the html tags with there content and add the xmlns attribute with quotes after the equals and in between the quotes is http://www.w3.org/1999/xhtml

Detecting an undefined object property

I would like to show you something I'm using in order to protect the undefined variable:

Object.defineProperty(window, 'undefined', {});

This forbids anyone to change the window.undefined value therefore destroying the code based on that variable. If using "use strict", anything trying to change its value will end in error, otherwise it would be silently ignored.

Official way to ask jQuery wait for all images to load before executing something

With jQuery, you use $(document).ready() to execute something when the DOM is loaded and $(window).on("load", handler) to execute something when all other things are loaded as well, such as the images.

The difference can be seen in the following complete HTML file, provided you have a lot of jollyrogerNN JPEG files (or other suitable ones):

<html>
    <head>
        <script src="jquery-1.7.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert ("done");
            });
        </script>
    </head><body>
        Hello
        <img src="jollyroger00.jpg">
        <img src="jollyroger01.jpg">
        // : 100 copies of this in total
        <img src="jollyroger99.jpg">
    </body>
</html>

With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:

$(document).ready(function() {

into:

$(window).on("load", function() {

then the alert box doesn't appear until after the images are loaded.

Hence, to wait until the entire page is ready, you could use something like:

$(window).on("load", function() {
    // weave your magic here.
});

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

Set Windows process (or user) memory limit

Use the Application Verifier (AppVerifier) tool from Microsoft.

In my case I need to simulate memory no longer being available so I did the following in the tool:

  1. Added my application
  2. Unchecked Basic
  3. Checked Low Resource Simulation
    • Changed TimeOut to 120000 - my application will run normally for 2 minutes before anything goes into effect.
    • Changed HeapAlloc to 100 - 100% chance of heap allocation error
    • Set Stacks to true - the stack will not be able to grow any larger
  4. Save
  5. Start my application

After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.

Programmatically change UITextField Keyboard type

_textField .keyboardType = UIKeyboardTypeAlphabet;
_textField .keyboardType = UIKeyboardTypeASCIICapable;
_textField .keyboardType = UIKeyboardTypeDecimalPad;
_textField .keyboardType = UIKeyboardTypeDefault;
_textField .keyboardType = UIKeyboardTypeEmailAddress;
_textField .keyboardType = UIKeyboardTypeNamePhonePad;
_textField .keyboardType = UIKeyboardTypeNumberPad;
_textField .keyboardType = UIKeyboardTypeNumbersAndPunctuation;
_textField .keyboardType = UIKeyboardTypePhonePad;
_textField .keyboardType = UIKeyboardTypeTwitter;
_textField .keyboardType = UIKeyboardTypeURL;
_textField .keyboardType = UIKeyboardTypeWebSearch;

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How can I be notified when an element is added to the page?

You can use livequery plugin for jQuery. You can provide a selector expression such as:

$("input[type=button].removeItemButton").livequery(function () {
    $("#statusBar").text('You may now remove items.');
});

Every time a button of a removeItemButton class is added a message appears in a status bar.

In terms of efficiency you might want avoid this, but in any case you could leverage the plugin instead of creating your own event handlers.

Revisited answer

The answer above was only meant to detect that an item has been added to the DOM through the plugin.

However, most likely, a jQuery.on() approach would be more appropriate, for example:

$("#myParentContainer").on('click', '.removeItemButton', function(){
          alert($(this).text() + ' has been removed');
});

If you have dynamic content that should respond to clicks for example, it's best to bind events to a parent container using jQuery.on.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

How to pass object from one component to another in Angular 2?

From component

_x000D_
_x000D_
import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
    import { HttpClient } from '@angular/common/http';_x000D_
    import { dataService } from "src/app/service/data.service";_x000D_
    @Component( {_x000D_
        selector: 'app-sideWidget',_x000D_
        templateUrl: './sideWidget.html',_x000D_
        styleUrls: ['./linked-widget.component.css']_x000D_
    } )_x000D_
    export class sideWidget{_x000D_
    TableColumnNames: object[];_x000D_
    SelectedtableName: string = "patient";_x000D_
    constructor( private LWTableColumnNames: dataService ) { _x000D_
       _x000D_
    }_x000D_
    _x000D_
    ngOnInit() {_x000D_
        this.http.post( 'getColumns', this.SelectedtableName )_x000D_
            .subscribe(_x000D_
            ( data: object[] ) => {_x000D_
                this.TableColumnNames = data;_x000D_
     this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
            } );_x000D_
    _x000D_
    }    _x000D_
    }
_x000D_
_x000D_
_x000D_

DataService

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
_x000D_
@Injectable()_x000D_
export class dataService {_x000D_
    refLWTableColumnNames: object;//creating an object for the data_x000D_
}
_x000D_
_x000D_
_x000D_

To Component

_x000D_
_x000D_
import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
_x000D_
@Component( {_x000D_
    selector: 'app-linked-widget',_x000D_
    templateUrl: './linked-widget.component.html',_x000D_
    styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
_x000D_
    constructor(private LWTableColumnNames: dataService) { }_x000D_
_x000D_
    ngOnInit() {_x000D_
    console.log(this.LWTableColumnNames.refLWTableColumnNames);_x000D_
    }_x000D_
    createTable(){_x000D_
        console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_
    }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

"Program type already exists" Remove your /build directory contents, it has some Dex(?) problem with the generated binary files. Got to those answers just like you, they helped to resolve this problem but created many others. Build contents removal works for all.

Get list of Excel files in a folder using VBA

You can use the built-in Dir function or the FileSystemObject.

They each have their own strengths and weaknesses.

Dir Function

The Dir Function is a built-in, lightweight method to get a list of files. The benefits for using it are:

  • Easy to Use
  • Good performance (it's fast)
  • Wildcard support

The trick is to understand the difference between calling it with or without a parameter. Here is a very simple example to demonstrate:

Public Sub ListFilesDir(ByVal sPath As String, Optional ByVal sFilter As String)

    Dim sFile As String

    If Right(sPath, 1) <> "\" Then
        sPath = sPath & "\"
    End If

    If sFilter = "" Then
        sFilter = "*.*"
    End If

    'call with path "initializes" the dir function and returns the first file name
    sFile = Dir(sPath & sFilter)

   'call it again until there are no more files
    Do Until sFile = ""

        Debug.Print sFile

        'subsequent calls without param return next file name
        sFile = Dir

    Loop

End Sub

If you alter any of the files inside the loop, you will get unpredictable results. It is better to read all the names into an array of strings before doing any operations on the files. Here is an example which builds on the previous one. This is a Function that returns a String Array:

Public Function GetFilesDir(ByVal sPath As String, _
    Optional ByVal sFilter As String) As String()

    'dynamic array for names
    Dim aFileNames() As String
    ReDim aFileNames(0)

    Dim sFile As String
    Dim nCounter As Long

    If Right(sPath, 1) <> "\" Then
        sPath = sPath & "\"
    End If

    If sFilter = "" Then
        sFilter = "*.*"
    End If

    'call with path "initializes" the dir function and returns the first file
    sFile = Dir(sPath & sFilter)

    'call it until there is no filename returned
    Do While sFile <> ""

        'store the file name in the array
        aFileNames(nCounter) = sFile

        'subsequent calls without param return next file
        sFile = Dir

        'make sure your array is large enough for another
        nCounter = nCounter + 1
        If nCounter > UBound(aFileNames) Then
            'preserve the values and grow by reasonable amount for performance
            ReDim Preserve aFileNames(UBound(aFileNames) + 255)
        End If

    Loop

    'truncate the array to correct size
    If nCounter < UBound(aFileNames) Then
        ReDim Preserve aFileNames(0 To nCounter - 1)
    End If

    'return the array of file names
    GetFilesDir = aFileNames()

End Function

File System Object

The File System Object is a library for IO operations which supports an object-model for manipulating files. Pros for this approach:

  • Intellisense
  • Robust object-model

You can add a reference to to "Windows Script Host Object Model" (or "Windows Scripting Runtime") and declare your objects like so:

Public Sub ListFilesFSO(ByVal sPath As String)

    Dim oFSO As FileSystemObject
    Dim oFolder As Folder
    Dim oFile As File

    Set oFSO = New FileSystemObject
    Set oFolder = oFSO.GetFolder(sPath)
    For Each oFile In oFolder.Files
        Debug.Print oFile.Name
    Next 'oFile

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

End Sub

If you don't want intellisense you can do like so without setting a reference:

Public Sub ListFilesFSO(ByVal sPath As String)

    Dim oFSO As Object
    Dim oFolder As Object
    Dim oFile As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    For Each oFile In oFolder.Files
        Debug.Print oFile.Name
    Next 'oFile

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

End Sub

How to erase the file contents of text file in Python?

Writing and Reading file content

def writeTempFile(text = ''):
    filePath = "/temp/file1.txt"
    if not text:                      # If blank return file content
        f = open(filePath, "r")
        slug = f.read()
        return slug
    else:
        f = open(filePath, "a") # Create a blank file
        f.seek(0)  # sets  point at the beginning of the file
        f.truncate()  # Clear previous content
        f.write(text) # Write file
        f.close() # Close file
        return text

It Worked for me

Duplicate keys in .NET dictionaries?

Here is one way of doing this with List< KeyValuePair< string, string > >

public class ListWithDuplicates : List<KeyValuePair<string, string>>
{
    public void Add(string key, string value)
    {
        var element = new KeyValuePair<string, string>(key, value);
        this.Add(element);
    }
}

var list = new ListWithDuplicates();
list.Add("k1", "v1");
list.Add("k1", "v2");
list.Add("k1", "v3");

foreach(var item in list)
{
    string x = string.format("{0}={1}, ", item.Key, item.Value);
}

Outputs k1=v1, k1=v2, k1=v3

C dynamically growing array

These posts apparently are in the wrong order! This is #1 in a series of 3 posts. Sorry.

In attempting to use Lie Ryan's code, I had problems retrieving stored information. The vector's elements are not stored contiguously,as you can see by "cheating" a bit and storing the pointer to each element's address (which of course defeats the purpose of the dynamic array concept) and examining them.

With a bit of tinkering, via:

ss_vector* vector; // pull this out to be a global vector

// Then add the following to attempt to recover stored values.

int return_id_value(int i,apple* aa) // given ptr to component,return data item
{   printf("showing apple[%i].id = %i and  other_id=%i\n",i,aa->id,aa->other_id);
    return(aa->id);
}

int Test(void)  // Used to be "main" in the example
{   apple* aa[10]; // stored array element addresses
    vector = ss_init_vector(sizeof(apple));
    // inserting some items
    for (int i = 0; i < 10; i++)
    {   aa[i]=init_apple(i);
        printf("apple id=%i and  other_id=%i\n",aa[i]->id,aa[i]->other_id);
        ss_vector_append(vector, aa[i]);
     }   
 // report the number of components
 printf("nmbr of components in vector = %i\n",(int)vector->size);
 printf(".*.*array access.*.component[5] = %i\n",return_id_value(5,aa[5]));
 printf("components of size %i\n",(int)sizeof(apple));
 printf("\n....pointer initial access...component[0] = %i\n",return_id_value(0,(apple *)&vector[0]));
 //.............etc..., followed by
 for (int i = 0; i < 10; i++)
 {   printf("apple[%i].id = %i at address %i, delta=%i\n",i,    return_id_value(i,aa[i]) ,(int)aa[i],(int)(aa[i]-aa[i+1]));
 }   
// don't forget to free it
ss_vector_free(vector);
return 0;
}

It's possible to access each array element without problems, as long as you know its address, so I guess I'll try adding a "next" element and use this as a linked list. Surely there are better options, though. Please advise.

cannot import name patterns

This is the code which worked for me. My django version is 1.10.4 final

from django.conf.urls import url, include

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    # Examples:
    # url(r'^$', 'blog.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
]

How to get access token from FB.login method in javascript SDK

If you are already connected, simply type this in the javascript console:

FB.getAuthResponse()['accessToken']

How can I copy data from one column to another in the same table?

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

rmagick gem install "Can't find Magick-config"

What I did to fix the problem on Ubuntu was

$ sudo apt-get install libmagickwand-dev
$ sudo apt-get install ImageMagick

How does jQuery work when there are multiple elements with the same ID value?

jQuery's id selector only returns one result. The descendant and multiple selectors in the second and third statements are designed to select multiple elements. It's similar to:

Statement 1

var length = document.getElementById('a').length;

...Yields one result.

Statement 2

var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
    if (document.body.childNodes.item(i).id == 'a') {
        length++;
    }
}

...Yields two results.

Statement 3

var length = document.getElementById('a').length + document.getElementsByTagName('div').length;

...Also yields two results.

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

How do you generate dynamic (parameterized) unit tests in Python?

There's also Hypothesis which adds fuzz or property based testing.

This is a very powerful testing method.

MongoDB SELECT COUNT GROUP BY

If you need multiple columns to group by, follow this model. Here I am conducting a count by status and type:

  db.BusinessProcess.aggregate({
    "$group": {
        _id: {
            status: "$status",
            type: "$type"
        },
        count: {
            $sum: 1
        }
    }
   })

How to print something when running Puppet client?

If, like me, you don't have access to the puppet master and need to print debug logs to inspect variables on your puppet client machine, you can try writing to a file from your puppet code itself:

file { '/tmp/puppet_debug.log':
  content => inline_template('<%= @variable_x.to_s %>'),
}

How to delete from multiple tables in MySQL?

I found this article which showing you how to delete data from multiple tables by using MySQL DELETE JOIN statement with good explanation.

enter image description here

Copy row but with new id

This works in MySQL all versions and Amazon RDS Aurora:

INSERT INTO my_table SELECT 0,tmp.* FROM tmp;

or

Setting the index column to NULL and then doing the INSERT.

But not in MariaDB, I tested version 10.

jQuery Button.click() event is triggered twice

Related to Stepan's Answer.

in my case, i have both input and label in my .click() listener.

i just replaced the label to div, it worked!

vbscript output to console

I came across this post and went back to an approach that I used some time ago which is similar to @MadAntrax's.

The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.

This assumes that your objective is to stream output to the console, rather than having output go to message boxes.

The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:

    Option Explicit

'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE

'// Now we can use the Consol object to write to and read from the console
With CONS

    '// Simply write a line
     .print "CSCRIPT Console demo script"

     '// Arguments are passed through correctly, if present
     .Print "Arg count=" & wscript.arguments.count

     '// List all the arguments on the console log
     dim ix
     for ix = 0 to wscript.arguments.count -1
        .print "Arg(" & ix & ")=" & wscript.arguments(ix)
     next

     '// Prompt for some text from the user
     dim sMsg : sMsg = .prompt( "Enter any text:" )

     '// Write out the text in a box
     .Box sMsg

     '// Pause with the message "Hit enter to continue"
     .Pause

End With     




'= =========== End of script - the cCONSOLE class code follows here

Here is the code for the cCONSOLE class

     CLASS cCONSOLE
 '= =================================================================
 '= 
 '=    This class provides automatic switch to CScript and has methods
 '=    to write to and read from the CSCript console. It transparently
 '=    switches to CScript if the script has been started in WScript.
 '=
 '= =================================================================

    Private oOUT
    Private oIN


    Private Sub Class_Initialize()
    '= Run on creation of the cCONSOLE object, checks for cScript operation


        '= Check to make sure we are running under CScript, if not restart
        '= then run using CScript and terminate this instance.
        dim oShell
        set oShell = CreateObject("WScript.Shell")

        If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
            '= Not running under CSCRIPT

            '= Get the arguments on the command line and build an argument list
            dim ArgList, IX
            ArgList = ""

            For IX = 0 to wscript.arguments.count - 1
                '= Add the argument to the list, enclosing it in quotes
                argList = argList & " """ & wscript.arguments.item(IX) & """"
            next

            '= Now restart with CScript and terminate this instance
            oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
            WScript.Quit

        End If

        '= Running under CScript so OK to continue
        set oShell = Nothing

        '= Save references to stdout and stdin for use with Print, Read and Prompt
        set oOUT = WScript.StdOut
        set oIN = WScript.StdIn

        '= Print out the startup box 
            StartBox
            BoxLine Wscript.ScriptName
            BoxLine "Started at " & Now()
            EndBox


    End Sub

    '= Utility methods for writing a box to the console with text in it

            Public Sub StartBox()

                Print "  " & String(73, "_") 
                Print " |" & Space(73) & "|"
            End Sub

            Public Sub BoxLine(sText)

                Print Left(" |" & Centre( sText, 74) , 75) & "|"
            End Sub

            Public Sub EndBox()
                Print " |" & String(73, "_") & "|"
                Print ""
            End Sub

            Public Sub Box(sMsg)
                StartBox
                BoxLine sMsg
                EndBox
            End Sub

    '= END OF Box utility methods


            '= Utility to center given text padded out to a certain width of text
            '= assuming font is monospaced
            Public Function Centre(sText, nWidth)
                dim iLen
                iLen = len(sText)

                '= Check for overflow
                if ilen > nwidth then Centre = sText : exit Function

                '= Calculate padding either side
                iLen = ( nWidth - iLen ) / 2

                '= Generate text with padding
                Centre = left( space(iLen) & sText & space(ilen), nWidth )
            End Function



    '= Method to write a line of text to the console
    Public Sub Print( sText )

        oOUT.WriteLine sText
    End Sub

    '= Method to prompt user input from the console with a message
    Public Function Prompt( sText )
        oOUT.Write sText
        Prompt = Read()
    End Function

    '= Method to read input from the console with no prompting
    Public Function Read()
        Read = oIN.ReadLine
    End Function

    '= Method to provide wait for n seconds
    Public Sub Wait(nSeconds)
        WScript.Sleep  nSeconds * 1000 
    End Sub

    '= Method to pause for user to continue
    Public Sub Pause
        Prompt "Hit enter to continue..."
    End Sub


 END CLASS

SQLAlchemy equivalent to SQL "LIKE" statement

try this code

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

How to correct TypeError: Unicode-objects must be encoded before hashing?

import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())

Display Python datetime without time

You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].

You can pass this as map/apply to use it in a dataframe/series too.

How to remove all line breaks from a string

You can use \n in a regex for newlines, and \r for carriage returns.

var str2 = str.replace(/\n|\r/g, "");

Different operating systems use different line endings, with varying mixtures of \n and \r. This regex will replace them all.

Limit Decimal Places in Android EditText

DecimalFormat form = new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.US));
    EditText et; 
    et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (actionId == EditorInfo.IME_ACTION_DONE) {
            double a = Double.parseDouble(et.getText().toString());
            et.setText(form.format(a));
        }
        return false;
    }
});

What this does is when you exit editing phase it formats the field to the right format. At them moment it has only 2 decimal charachters. I think this is pretty easy way to do this.

Creating a BLOB from a Base64 string in JavaScript

I'm posting a more declarative way of sync Base64 converting. While async fetch().blob() is very neat and I like this solution a lot, it doesn't work on Internet Explorer 11 (and probably Edge - I haven't tested this one), even with the polyfill - take a look at my comment to Endless' post for more details.

const blobPdfFromBase64String = base64String => {
   const byteArray = Uint8Array.from(
     atob(base64String)
       .split('')
       .map(char => char.charCodeAt(0))
   );
  return new Blob([byteArray], { type: 'application/pdf' });
};

Bonus

If you want to print it you could do something like:

const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // Or however you want to check it
const printPDF = blob => {
   try {
     isIE11
       ? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
       : printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
   } catch (e) {
     throw PDFError;
   }
};

Bonus x 2 - Opening a BLOB file in new tab for Internet Explorer 11

If you're able to do some preprocessing of the Base64 string on the server you could expose it under some URL and use the link in printJS :)

How to create dictionary and add key–value pairs dynamically?

In case if someone needs to create a dictionary object dynamically you can use the following code snippet

_x000D_
_x000D_
   let vars = [{key:"key", value:"value"},{key:"key2", value:"value2"}];
     let dict={}
     vars.map(varItem=>{
              dict[varItem.key]=varItem.value
            })

    console.log(dict)
_x000D_
_x000D_
_x000D_

Difference between & and && in Java?

& is bitwise. && is logical.

& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

Use child_process.execSync but keep output in console

You can pass the parent´s stdio to the child process if that´s what you want:

require('child_process').execSync(
    'rsync -avAXz --info=progress2 "/src" "/dest"',
    {stdio: 'inherit'}
);

Subtract one day from datetime

Try this, may this will help you

SELECT DATEDIFF(DAY, DATEADD(DAY,-1,'2013-03-13 00:00:00.000') , GETDATE())

Created Button Click Event c#

Create the Button and add it to Form.Controls list to display it on your form:

Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

Create the button click method here:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

Run javascript script (.js file) in mongodb including another file inside js

Yes you can. The default location for script files is data/db

If you put any script there you can call it as

load("myjstest.js")      // or 
load("/data/db/myjstest.js")

Convert SVG image to PNG with PHP

$command = 'convert -density 300 ';
                        if(Input::Post('height')!='' && Input::Post('width')!=''){
                            $command.='-resize '.Input::Post('width').'x'.Input::Post('height').' ';
                        }
                        $command.=$svg.' '.$source;
                        exec($command);
                        @unlink($svg);

or using : potrace demo :Tool4dev.com

What are named pipes?

Both on Windows and POSIX systems, named-pipes provide a way for inter-process communication to occur among processes running on the same machine. What named pipes give you is a way to send your data without having the performance penalty of involving the network stack.

Just like you have a server listening to a IP address/port for incoming requests, a server can also set up a named pipe which can listen for requests. In either cases, the client process (or the DB access library) must know the specific address (or pipe name) to send the request. Often, a commonly used standard default exists (much like port 80 for HTTP, SQL server uses port 1433 in TCP/IP; \\.\pipe\sql\query for a named pipe).

By setting up additional named pipes, you can have multiple DB servers running, each with its own request listeners.

The advantage of named pipes is that it is usually much faster, and frees up network stack resources.

-- BTW, in the Windows world, you can also have named pipes to remote machines -- but in that case, the named pipe is transported over TCP/IP, so you will lose performance. Use named pipes for local machine communication.

Query to search all packages for table and/or column

You can do this:

select *
from user_source
where upper(text) like upper('%SOMETEXT%');

Alternatively, SQL Developer has a built-in report to do this under:

View > Reports > Data Dictionary Reports > PLSQL > Search Source Code

The 11G docs for USER_SOURCE are here

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

All project settings seemed perfect, but I still got the error. Looking into the .vcxproj file and searching for "x86" revealed the problem:

<Lib>
  <AdditionalOptions> /machine:X86 %(AdditionalOptions)</AdditionalOptions>
</Lib>

A quick search/replace for all occurrances (ten individual file settings) fixed the problem.

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Here's a brief one for getting a specified number of tweets from your timeline. It basically does the same thing as the other examples, only with less code.

Just fill in the keys and adjust $count to your liking:

$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$count = '10';

$oauth = array('count' => $count,
               'oauth_consumer_key' => '[CONSUMER KEY]',
               'oauth_nonce' => md5(mt_rand()),
               'oauth_signature_method' => 'HMAC-SHA1',
               'oauth_timestamp' => time(),
               'oauth_token' => '[ACCESS TOKEN]',
               'oauth_version' => '1.0');

$oauth['oauth_signature'] = base64_encode(hash_hmac('sha1', 'GET&' . rawurlencode($url) . '&' . rawurlencode(implode('&', array_map(function ($v, $k) { return $k . '=' . $v; }, $oauth, array_keys($oauth)))), '[CONSUMER SECRET]&[ACCESS TOKEN SECRET]', true));

$twitterData = json_decode(file_get_contents($url . '?count=' . $count, false, stream_context_create(array('http' => array('method' => 'GET',
                                                                                                                           'header' => 'Authorization: OAuth ' 
                                                                                                                                       . implode(', ', array_map(function ($v, $k) { return $k . '="' . rawurlencode($v) . '"'; }, $oauth, array_keys($oauth))))))));

This one uses anonymous functions and file_get_contents instead of the cURL library. Note the use of an MD5 hashed nonce. Everyone seems to be going along with the time() nonce, however, most examples on the web concerning OAuth use some kind of encrypted string (like this one: http://www.sitepoint.com/understanding-oauth-1/). This makes more sense to me too.

Further note: you need PHP 5.3+ for the anonymous functions (in case your server/computer is in some cold war cave and you can't upgrade it).

Adding click event handler to iframe

You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);

cvc-elt.1: Cannot find the declaration of element 'MyElement'

Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

How to hide columns in HTML table?

You can also do what vs dev suggests programmatically by assigning the style with Javascript by iterating through the columns and setting the td element at a specific index to have that style.

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

Find Active Tab using jQuery and Twitter Bootstrap

First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.

  <ul class='nav nav-tabs'>
    <li class='active'><a href='#home'>Home</a></li>
    <li><a href='#menu1'>Menu 1</a></li>
    <li><a href='#menu2'>Menu 2</a></li>
    <li><a href='#menu3'>Menu 3</a></li>
  </ul>

  <div class='tab-content'>
    <div id='home' class='tab-pane fade in active'>
      <h3>HOME</h3>
    <div id='menu1' class='tab-pane fade'>
      <h3>Menu 1</h3>
    </div>
    <div id='menu2' class='tab-pane fade'>
      <h3>Menu 2</h3>
    </div>
    <div id='menu3' class='tab-pane fade'>
      <h3>Menu 3</h3>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
// Handling data-toggle manually
    $('.nav-tabs a').click(function(){
        $(this).tab('show');
    });
// The on tab shown event
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        alert('Hello from the other siiiiiide!');
        var current_tab = e.target;
        var previous_tab = e.relatedTarget;
    });
});
</script>

Adding maven nexus repo to my pom.xml

From maven setting reference, you can not put your username/password in a pom.xml

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

You can first add a repository in your pom and then add the username/password in the $MAVEN_HOME/conf/settings.xml:

  <servers>
    <server>
        <id>my-internal-site</id>
        <username>yourUsername</username>
        <password>yourPassword</password>
    </server>
  </servers>

Pretty-print a Map in Java

You should be able to do what you want by doing:

System.out.println(map) for example

As long as ALL your objects in the map have overiden the toString method you would see:
{key1=value1, key2=value2} in a meaningfull manner

If this is for your code, then overiding toString is a good habit and I suggest you go for that instead.

For your example where your objects are Strings you should be fine without anything else.
I.e. System.out.println(map) would print exactly what you need without any extra code

Bash script and /bin/bash^M: bad interpreter: No such file or directory

Your file has Windows line endings, which is confusing Linux.

Remove the spurious CR characters. You can do it with the following command:

 $ sed -i -e 's/\r$//' setup.sh

Python Key Error=0 - Can't find Dict error in code

The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

For those who got this error in AngularJS and not jQuery:

I got it in AngularJS v1.5.8 by trying to ng-include a type="text/ng-template" that didn't exist.

 <div ng-include="tab.content">...</div>

Make sure that when you use ng-include, the data for that directive points to an actual page/section. Otherwise, you probably wanted:

<div>{{tab.content}}</div>

Get the first key name of a JavaScript object

I use Lodash for defensive coding reasons.

In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.

A "fully defensive" approach with Lodash would use both keys as well as get:

const firstKey = _.get(_.keys(ahash), 0);

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

This usually means that something is trying to access the @property "givenName".

If you were doing something with Interface Builder(IB), the usual cause is that you either:

  1. deleted that property from the class, but haven't deleted the hookups in IB yet
  2. OR: you have a File's Owner object set to the wrong class (check the properties - different depending which version of xcode you're using
    • to find the Class Name its set as. You probably copy/pasted a NIB file, and didn't change this field in the NIB), and you've hooked up an outlet for that class, but your actual File's Owner is something different

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

You are trying to set int value to TextView so you are getting this issue. To solve this try below one option

option 1:

tv.setText(no+"");

Option2:

tv.setText(String.valueOf(no));

How to force IE10 to render page in IE9 document mode

The hack is recursive. It is like IE itself uses the component that is used by many other processes which want "web component". Hence in registry we add IEXPLORE.exe. In effect it is a recursive hack.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I am using the following construct, although you might want to avoid shell=True. This gives you the output and error message for any command, and the error code as well:

process = subprocess.Popen(cmd, shell=True,
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode

How to get the background color code of an element in hex?

Adding on @Newred solution. If your style has more than just the background-color you can use this:

$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1]

How can I make a JPA OneToOne relation lazy

This question is quite old, but with Hibernate 5.1.10, there are some new better comfortable solution.

Lazy loading works except for the parent side of a @OneToOne association. This is because Hibernate has no other way of knowing whether to assign a null or a Proxy to this variable. More details you can find in this article

  • You can activate lazy loading bytecode enhancement
  • Or, you can just remove the parent side and use the client side with @MapsId as explained in the article above. This way, you will find that you don’t really need the parent side since the child shares the same id with the parent so you can easily fetch the child by knowing the parent id .