Programs & Examples On #Variable width

How to horizontally center a floating element of a variable width?

The popular answer here does work sometimes, but other times it creates horizontal scroll bars that are tough to deal with - especially when dealing with wide horizontal navigations and large pull down menus. Here is an even lighter-weight version that helps avoid those edge cases:

#wrap {
    float: right;
    position: relative;
    left: -50%;
}
#content {
    left: 50%;
    position: relative;
}

Proof that it is working!

To more specifically answer your question, it is probably not possible to do without setting up some containing element, however it is very possible to do without specifying a width value. Hope that saves someone out there some headaches!

How to get text of an element in Selenium WebDriver, without including child element text?

You don't have to do a replace, you can get the length of the children text and subtract that from the overall length, and slice into the original text. That should be substantially faster.

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

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

Well, I've got no problem here :

df <- data.frame(v=1:5, x=sample(LETTERS[1:5],5))
df

#   v x
# 1 1 D
# 2 2 A
# 3 3 B
# 4 4 C
# 5 5 E

df <- df[order(df$x),]
df

#   v x
# 2 2 A
# 3 3 B
# 4 4 C
# 1 1 D
# 5 5 E

Display UIViewController as Popup in iPhone

You can do this to add any other subview to the view controller. First set the status bar to None for the ViewController which you want to add as subview so that you can resize to whatever you want. Then create a button in Present View controller and a method for button click. In the method:

- (IBAction)btnLogin:(id)sender {
    SubView *sub = [[SubView alloc] initWithNibName:@"SubView" bundle:nil];
    sub.view.frame = CGRectMake(20, 100, sub.view.frame.size.width, sub.view.frame.size.height);
    [self.view addSubview:sub.view];
}

Hope this helps, feel free to ask if any queries...

How can I mock requests and the response?

Just a helpful hint to those that are still struggling, converting from urllib or urllib2/urllib3 to requests AND trying to mock a response- I was getting a slightly confusing error when implementing my mock:

with requests.get(path, auth=HTTPBasicAuth('user', 'pass'), verify=False) as url:

AttributeError: __enter__

Well, of course, if I knew anything about how with works (I didn't), I'd know it was a vestigial, unnecessary context (from PEP 343). Unnecessary when using the requests library because it does basically the same thing for you under the hood. Just remove the with and use bare requests.get(...) and Bob's your uncle.

How to show all privileges from a user in oracle?

You can try these below views.

SELECT * FROM USER_SYS_PRIVS; 
SELECT * FROM USER_TAB_PRIVS;
SELECT * FROM USER_ROLE_PRIVS;

DBAs and other power users can find the privileges granted to other users with the DBA_ versions of these same views. They are covered in the documentation .

Those views only show the privileges granted directly to the user. Finding all the privileges, including those granted indirectly through roles, requires more complicated recursive SQL statements:

select * from dba_role_privs connect by prior granted_role = grantee start with grantee = '&USER' order by 1,2,3;
select * from dba_sys_privs  where grantee = '&USER' or grantee in (select granted_role from dba_role_privs connect by prior granted_role = grantee start with grantee = '&USER') order by 1,2,3;
select * from dba_tab_privs  where grantee = '&USER' or grantee in (select granted_role from dba_role_privs connect by prior granted_role = grantee start with grantee = '&USER') order by 1,2,3,4;

How do I remove a MySQL database?

If you are using an SQL script when you are creating your database and have any users created by your script, you need to drop them too. Lastly you need to flush the users; i.e., force MySQL to read the user's privileges again.

-- DELETE ALL RECIPE

drop schema <database_name>;
-- Same as `drop database <database_name>`

drop user <a_user_name>;
-- You may need to add a hostname e.g `drop user bob@localhost`

FLUSH PRIVILEGES;

Good luck!

Exclude all transitive dependencies of a single dependency

There is a workaround for this, if you set the scope of a dependency to runtime, transitive dependencies will be excluded. Though be aware this means you need to add in additional processing if you want to package the runtime dependency.

To include the runtime dependency in any packaging, you can use the maven-dependency-plugin's copy goal for a specific artifact.

Cannot create PoolableConnectionFactory

In my case the solution was to remove the attribute

validationQuery="select 1"

from the (Derby DB) resource tag.

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash
        self.tableView.reloadData()

        completionHandler(true)
    }
    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration
}

Embedding SVG into ReactJS

Update 2016-05-27

As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (class ? className, style="color: purple" ? style={{color: 'purple'}}). For any namespaced (colon-separated) attribute, e.g. xlink:href, remove the : and capitalize the second part of the attribute, e.g. xlinkHref. Here’s an example of an svg with <defs>, <use>, and inline styles:

function SvgWithXlink (props) {
    return (
        <svg
            width="100%"
            height="100%"
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
        >
            <style>
                { `.classA { fill:${props.fill} }` }
            </style>
            <defs>
                <g id="Port">
                    <circle style={{fill:'inherit'}} r="10"/>
                </g>
            </defs>

            <text y="15">black</text>
            <use x="70" y="10" xlinkHref="#Port" />
            <text y="35">{ props.fill }</text>
            <use x="70" y="30" xlinkHref="#Port" className="classA"/>
            <text y="55">blue</text>
            <use x="0" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
        </svg>
    );
}

Working codepen demo

For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.


Previous answer

You can do a simple SVG embed without having to use dangerouslySetInnerHTML by just stripping the namespace attributes. For example, this works:

        render: function() {
            return (
                <svg viewBox="0 0 120 120">
                    <circle cx="60" cy="60" r="50"/>
                </svg>
            );
        }

At which point you can think about adding props like fill, or whatever else might be useful to configure.

How to open the Chrome Developer Tools in a new window?

You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

ImportError: cannot import name main when running pip --version command in windows7 32 bit

I had the same problem, but uninstall and reinstall with apt and pip didn't work for me.

I saw another solution that presents a easy way to recover pip3 path:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

Disable future dates after today in Jquery Ui Datepicker

Change maxDate to current date

maxDate: new Date()

It will set current date as maximum value.

How do I restart a program based on user input?

Using one while loop:

In [1]: start = 1
   ...: 
   ...: while True:
   ...:     if start != 1:        
   ...:         do_run = raw_input('Restart?  y/n:')
   ...:         if do_run == 'y':
   ...:             pass
   ...:         elif do_run == 'n':
   ...:             break
   ...:         else: 
   ...:             print 'Invalid input'
   ...:             continue
   ...: 
   ...:     print 'Doing stuff!!!'
   ...: 
   ...:     if start == 1:
   ...:         start = 0
   ...:         
Doing stuff!!!

Restart?  y/n:y
Doing stuff!!!

Restart?  y/n:f
Invalid input

Restart?  y/n:n

In [2]:

Using Google Text-To-Speech in Javascript

Very easy with responsive voice. Just include the js and voila!

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>

<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value=' Play' />

What is the difference between React Native and React?

We can't compare them exactly. There are differences in use case.

(2018 update)


ReactJS

React has as its main focus Web Development.

    • React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page.
    • You can reuse code components in React, saving you a lot of time. (You can in React Native too.)
    • As a business: The rendering of your pages completely, from the server to the browser will improve the SEO of your web app.
    • It improves the debugging speed making your developer’s life easier.
    • You can use hybrid mobile app development, like Cordova or Ionic, to build mobile apps with React, but is more efficiently building mobile apps with React Native from many points.

React Native

An extension of React, niched on Mobile Development.

    • Its main focus is all about Mobile User Interfaces.
    • iOS & Android are covered.
    • Reusable React Native UI components & modules allow hybrid apps to render natively.
    • No need to overhaul your old app. All you have to do is add React Native UI components into your existing app’s code, without having to rewrite.
    • Doesn't use HTML to render the app. Provides alternative components that work in a similar way, so it wouldn't be hard to understand them.
    • Because your code doesn’t get rendered in an HTML page, this also means you won’t be able to reuse any libraries you previously used with React that renders any kind of HTML, SVG or Canvas.
    • React Native is not made from web elements and can’t be styled in the same way. Goodbye CSS Animations!

Hopefully I helped you :)

How do I get the directory that a program is running from?

#include <windows.h>
using namespace std;

// The directory path returned by native GetCurrentDirectory() no end backslash
string getCurrentDirectoryOnWindows()
{
    const unsigned long maxDir = 260;
    char currentDir[maxDir];
    GetCurrentDirectory(maxDir, currentDir);
    return string(currentDir);
}

How to annotate MYSQL autoincrement field with JPA annotations

If you are using MariaDB this will work

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

For more, you can check https://thorben-janssen.com/hibernate-tips-use-auto-incremented-column-primary-key/

Can't start Tomcat as Windows Service

You need to check the ports first. It might be situation that default port(8080) is used by some other application.

Try changing the port from 8080 to some different port in conf/server.xml file.

Also please check that your JRE_HOME variable is set correctly because tomcat needs JRE to run. You can also set your JRE_HOME variable in system. For that go to my computer->right click and select properties->Advanced system settings->Advanced->Environment variable and click on new-> variable name = "JRE_HOME" and variable value = "C:\Program Files\Java\jre7"

CSS to keep element at "fixed" position on screen

position: fixed;

Will make this happen.

It handles like position:absolute; with the exception that it will scroll with the window as the user scrolls down the content.

Mac install and open mysql using terminal

try with either of the 2 below commands

/usr/local/mysql/bin/mysql -uroot
-- OR --
/usr/local/Cellar/mysql/<version>/bin/mysql -uroot

How to get a unix script to run every 15 seconds?

I wrote a scheduler faster than cron. I have also implemented an overlapping guard. You can configure the scheduler to not start new process if previous one is still running. Take a look at https://github.com/sioux1977/scheduler/wiki

How to do this in Laravel, subquery where in

Please try this online tool sql2builder

DB::table('products')
    ->whereIn('products.id',function($query) {
                            DB::table('product_category')
                            ->whereIn('category_id',['223','15'])
                            ->select('product_id');
                        })
    ->where('products.active',1)
    ->select('products.id','products.name','products.img','products.safe_name','products.sku','products.productstatusid')
    ->get();

How to remove all characters after a specific character in python?

Split on your separator at most once, and take the first piece:

sep = '...'
stripped = text.split(sep, 1)[0]

You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.

How to display a date as iso 8601 format with PHP

The second argument of date is a UNIX timestamp, not a database timestamp string.

You need to convert your database timestamp with strtotime.

<?= date("c", strtotime($post[3])) ?>

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

Select box arrow style

The select box arrow is a native ui element, it depends on the desktop theme or the web browser. Use a jQuery plugin (e.g. Select2, Chosen) or CSS.

Set value of textbox using JQuery

You are logging sup directly which is a string

console.log('sup')

Also you are using the wrong id

The template says #main_search but you are using #searchBar

I suppose you are trying this out

$(function() {
   var sup = $('#main_search').val('hi')
   console.log(sup);  // sup is a variable here
});

How to search a string in String array

bool exists = arr.Contains("One");

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

If the time is in milliseconds and one need to preserve them:

DECLARE @value VARCHAR(32) = '1561487667713';

SELECT DATEADD(MILLISECOND, CAST(RIGHT(@value, 3) AS INT) - DATEDIFF(MILLISECOND,GETDATE(),GETUTCDATE()), DATEADD(SECOND, CAST(LEFT(@value, 10) AS INT), '1970-01-01T00:00:00'))

VB.NET - How to move to next item a For Each Loop?

What about:

If Not I = x Then

  ' Do something '

End If

' Move to next item '

Generate a heatmap in MatPlotLib using a scatter data set

In Matplotlib lexicon, i think you want a hexbin plot.

If you're not familiar with this type of plot, it's just a bivariate histogram in which the xy-plane is tessellated by a regular grid of hexagons.

So from a histogram, you can just count the number of points falling in each hexagon, discretiize the plotting region as a set of windows, assign each point to one of these windows; finally, map the windows onto a color array, and you've got a hexbin diagram.

Though less commonly used than e.g., circles, or squares, that hexagons are a better choice for the geometry of the binning container is intuitive:

  • hexagons have nearest-neighbor symmetry (e.g., square bins don't, e.g., the distance from a point on a square's border to a point inside that square is not everywhere equal) and

  • hexagon is the highest n-polygon that gives regular plane tessellation (i.e., you can safely re-model your kitchen floor with hexagonal-shaped tiles because you won't have any void space between the tiles when you are finished--not true for all other higher-n, n >= 7, polygons).

(Matplotlib uses the term hexbin plot; so do (AFAIK) all of the plotting libraries for R; still i don't know if this is the generally accepted term for plots of this type, though i suspect it's likely given that hexbin is short for hexagonal binning, which is describes the essential step in preparing the data for display.)


from matplotlib import pyplot as PLT
from matplotlib import cm as CM
from matplotlib import mlab as ML
import numpy as NP

n = 1e5
x = y = NP.linspace(-5, 5, 100)
X, Y = NP.meshgrid(x, y)
Z1 = ML.bivariate_normal(X, Y, 2, 2, 0, 0)
Z2 = ML.bivariate_normal(X, Y, 4, 1, 1, 1)
ZD = Z2 - Z1
x = X.ravel()
y = Y.ravel()
z = ZD.ravel()
gridsize=30
PLT.subplot(111)

# if 'bins=None', then color of each hexagon corresponds directly to its count
# 'C' is optional--it maps values to x-y coordinates; if 'C' is None (default) then 
# the result is a pure 2D histogram 

PLT.hexbin(x, y, C=z, gridsize=gridsize, cmap=CM.jet, bins=None)
PLT.axis([x.min(), x.max(), y.min(), y.max()])

cb = PLT.colorbar()
cb.set_label('mean value')
PLT.show()   

enter image description here

How to negate a method reference predicate

You can use Predicates from Eclipse Collections

MutableList<String> strings = Lists.mutable.empty();
int nonEmptyStrings = strings.count(Predicates.not(String::isEmpty));

If you can't change the strings from List:

List<String> strings = new ArrayList<>();
int nonEmptyStrings = ListAdapter.adapt(strings).count(Predicates.not(String::isEmpty));

If you only need a negation of String.isEmpty() you can also use StringPredicates.notEmpty().

Note: I am a contributor to Eclipse Collections.

How do I view the list of functions a Linux shared library is exporting?

What you need is nm and its -D option:

$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
         U atanf
         U calloc
.
.
.

Exported sumbols are indicated by a T. Required symbols that must be loaded from other shared objects have a U. Note that the symbol table does not include just functions, but exported variables as well.

See the nm manual page for more information.

How do I drop a foreign key constraint only if it exists in sql server?

James's answer works just fine if you know the name of the actual constraint. The tricky thing is that in legacy and other real world scenarios you may not know what the constraint is called.

If this is the case you risk creating duplicate constraints, to avoid you can use:

create function fnGetForeignKeyName
(
    @ParentTableName nvarchar(255), 
    @ParentColumnName nvarchar(255),
    @ReferencedTableName nvarchar(255),
    @ReferencedColumnName nvarchar(255)
)
returns nvarchar(255)
as
begin 
    declare @name nvarchar(255)

    select @name = fk.name  from sys.foreign_key_columns fc
    join sys.columns pc on pc.column_id = parent_column_id and parent_object_id = pc.object_id
    join sys.columns rc on rc.column_id = referenced_column_id and referenced_object_id = rc.object_id 
    join sys.objects po on po.object_id = pc.object_id
    join sys.objects ro on ro.object_id = rc.object_id 
    join sys.foreign_keys fk on fk.object_id = fc.constraint_object_id
    where 
        po.object_id = object_id(@ParentTableName) and 
        ro.object_id = object_id(@ReferencedTableName) and
        pc.name = @ParentColumnName and 
        rc.name = @ReferencedColumnName

    return @name
end

go

declare @name nvarchar(255)
declare @sql nvarchar(4000)
-- hunt for the constraint name on 'Badges.BadgeReasonTypeId' table refs the 'BadgeReasonTypes.Id'
select @name = dbo.fnGetForeignKeyName('dbo.Badges', 'BadgeReasonTypeId', 'dbo.BadgeReasonTypes', 'Id')
-- if we find it, the name will not be null
if @name is not null 
begin 
    set @sql = 'alter table Badges drop constraint ' + replace(@name,']', ']]')
    exec (@sql)
end

Import SQL file into mysql

Finally, i solved the problem. I placed the `nitm.sql` file in `bin` file of the `mysql` folder and used the following syntax.

C:\wamp\bin\mysql\mysql5.0.51b\bin>mysql -u root nitm < nitm.sql

And this worked.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

To find ANY and ALL unicode error related... Using the following command:

grep -r -P '[^\x00-\x7f]' /etc/apache2 /etc/letsencrypt /etc/nginx

Found mine in

/etc/letsencrypt/options-ssl-nginx.conf:        # The following CSP directives don't use default-src as 

Using shed, I found the offending sequence. It turned out to be an editor mistake.

00008099:     C2  194 302 11000010
00008100:     A0  160 240 10100000
00008101:  d  64  100 144 01100100
00008102:  e  65  101 145 01100101
00008103:  f  66  102 146 01100110
00008104:  a  61  097 141 01100001
00008105:  u  75  117 165 01110101
00008106:  l  6C  108 154 01101100
00008107:  t  74  116 164 01110100
00008108:  -  2D  045 055 00101101
00008109:  s  73  115 163 01110011
00008110:  r  72  114 162 01110010
00008111:  c  63  099 143 01100011
00008112:     C2  194 302 11000010
00008113:     A0  160 240 10100000

Running MSBuild fails to read SDKToolsPath

We have a winXP build pc, and use Visual Build Pro 6 to build our software. since some of our developers use VS 2010 the project files now contain reference to "tool version 4.0" and from what I can tell, this tells Visual Build it needs to find a sdk7.x somewhere, even though we only build for .NET 3.5. This caused it not to find lc.exe. I tried to fool it by pointing all the macros to the 6.0A sdk that came with VS2008 which is installed on the pc, but that did not work.

I eventually got it working by downloading and installing sdk 7.1. I then created a registry key for 7.0A and pointed the install path to the install path of the 7.1 sdk. now it happily finds a compatible "lc.exe" and all the code compiles fine. I have a feeling I will now also be able to compile .NET 4.0 code even though VS2010 is not installed, but I have not tried that yet.

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

It depends on what version you are using. These two 2012 keys have worked well for me with their corresponding versions to download for Update 4. Please be aware that some of these reg locations may be OS-dependent. I collected this info from a Windows 10 x64 box. I'm just going to go ahead and dump all of these redist versions and the reg keys I search for to detect installation.:


Visual C++ 2005

Microsoft Visual C++ 2005 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\1af2a8da7e60d0b429d7e6453b3d0182
Configuration: x64
Version: 6.0.2900.2180

Direct Download URL: https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x64.EXE

Microsoft Visual C++ 2005 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\c1c4f01781cc94c4c8fb1542c0981a2a 
Configuration: x86
Version: 6.0.2900.2180

Direct Download URL: https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x86.EXE


Visual C++ 2008

Microsoft Visual C++ 2008 Redistributable - x64 9.0.30729.6161 (SP1)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\67D6ECF5CD5FBA732B8B22BAC8DE1B4D 
Configuration: x64
Version: 9.0.30729.6161 (Actual $Version data in registry: 0x9007809 [DWORD])

Direct Download URL: https://download.microsoft.com/download/2/d/6/2d61c766-107b-409d-8fba-c39e61ca08e8/vcredist_x64.exe

Microsoft Visual C++ 2008 Redistributable - x86 9.0.30729.6161 (SP1)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\6E815EB96CCE9A53884E7857C57002F0
Configuration: x86
Version: 9.0.30729.6161 (Actual $Version data in registry: 0x9007809 [DWORD])

Direct Download URL: https://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-795376989c03/vcredist_x86.exe


Visual C++ 2010

Microsoft Visual C++ 2010 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\1926E8D15D0BCE53481466615F760A7F 
Configuration: x64
Version: 10.0.40219.325

Direct Download URL: https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x64.exe

Microsoft Visual C++ 2010 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\1D5E3C0FEDA1E123187686FED06E995A 
Configuration: x86
Version: 10.0.40219.325

Direct Download URL: https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x86.exe


Visual C++ 2012

Microsoft Visual C++ 2012 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{ca67548a-5ebe-413a-b50c-4b9ceb6d66c6} 
Configuration: x64
Version: 11.0.61030.0

Direct Download URL: https://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x64.exe

Microsoft Visual C++ 2012 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{33d1fd90-4274-48a1-9bc1-97e33d9c2d6f} 
Configuration: x86
Version: 11.0.61030.0

Direct Download URL: https://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x86.exe

version caveat: Per user Wai Ha Lee's findings, "...the binaries that come with VC++ 2012 update 4 (11.0.61030.0) have version 11.0.60610.1 for the ATL and MFC binaries, and 11.0.51106.1 for everything else, e.g. msvcp110.dll and msvcr110.dll..."


Visual C++ 2013

Microsoft Visual C++ 2013 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{050d4fc8-5d48-4b8f-8972-47c82c46020f} 
Configuration: x64
Version: 12.0.30501.0

Direct Download URL: https://download.microsoft.com/download/2/E/6/2E61CFA4-993B-4DD4-91DA-3737CD5CD6E3/vcredist_x64.exe

Microsoft Visual C++ 2013 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{f65db027-aff3-4070-886a-0d87064aabb1} 
Configuration: x86
Version: 12.0.30501.0

Direct Download URL: https://download.microsoft.com/download/2/E/6/2E61CFA4-993B-4DD4-91DA-3737CD5CD6E3/vcredist_x86.exe


Visual C++ 2015

Consider using the 2015-2019 bundle as an alternative

Microsoft Visual C++ 2015 Redistributable (x64) - 14.0.24215
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{d992c12e-cab2-426f-bde3-fb8c53950b0d}
Configuration: x64
Version: 14.0.24215.1

Direct Download URL: https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x64.exe

Microsoft Visual C++ 2015 Redistributable (x86) - 14.0.24215
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{e2803110-78b3-4664-a479-3611a381656a}
Configuration: x86
Version: 14.0.24215.1

Direct Download URL: https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x86.exe


Visual C++ 2017

Consider using the 2015-2019 bundle as an alternative

Caveat: There's either a new 2017 registry convention being used, or it hasn't been finalized, yet. As I'm guessing the upper-most keys of: [HKEY_CLASSES_ROOT\Installer\Dependencies\,,amd64,14.0,bundle] and [HKEY_CLASSES_ROOT\Installer\Dependencies\,,x86,14.0,bundle]

are subject to change, or at least have different nested GUIDs, I'm going to use list the key that ends with a GUID.

Microsoft Visual C++ 2017 Redistributable (x64) - 14.16.27012
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x64,amd64,14.16,bundle\Dependents\{427ada59-85e7-4bc8-b8d5-ebf59db60423}]
Configuration: x64
Version: 14.16.27012.6

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/9fbed7c7-7012-4cc0-a0a3-a541f51981b5/e7eec15278b4473e26d7e32cef53a34c/vc_redist.x64.exe

Microsoft Visual C++ 2017 Redistributable (x86) - 14.16.27012
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x86,x86,14.16,bundle\Dependents\{67f67547-9693-4937-aa13-56e296bd40f6}]
Configuration: x86
Version: 14.16.27012.6

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/d0b808a8-aa78-4250-8e54-49b8c23f7328/9c5e6532055786367ee61aafb3313c95/vc_redist.x86.exe


Visual C++ 2019 (2015-2019 bundle)

Caveat: There's another new registry convention being used for Visual C++ 2019. There also doesn't appear to be a standalone installer for Visual C++ 2019, only this bundle installer that is Visual C++ 2015 through 2019.

14.21.27702

Microsoft Visual C++ 2015-2019 Redistributable (x64) - 14.21.27702
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x64,amd64,14.21,bundle\Dependents\{f4220b74-9edd-4ded-bc8b-0342c1e164d8}]
Configuration: x64
Version: 14.21.27702  

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/9e04d214-5a9d-4515-9960-3d71398d98c3/1e1e62ab57bbb4bf5199e8ce88f040be/vc_redist.x64.exe

Microsoft Visual C++ 2015-2019 Redistributable (x86) - 14.21.27702
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x86,x86,14.21,bundle\Dependents\{49697869-be8e-427d-81a0-c334d1d14950}]
Configuration: x86
Version: 14.21.27702

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/c8edbb87-c7ec-4500-a461-71e8912d25e9/99ba493d660597490cbb8b3211d2cae4/vc_redist.x86.exe

14.22.27821

Microsoft Visual C++ 2015-2019 Redistributable (x86) - 14.22.27821
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x86,x86,14.22,bundle\Dependents\{5bfc1380-fd35-4b85-9715-7351535d077e}]
Configuration: x86
Version: 14.22.27821

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/0c1cfec3-e028-4996-8bb7-0c751ba41e32/1abed1573f36075bfdfc538a2af00d37/vc_redist.x86.exe

Microsoft Visual C++ 2015-2019 Redistributable (x86) - 14.22.27821
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x64,amd64,14.22,bundle\Dependents\{6361b579-2795-4886-b2a8-53d5239b6452}]
Configuration: x64
Version: 14.22.27821

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/cc0046d4-e7b4-45a1-bd46-b1c079191224/9c4042a4c2e6d1f661f4c58cf4d129e9/vc_redist.x64.exe


Changelog:
August 19th, 2019 -- Added a new version of 2015-2019 bundle version
June 13th, 2019 -- Added a new section for the 2015-2019 bundle version 14.21.27702 and added small notes to the 2015 and 2017 sections about considering the usage of the new bundle as an alternative.
December 14th, 2018 -- Updated MSVC2008 for Service Pack 1's 9.0.30729.6161 update per Jim Wolff's findings
November 27th, 2018 -- Updated info for MSVC2017 v. 14.16
September 12th, 2018 -- Added version caveat to 2012 Update 4 per Wai Ha Lee's findings
August 24th, 2018 -- Updated 2017's version for 14.15.26706, the updated Visual C++ dependencies packaged with VS 2017 15.8.1
May 16th, 2018 -- Updated 2017's version for 14.14.26405.0 as the new C++ 2017 entry
September 8th, 2017 -- Updated 2017's version for 14.11.25325.0 as the new Visual C++ 2017 entry
April 7th, 2017 -- Updated 2017's version of 14.10.25008.0 as the new Visual C++ 2017 entry
October 24th, 2016 -- Updated 2015's version info for 14.0.24215.1
August 18th, 2016 -- Updated 2015's version info for 14.0.24212
May 27th, 2016 -- Updated info for MSVC2015 Update 2

Please contact me here if any of these become outdated.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

How can I output UTF-8 from Perl?

You also want to say, that strings in your code are utf-8. See Why does modern Perl avoid UTF-8 by default?. So set not only PERL_UNICODE=SDAL but also PERL5OPT=-Mutf8.

How to add a TextView to LinearLayout in Android

for(int j=0;j<30;j++) {
    LinearLayout childLayout = new LinearLayout(MainActivity.this);
    LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
    childLayout.setLayoutParams(linearParams);

    TextView mType = new TextView(MainActivity.this);
    TextView mValue = new TextView(MainActivity.this);

    mType.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 1f));
    mValue.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 1f));

    mType.setTextSize(17);
    mType.setPadding(5, 3, 0, 3);
    mType.setTypeface(Typeface.DEFAULT_BOLD);
    mType.setGravity(Gravity.LEFT | Gravity.CENTER);

    mValue.setTextSize(16);
    mValue.setPadding(5, 3, 0, 3);
    mValue.setTypeface(null, Typeface.ITALIC);
    mValue.setGravity(Gravity.LEFT | Gravity.CENTER);

    mType.setText("111");
    mValue.setText("111");

    childLayout.addView(mValue, 0);
    childLayout.addView(mType, 0);

    linear.addView(childLayout);
}

How to post a file from a form with Axios

Add the file to a formData object, and set the Content-Type header to multipart/form-data.

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

setting multiple column using one update

UPDATE some_table 
   SET this_column=x, that_column=y 
   WHERE something LIKE 'them'

How can I make a list of lists in R?

As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:

> str(list_all)
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

And the most simple construction would be this:

> str(list(list(1, 2), list("a", "b")))
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

Recursively find files with a specific extension

find -name "*Robert*" \( -name "*.pdf" -o -name "*.jpg" \)

The -o repreents an OR condition and you can add as many as you wish within the braces. So this says to find all files containing the word "Robert" anywhere in their names and whose names end in either "pdf" or "jpg".

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

You can first insert data into blob field and then copy to text field with the folloing function

CREATE OR REPLACE FUNCTION blob2text() RETURNS void AS $$
Declare
    ref record;
    i integer;
Begin
    FOR ref IN SELECT id, blob_field FROM table LOOP

          --  find 0x00 and replace with space    
      i := position(E'\\000'::bytea in ref.blob_field);
      WHILE i > 0 LOOP
        ref.bob_field := set_byte(ref.blob_field, i-1, 20);
        i := position(E'\\000'::bytea in ref.blobl_field);
      END LOOP

    UPDATE table SET field = encode(ref.blob_field, 'escape') WHERE id = ref.id;
    END LOOP;

End; $$ LANGUAGE plpgsql; 

--

SELECT blob2text();

Auto code completion on Eclipse

You can also set auto completion to open automatically while typing.

Go to Preferences > Java > Editor > Content Assist and write .abcdefghijklmnopqrstuvwxyz in the Auto activation triggers for Java field.

See this question for more details.

Maximum concurrent Socket.IO connections

This article may help you along the way: http://drewww.github.io/socket.io-benchmarking/

I wondered the same question, so I ended up writing a small test (using XHR-polling) to see when the connections started to fail (or fall behind). I found (in my case) that the sockets started acting up at around 1400-1800 concurrent connections.

This is a short gist I made, similar to the test I used: https://gist.github.com/jmyrland/5535279

return query based on date

if you want to get items anywhere on that date you need to compare two dates

You can create two dates off of the first one like this, to get the start of the day, and the end of the day.

var startDate = new Date(); // this is the starting date that looks like ISODate("2014-10-03T04:00:00.188Z")

startDate.setSeconds(0);
startDate.setHours(0);
startDate.setMinutes(0);

var dateMidnight = new Date(startDate);
dateMidnight.setHours(23);
dateMidnight.setMinutes(59);
dateMidnight.setSeconds(59);

### MONGO QUERY

var query = {
        inserted_at: {
                    $gt:morning,
                    $lt:dateScrapedMidnight
        }
};

//MORNING: Sun Oct 12 2014 00:00:00 GMT-0400 (EDT)
//MIDNIGHT: Sun Oct 12 2014 23:59:59 GMT-0400 (EDT)

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

HTML

<form id="some_form">
<!-- some form elements -->
</form>

and jquery

$("#some_form").reset();

How to check if an int is a null

A primitive int cannot be null. If you need null, use Integer instead.

Sending Windows key using SendKeys

download InputSimulator from nuget package.

then write this:

        var simu = new InputSimulator();
        simu.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);

in my case to create new vertial desktop, 3 keys needed and code like this(windows key + ctrl + D):

        simu.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL }, VirtualKeyCode.VK_D);

Change Schema Name Of Table In SQL

CREATE SCHEMA exe AUTHORIZATION [dbo]
GO

ALTER SCHEMA exe
TRANSFER dbo.Employees
GO

Android Google Maps v2 - set zoom level for myLocation

Location locaton;
double latitude = location.getlatitude;
double longitude = location.getlongitude;

If you want to save the zoom or get it all the time,you just need to call the following

int zoom = mMap.getCameraPosition().zoom;

//To set that just use

mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(getlatitude(), getlongitude),zoom);

What is the difference between Tomcat, JBoss and Glassfish?

jboss and glassfish include a servlet container(like tomcat), however the two application servers (jboss and glassfish) also provide a bean container (and a few other things aswell I imagine)

Extracting text from HTML file using Python

Best worked for me is inscripts .

https://github.com/weblyzard/inscriptis

import urllib.request
from inscriptis import get_text

url = "http://www.informationscience.ch"
html = urllib.request.urlopen(url).read().decode('utf-8')

text = get_text(html)
print(text)

The results are really good

Delete everything in a MongoDB database

I followed the db.dropDatabase() route for a long time, however if you're trying to use this for wiping the database in between test cases you may eventually find problems with index constraints not being honored after the database drop. As a result, you'll either need to mess about with ensureIndexes, or a simpler route would be avoiding the dropDatabase alltogether and just removing from each collection in a loop such as:

db.getCollectionNames().forEach(
  function(collection_name) {
    db[collection_name].remove()
  }
);

In my case I was running this from the command-line using:

mongo [database] --eval "db.getCollectionNames().forEach(function(n){db[n].remove()});"

Split string into array of characters?

Here's another way to do it in VBA.

Function ConvertToArray(ByVal value As String)
    value = StrConv(value, vbUnicode)
    ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
    Dim originalString As String
    originalString = "hi there"
    Dim myArray() As String
    myArray = ConvertToArray(originalString)
End Sub

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

In addition to others' proposals, there is another option to handle that issue.

If your application should behave the same in case of lack of "href" attribute, as in case of it being empty, just replace this:

var theHref = $(obj.mainImg_select).attr('href');

with this:

var theHref = $(obj.mainImg_select).attr('href') || '';

which will treat empty string ('') as the default, if the attribute has not been found.

But it really depends, on how you want to handle undefined "href" attribute. This answer assumes you will want to handle it as if it was empty string.

Force IE10 to run in IE10 Compatibility View?

I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

My thanks to Scott Hanselman for this fix.

Here is the link -

http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.

Rick

Allow anything through CORS Policy

I've your same requirements on a public API for which I used rails-api.

I've also set header in a before filter. It looks like this:

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

It seems you missed the Access-Control-Request-Method header.

Getting value of HTML Checkbox from onclick/onchange events

For React.js, you can do this with more readable code. Hope it helps.

handleCheckboxChange(e) {
  console.log('value of checkbox : ', e.target.checked);
}
render() {
  return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Not OP's answer but as this was the first question that popped up for me in google, Id also like to add that users searching for this might need to reseed their table, which was the case for me

DBCC CHECKIDENT(tablename)

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Misconception Common misconception with column ordering is that, I should (or could) do the pushing and pulling on mobile devices, and that the desktop views should render in the natural order of the markup. This is wrong.

Reality Bootstrap is a mobile first framework. This means that the order of the columns in your HTML markup should represent the order in which you want them displayed on mobile devices. This mean that the pushing and pulling is done on the larger desktop views. not on mobile devices view..

Brandon Schmalz - Full Stack Web Developer Have a look at full description here

How do I install PyCrypto on Windows?

For VS2010:

SET VS90COMNTOOLS=%VS100COMNTOOLS%

For VS2012:

SET VS90COMNTOOLS=%VS110COMNTOOLS%

then Call:

pip install pyCrypto 

Serving static web resources in Spring Boot & Spring Security application

i had the same issue with my spring boot application, so I thought it will be nice if i will share with you guys my solution. I just simply configure the antMatchers to be suited to specific type of filles. In my case that was only js filles and js.map. Here is a code:

   @Configuration
   @EnableWebSecurity
   public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
      .antMatchers("/index.html", "/", "/home", 
       "/login","/favicon.ico","/*.js","/*.js.map").permitAll()
      .anyRequest().authenticated().and().csrf().disable();
   }
  }

What is interesting. I find out that resources path like "resources/myStyle.css" in antMatcher didnt work for me at all. If you will have folder inside your resoruces folder just add it in antMatcher like "/myFolder/myFille.js"* and it should work just fine.

How to show the last queries executed on MySQL?

If mysql binlog is enabled you can check the commands ran by user by executing following command in linux console by browsing to mysql binlog directory

mysqlbinlog binlog.000001 >  /tmp/statements.sql

enabling

[mysqld]
log = /var/log/mysql/mysql.log

or general log will have an effect on performance of mysql

Where can I set environment variables that crontab will use?

Setting vars in /etc/environment also worked for me in Ubuntu. As of 12.04, variables in /etc/environment are loaded for cron.

Uploading Images to Server android

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);

ABOVE CODE TO SELECT IMAGE FROM GALLERY

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1)
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();

            String filePath = getPath(selectedImage);
            String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
            image_name_tv.setText(filePath);

            try {
                if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                    //FINE
                } else {
                    //NOT IN REQUIRED FORMAT
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

public String getPath(Uri uri) {
    String[] projection = {MediaColumns.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    column_index = cursor
            .getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    imagePath = cursor.getString(column_index);

    return cursor.getString(column_index);
}

NOW POST THE DATA USING MULTIPART FORM DATA

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");

Multipart FORM DATA

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
    File file = new File(filePath);
    Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
    Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
    mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}

FINALLY POST DATA TO SERVER

httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);

Uploading both data and files in one form using Ajax?

another option is to use an iframe and set the form's target to it.

you may try this (it uses jQuery):

function ajax_form($form, on_complete)
{
    var iframe;

    if (!$form.attr('target'))
    {
        //create a unique iframe for the form
        iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
        $form.attr('target', iframe.attr('name'));
    }

    if (on_complete)
    {
        iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
        iframe.load(function ()
        {
            //get the server response
            var response = iframe.contents().find('body').text();
            on_complete(response);
        });
    }
}

it works well with all browsers, you don't need to serialize or prepare the data. one down side is that you can't monitor the progress.

also, at least for chrome, the request will not appear in the "xhr" tab of the developer tools but under "doc"

Change Bootstrap input focus blue glow

You can use the .form-control selector to match all inputs. For example to change to red:

.form-control:focus {
  border-color: #FF0000;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}

Put it in your custom css file and load it after bootstrap.css. It will apply to all inputs including textarea, select etc...

error: Libtool library used but 'LIBTOOL' is undefined

A good answer for me was to install libtool:

sudo apt-get install libtool

Handle Guzzle exception and get HTTP body

if put 'http_errors' => false in guzzle request options, then it would stop throw exception while get 4xx or 5xx error, like this: $client->get(url, ['http_errors' => false]). then you parse the response, not matter it's ok or error, it would be in the response for more info

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

"SELECT Applicant.applicantId, Applicant.lastName, Applicant.firstName, Applicant.middleName, Applicant.status,Applicant.companyId, Company.name, Applicant.createDate FROM (Applicant INNER JOIN Company ON Applicant.companyId = Company.companyId) WHERE Applicant.createDate between  '" +dateTimePicker1.Text.ToString() + "'and '"+dateTimePicker2.Text.ToString() +"'";

this is what i did!!

Java: parse int value from a char

Try Character.getNumericValue(char).

String element = "el5";
int x = Character.getNumericValue(element.charAt(2));
System.out.println("x=" + x);

produces:

x=5

The nice thing about getNumericValue(char) is that it also works with strings like "el?" and "el?" where ? and ? are the digits 5 in Eastern Arabic and Hindi/Sanskrit respectively.

generate random string for div id

I really like this function:

function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

From Create GUID / UUID in JavaScript?

The entity type <type> is not part of the model for the current context

For me the issue was that I had not included the Entity Class within my db set inside the context for entity framework.

public DbSet<ModelName> ModelName { get; set; }

git: updates were rejected because the remote contains work that you do not have locally

you can use

git pull --rebase <your_reponame> <your_branch>

this will help incase you have some changes not yet registered on your local repo. especially README.md

Changing nav-bar color after scrolling?

window.addEventListener('scroll', function (e) {
        var nav = document.getElementById('nav');
        if (document.documentElement.scrollTop || document.body.scrollTop > window.innerHeight) {
                nav.classList.add('nav-colored');
                nav.classList.remove('nav-transparent');
            } else {
                nav.classList.add('nav-transparent');
                nav.classList.remove('nav-colored');
            }
    });

best approach to use event listener. especially for Firefox browser, check this doc Scroll-linked effects and Firefox is no longer support document.body.scrollTop and alternative to use document.documentElement.scrollTop. This is completes the answer from Yahya Essam

push multiple elements to array

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

Conversion from List<T> to array T[]

One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:

list.AsParallel().ToArray();

How do you check in python whether a string contains only numbers?

As every time I encounter an issue with the check is because the str can be None sometimes, and if the str can be None, only use str.isdigit() is not enough as you will get an error

AttributeError: 'NoneType' object has no attribute 'isdigit'

and then you need to first validate the str is None or not. To avoid a multi-if branch, a clear way to do this is:

if str and str.isdigit():

Hope this helps for people have the same issue like me.

C: What is the difference between ++i and i++?

Pre-crement means increment on the same line. Post-increment means increment after the line executes.

int j=0;
System.out.println(j); //0
System.out.println(j++); //0. post-increment. It means after this line executes j increments.

int k=0;
System.out.println(k); //0
System.out.println(++k); //1. pre increment. It means it increments first and then the line executes

When it comes with OR, AND operators, it becomes more interesting.

int m=0;
if((m == 0 || m++ == 0) && (m++ == 1)) { //false
/* in OR condition if first line is already true then compiler doesn't check the rest. It is technique of compiler optimization */
System.out.println("post-increment "+m);
}

int n=0;
if((n == 0 || n++ == 0) && (++n == 1)) { //true
System.out.println("pre-increment "+n); //1
}

In Array

System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 } ;
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); //12

jj = a[1]++; //12
System.out.println(a[1]); //a[1] = 13

mm = a[1];//13
System.out.printf ( "\n%d %d %d\n", ii, jj, mm ) ; //12, 12, 13

for (int val: a) {
     System.out.print(" " +val); //55, 13, 15, 20, 25
}

In C++ post/pre-increment of pointer variable

#include <iostream>
using namespace std;

int main() {

    int x=10;
    int* p = &x;

    std::cout<<"address = "<<p<<"\n"; //prints address of x
    std::cout<<"address = "<<p<<"\n"; //prints (address of x) + sizeof(int)
    std::cout<<"address = "<<&x<<"\n"; //prints address of x

    std::cout<<"address = "<<++&x<<"\n"; //error. reference can't re-assign because it is fixed (immutable)
}

How To Add An "a href" Link To A "div"?

Your solutions don't seem to be working for me, I have the following code. How to put link into the last two divs.

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">

<style>
/* Import */
@import url(https://fonts.googleapis.com/css?family=Quicksand:300,400);
* {
  font-family: "Quicksand", sans-serif; 
  font-weight: bold; 
  text-align: center;  
  text-transform: uppercase; 
  -webkit-transition: all 0.25s ease; 
  -moz-transition: all 0.25s ease; 
  -ms-transition: all 0.25s ease; 
  -o-transition: all 0.025s ease; 
}

/* Colors */

#ora {
  background-color: #e67e22; 
}

#red {
  background-color: #e74c3c; 
}

#orab {
  background-color: white; 
  border: 5px solid #e67e22; 
}

#redb {
  background-color: white; 
  border: 5px solid #e74c3c; 
}
/* End of Colors */

.B {
  width: 240px; 
  height: 55px; 
  margin: auto; 
  line-height: 45px; 
  display: inline-block; 
  box-sizing: border-box; 
  -webkit-box-sizing: border-box; 
  -moz-box-sizing: border-box; 
  -ms-box-sizing: border-box; 
  -o-box-sizing: border-box; 
} 

#orab:hover {
  background-color: #e67e22; 
}

#redb:hover {
  background-color: #e74c3c; 
}
#whib:hover {
  background-color: #ecf0f1; 
}

/* End of Border

.invert:hover {
  -webkit-filter: invert(1);
  -moz-filter: invert(1);
  -ms-filter: invert(1);
  -o-filter: invert(1);
}
</style>
<h1>Flat and Modern Buttons</h1>
<h2>Border Stylin'</h2> 

<div class="B bo" id="orab">See the movies list</div></a>
<div class="B bo" id="redb">Avail a free rental day</div>

</html>

What is the difference between a database and a data warehouse?

Database:

Used for Online Transactional Processing (OLTP).

  • Transaction-oriented.
  • Application oriented.
  • Current data.
  • Detailed data.
  • Scalable data.
  • Many Users, Administrators / Operational.
  • Execution time: short.

Data Warehouse:

Used for Online Analytical Processing (OLAP).

  • Oriented analysis.
  • Subject oriented.
  • Historical data.
  • Aggregated data.
  • Static data.
  • Not many users, manager.
  • Execution time: long.

What's the -practical- difference between a Bare and non-Bare repository?

5 years too late, I know, but no-one actually answered the question:

Then, why should I use the bare repository and why not? What's the practical difference? That would not be beneficial to more people working on a project, I suppose.

What are your methods for this kind of work? Suggestions?

To quote directly from the Loeliger/MCullough book (978-1-449-31638-9, p196/7):

A bare repository might seem to be of little use, but its role is crucial: to serve as an authoritative focal point for collaborative development. Other developers clone and fetch from the bare repository and push updates to it... if you set up a repository into which developers push changes, it should be bare. In effect, this is a special case of the more general best practice that a published repository should be bare.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Extending John Feminella answer:

Apple, Banana, Cherry implements FruitFactory and that has a method called Create which is solely responsible of creating Apple or Banana or Cherry. You're done, with your Factory method.

Now, you want to Create a special salad out of your fruits and there comes your Abstract Factory. Abstract Factory knows how to create your special Salad out of the Apple, Banana and Cherry.

public class Apple implements Fruit, FruitFactory {
    public Fruit Create() {
        // Apple creation logic goes here
    }
}

public class Banana implements Fruit, FruitFactory {
    public Fruit Create() {
        // Banana creation logic goes here
    }
}

public class Cherry implements Fruit, FruitFactory {
    public Fruit Create() {
        // Cherry creation logic goes here
    }
}

public class SpecialSalad implements Salad, SaladFactory {
    public static Salad Create(FruitFactory[] fruits) {
        // loop through the factory and create the fruits.
        // then you're ready to cut and slice your fruits 
        // to create your special salad.
    }
}

How to check if an item is selected from an HTML drop down list?

function check(selId) {
  var sel = document.getElementById(selId);
  var dropDown_sel = sel.options[sel.selectedIndex].text;
  if (dropDown_sel != "none") {

           state=1;

     //state is a Global variable initially it is set to 0
  } 
}


function checkstatevalue() {
      if (state==1) {
           return 1;
      } 
      return false;
    }

and html is for example

<form name="droptest" onSubmit="return checkstatevalue()">

<select id='Sel1' onchange='check("Sel1");'>
  <option value='junaid'>Junaid</option>
  <option value='none'>none</option>
  <option value='ali'>Ali</option>
</select>

</form>

Now when submitting a form first check what is the value of state if it is 0 it means that no item has been selected.

php - push array into array - key issue

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}


array_push == $res_arr_values[] = $row;

example 

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
?>

Merge (with squash) all changes from another branch as a single commit

Using git merge --squash <feature branch> as the accepted answer suggests does the trick but it will not show the merged branch as actually merged.

Therefore an even better solution is to:

  • Create a new branch from the latest master, commit in the master branch where the feature branch initiated.
  • Merge <feature branch> into the above using git merge --squash
  • Merge the newly created branch into master. This way, the feature branch will contain only one commit and the merge will be represented in a short and tidy illustration.

This wiki explains the procedure in detail.

In the following example, the left hand screenshot is the result of qgit and the right hand screenshot is the result of:

git log --graph --decorate --pretty=oneline --abbrev-commit

Both screenshots show the same range of commits in the same repository. Nonetheless, the right one is more compact thanks to --squash.

  • Over time, the master branch deviated from db.
  • When the db feature was ready, a new branch called tag was created in the same commit of master that db has its root.
  • From tag a git merge --squash db was performed and then all changes were staged and committed in a single commit.
  • From master, tag got merged: git merge tag.
  • The branch search is irrelevant and not merged in any way.

enter image description here

AngularJS - get element attributes values

Use Jquery functions

<Button id="myPselector" data-id="1234">HI</Button> 
console.log($("#myPselector").attr('data-id'));

How to display a JSON representation and not [Object Object] on the screen

<li *ngFor="let obj of myArray">{{obj | json}}</li>

Query to count the number of tables I have in MySQL

from command line :

mysql -uroot -proot  -e "select count(*) from 
information_schema.tables where table_schema = 'database_name';"

in above example root is username and password , hosted on localhost.

Call child component method from parent class - Angular

You can do this by using @ViewChild for more info check this link

With type selector

child component

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

parent component

@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild(ChildCmp) child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

With string selector

child component

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}

parent component

@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {

  @ViewChild('child') child:ChildCmp;

  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

Way to ng-repeat defined number of times instead of repeating over array?

This is really UGLY, but it works without a controller for either an integer or variable:

integer:

<span ng-repeat="_ in ((_ = []) && (_.length=33) && _) track by $index">{{$index}}</span>

variable:

<span ng-repeat="_ in ((_ = []) && (_.length=myVar) && _) track by $index">{{$index}}</span>

Create ArrayList from array

(old thread, but just 2 cents as none mention Guava or other libs and some other details)

If You Can, Use Guava

It's worth pointing out the Guava way, which greatly simplifies these shenanigans:

Usage

For an Immutable List

Use the ImmutableList class and its of() and copyOf() factory methods (elements can't be null):

List<String> il = ImmutableList.of("string", "elements");  // from varargs
List<String> il = ImmutableList.copyOf(aStringArray);      // from array

For A Mutable List

Use the Lists class and its newArrayList() factory methods:

List<String> l1 = Lists.newArrayList(anotherListOrCollection);    // from collection
List<String> l2 = Lists.newArrayList(aStringArray);               // from array
List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs

Please also note the similar methods for other data structures in other classes, for instance in Sets.

Why Guava?

The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methods allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.

But it's not the only reason (and Java 7 isn't everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.


If You Can't...

For an Immutable List

Use the JDK's Arrays class and its asList() factory method, wrapped with a Collections.unmodifiableList():

List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));
List<String> l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2"));

Note that the returned type for asList() is a List using a concrete ArrayList implementation, but it is NOT java.util.ArrayList. It's an inner type, which emulates an ArrayList but actually directly references the passed array and makes it "write through" (modifications are reflected in the array).

It forbids modifications through some of the List API's methods by way of simply extending an AbstractList (so, adding or removing elements is unsupported), however it allows calls to set() to override elements. Thus this list isn't truly immutable and a call to asList() should be wrapped with Collections.unmodifiableList().

See the next step if you need a mutable list.

For a Mutable List

Same as above, but wrapped with an actual java.util.ArrayList:

List<String> l1  = new ArrayList<String>(Arrays.asList(array));    // Java 1.5 to 1.6
List<String> l1b = new ArrayList<>(Arrays.asList(array));          // Java 1.7+
List<String> l2  = new ArrayList<String>(Arrays.asList("a", "b")); // Java 1.5 to 1.6
List<String> l2b = new ArrayList<>(Arrays.asList("a", "b"));       // Java 1.7+

For Educational Purposes: The Good ol' Manual Way

// for Java 1.5+
static <T> List<T> arrayToList(final T[] array) {
  final List<T> l = new ArrayList<T>(array.length);

  for (final T s : array) {
    l.add(s);
  }
  return (l);
}

// for Java < 1.5 (no generics, no compile-time type-safety, boo!)
static List arrayToList(final Object[] array) {
  final List l = new ArrayList(array.length);

  for (int i = 0; i < array.length; i++) {
    l.add(array[i]);
  }
  return (l);
}

Can I restore a single table from a full mysql mysqldump file?

One possible way to deal with this is to restore to a temporary database, and dump just that table from the temporary database. Then use the new script.

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

How to avoid the "Circular view path" exception with Spring MVC test

Another simple approach:

package org.yourpackagename;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

      @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(PreferenceController.class);
        }


    public static void main(String[] args) {
        SpringApplication.run(PreferenceController.class, args);
    }
}

Phonegap Cordova installation Windows

This answer was first posted here: cordova/phonegap does not make android directory

With the release of Cordova 3.3.0, it seems the PhoneGap team is trying to address the naming confusion. The documentations have been updated to recommend people using the cordova command instead. Do not use the phonegap command anymore.

Here is a fresh installation guide for a guaranteed trouble free set up:

  1. Install Cordova (forget the name PhoneGap from now on). For PC:

    C:> npm install -g cordova

  2. From command prompt, navigate to the folder you want to create your project using:

    cordova create hello com.example.hello HelloWorld
    cd hello

  3. Define the OS you want to suppport for example:

    cordova platform add wp8

  4. Install plugins (If needed). For example we want the following:

    cordova plugin add org.apache.cordova.device
    cordova plugin add org.apache.cordova.camera
    cordova plugin add org.apache.cordova.media-capture
    cordova plugin add org.apache.cordova.media
    

  5. Finally, generate the app using:
    cordova build wp8

Here is a link to the PhoneGapCordova 3.3.0 Documentation http://docs.phonegap.com/en/3.3.0/guide_cli_index.md.html#The%20Command-Line%20Interface

How to implement a lock in JavaScript

Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.

I suspect you need to just set a semaphore (flagging system) between your buttons.

Cannot load properties file from resources directory

Using ClassLoader.getSystemClassLoader()

Sample code :

Properties prop = new Properties();
InputStream input = null;
try {
    input = ClassLoader.getSystemClassLoader().getResourceAsStream("conf.properties");
    prop.load(input);

} catch (IOException io) {
    io.printStackTrace();
}

How do you change the value inside of a textfield flutter?

The problem with just setting

_controller.text = "New value";

is that the cursor will be repositioned to the beginning (in material's TextField). Using

_controller.text = "Hello";
_controller.selection = TextSelection.fromPosition(
    TextPosition(offset: _controller.text.length),
);
setState(() {});

is not efficient since it rebuilds the widget more than it's necessary (when setting the text property and when calling setState).

--

I believe the best way is to combine everything into one simple command:

final _newValue = "New value";
_controller.value = TextEditingValue(
      text: _newValue,
      selection: TextSelection.fromPosition(
        TextPosition(offset: _newValue.length),
      ),
    );

It works properly for both Material and Cupertino Textfields.

Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR: Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay.


Exception is the root of Ruby's exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError, LoadError, and Interrupt.

Rescuing Interrupt prevents the user from using CTRLC to exit the program.

Rescuing SignalException prevents the program from responding correctly to signals. It will be unkillable except by kill -9.

Rescuing SyntaxError means that evals that fail will do so silently.

All of these can be shown by running this program, and trying to CTRLC or kill it:

loop do
  begin
    sleep 1
    eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
  rescue Exception
    puts "I refuse to fail or be stopped!"
  end
end

Rescuing from Exception isn't even the default. Doing

begin
  # iceberg!
rescue
  # lifeboats
end

does not rescue from Exception, it rescues from StandardError. You should generally specify something more specific than the default StandardError, but rescuing from Exception broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.


If you have a situation where you do want to rescue from StandardError and you need a variable with the exception, you can use this form:

begin
  # iceberg!
rescue => e
  # lifeboats
end

which is equivalent to:

begin
  # iceberg!
rescue StandardError => e
  # lifeboats
end

One of the few common cases where it’s sane to rescue from Exception is for logging/reporting purposes, in which case you should immediately re-raise the exception:

begin
  # iceberg?
rescue Exception => e
  # do some logging
  raise # not enough lifeboats ;)
end

What is the official "preferred" way to install pip and virtualenv systemwide?

Starting from distro packages, you can either use:

sudo apt-get install python-virtualenv

which lets you create virtualenvs, or

sudo apt-get install python{,3}-pip

which lets you install arbitrary packages to your home directory.

If you're used to virtualenv, the first command gives you everything you need (remember, pip is bundled and will be installed in any virtualenv you create).

If you just want to install packages, the second command gives you what you need. Use pip like this:

pip install --user something

and put something like

PATH=~/.local/bin:$PATH

in your ~/.bashrc.


If your distro is ancient and you don't want to use its packages at all (except for Python itself, probably), you can download virtualenv, either as a tarball or as a standalone script:

wget -O ~/bin/virtualenv https://raw.github.com/pypa/virtualenv/master/virtualenv.py
chmod +x ~/bin/virtualenv

If your distro is more of the bleeding edge kind, Python3.3 has built-in virtualenv-like abilities:

python3 -m venv ./venv

This runs way faster, but setuptools and pip aren't included.

Arrays.asList() of an array

Arrays.asList(factors) returns a List<int[]>, not a List<Integer>. Since you're doing new ArrayList instead of new ArrayList<Integer> you don't get a compile error for that, but create an ArrayList<Object> which contains an int[] and you then implicitly cast that arraylist to ArrayList<Integer>. Of course the first time you try to use one of those "Integers" you get an exception.

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

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

The Unsupported major.minor version 51.0 error could mean:

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

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

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

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

for the latest version of the JRE and JDK respectively.

EDIT:

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

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

What is the best way to add a value to an array in state

For now, this is the best way.

this.setState(previousState => ({
    myArray: [...previousState.myArray, 'new value']
}));

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

Add class to <html> with Javascript?

Like this:

var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)

root.setAttribute( 'class', 'myCssClass' );

Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)

root.className += ' myCssClass';

Or, depending on the required browser support, you can use the classList.add() method:

root.classList.add('myCssClass');

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist

UPDATE:

A more elegant solution for referencing the HTML element might be this:

var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
//  root.classList.add('myCssClass');
//

How can I create a keystore?

Create keystore file from command line :

  1. Open Command line:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved
    
    // (if you want to store keystore file at C:/ open command line with RUN AS ADMINISTRATOR)
    
    C:\Windows\system32> keytool -genkey -v -keystore [your keystore file path]{C:/index.keystore} -alias [your_alias_name]{index} -keyalg RSA -keysize 2048 -validity 10000[in days]
    
  2. Enter > It will prompt you for password > enter password (it will be invisible)

    Enter keystore password:
    Re-enter new password:
    
  3. Enter > It will ask your detail.

    What is your first and last name?
     [Unknown]:  {AB} // [Your Name / Name of Signer] 
    What is the name of your organizational unit?
     [Unknown]:  {Self} // [Your Unit Name] 
    What is the name of your organization?
     [Unknown]:  {Self} // [Your Organization Name] 
    What is the name of your City or Locality?
     [Unknown]:  {INDORE} // [Your City Name] 
    What is the name of your State or Province?
     [Unknown]:  {MP} //[Your State] 
    What is the two-letter country code for this unit?
     [Unknown]:  91
    
  4. Enter > Enter Y

    Is CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91 correct?
    [no]:  Y
    
  5. Enter > Enter password again.

    Generating 2,048 bit RSA key pair and self-signed certificate    (SHA256withRSA) with a validity of 10,000 days
        for: CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91
    Enter key password for <index> (RETURN if same as keystore password):
    Re-enter new password:
    

[ Storing C:/index.keystore ]

  1. And your are DONE!!!

Export In Eclipse :

Export your android package to .apk with your created keystore file

  1. Right click on Package you want to export and select export enter image description here

  2. Select Export Android Application > Next enter image description here

  3. Next
    enter image description here

  4. Select Use Existing Keystore > Browse .keystore file > enter password > Next enter image description here

  5. Select Alias > enter password > Next enter image description here

  6. Browse APK Destination > Finish enter image description here

In Android Studio:

Create keystore [.keystore/.jks] in studio...

  1. Click Build (ALT+B) > Generate Signed APK...
    enter image description here

  2. Click Create new..(ALT+C)
    enter image description here

  3. Browse Key store path (SHIFT+ENTER) > Select Path > Enter name > OK enter image description here

  4. Fill the detail about your .jks/keystore file enter image description here

  5. Next
    enter image description here

  6. Your file
    enter image description here

  7. Enter Studio Master Password (You can RESET if you don't know) > OK enter image description here

  8. Select *Destination Folder * > Build Type

    release : for publish on app store
    debug : for debugging your application
    

    Click Finish

    enter image description here

Done !!!

How to determine whether a Pandas Column contains a particular value

Use

df[df['id']==x].index.tolist()

If x is present in id then it'll return the list of indices where it is present, else it gives an empty list.

How to add headers to OkHttp request interceptor?

This worked for me:

class JSONHeaderInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain) : Response {
        val request = chain.request().newBuilder()
            .header("Content-Type", "application/json")
            .build()
        return chain.proceed(request)
    }
}
fun provideHttpClient(): OkHttpClient {
    val okHttpClientBuilder = OkHttpClient.Builder()
    okHttpClientBuilder.addInterceptor(JSONHeaderInterceptor())
    return okHttpClientBuilder.build()
}

How can I close a login form and show the main form without my application closing?

Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program

Using filesystem in node.js with async / await

I have this little helping module that exports promisified versions of fs functions

const fs = require("fs");
const {promisify} = require("util")

module.exports = {
  readdir: promisify(fs.readdir),
  readFile: promisify(fs.readFile),
  writeFile: promisify(fs.writeFile)
  // etc...
};

Best way to convert string to bytes in Python 3?

Answer for a slightly different problem:

You have a sequence of raw unicode that was saved into a str variable:

s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"

You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)

s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'

Solution:

s_new: bytes = bytes(s, encoding="raw_unicode_escape")

Reference (scroll up for standard encodings):

Python Specific Encodings

Current time in microseconds in java

Here is an example of how to create an UnsignedLong current Timestamp:

UnsignedLong current = new UnsignedLong(new Timestamp(new Date().getTime()).getTime());

configure: error: C compiler cannot create executables

I just had this issue building apache. The solution I used was the same as Mostafa, I had to export 2 variables:

export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'

This was one Mac OSX Mavericks

How can I generate an ObjectId with mongoose?

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

Redirect non-www to www in .htaccess

Try this, I used it in many websites, it works perfectly

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^bewebdeveloper.com$
RewriteRule ^(.*) http://www.bewebdeveloper.com/$1  [QSA,L,R=301]

Alphabet range in Python

Print the Upper and Lower case alphabets in python using a built-in range function

def upperCaseAlphabets():
    print("Upper Case Alphabets")
    for i in range(65, 91):
        print(chr(i), end=" ")
    print()

def lowerCaseAlphabets():
    print("Lower Case Alphabets")
    for i in range(97, 123):
        print(chr(i), end=" ")

upperCaseAlphabets();
lowerCaseAlphabets();

C# Iterating through an enum? (Indexing a System.Array)

Array has a GetValue(Int32) method which you can use to retrieve the value at a specified index.

Array.GetValue

nodemon command is not recognized in terminal for node js server

Since node prefix is not in the PATH ENV variable , any of the globally installed modules are not getting recognized. Please try this. Open cmd prompt npm config get prefix append the resulting path to PATH env variable. Now you should be able to run nodemon from any location. try this link and follow it.fixing npm permissions https://docs.npmjs.com/getting-started/fixing-npm-permissions#option-2-change-npms-default-directory-to-another-directory

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

How can I combine multiple rows into a comma-delimited list in Oracle?

I needed a similar thing and found the following solution.

select RTRIM(XMLAGG(XMLELEMENT(e,country_name || ',')).EXTRACT('//text()'),',') country_name from  

How do I uninstall nodejs installed from pkg (Mac OS X)?

I ran:

lsbom -f -l -s -pf /var/db/receipts/org.nodejs.pkg.bom \
| while read i; do
  sudo rm /usr/local/${i}
done
sudo rm -rf /usr/local/lib/node \
     /usr/local/lib/node_modules \
     /var/db/receipts/org.nodejs.*

Coded into gist 2697848

Update It seems the receipts .bom file name may have changed so you may need to replace org.nodejs.pkg.bom with org.nodejs.node.pkg.bom in the above. The gist has been updated accordingly.

Convert a python UTC datetime to a local datetime using only python standard library?

The standard Python library does not come with any tzinfo implementations at all. I've always considered this a surprising shortcoming of the datetime module.

The documentation for the tzinfo class does come with some useful examples. Look for the large code block at the end of the section.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

Get Date::Manip from CPAN, then:

use Date::Manip;
$string = '18-Sep-2008 20:09'; # or a wide range of other date formats
$unix_time = UnixDate( ParseDate($string), "%s" );

edit:

Date::Manip is big and slow, but very flexible in parsing, and it's pure perl. Use it if you're in a hurry when you're writing code, and you know you won't be in a hurry when you're running it.

e.g. Use it to parse command line options once on start-up, but don't use it parsing large amounts of data on a busy web server.

See the authors comments.

(Thanks to the author of the first comment below)

Undefined Reference to

Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:

foo.h:

namespace foo {
    void bar();
}

foo.cc:

namespace foo {
    namespace {  // wrong
        void bar() { cout << "hello"; };
    }
}

other.cc file:

#include "foo.h"

void baz() {
    foo::bar();
}

How to position the form in the center screen?

i hope this will be helpful.

put this on the top of source code :

import java.awt.Toolkit;

and then write this code :

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    int lebar = this.getWidth()/2;
    int tinggi = this.getHeight()/2;
    int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar;
    int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi;
    this.setLocation(x, y);
}

good luck :)

Datetime BETWEEN statement not working in SQL Server

You need to convert the date field to varchar to strip out the time, then convert it back to datetime, this will reset the time to '00:00:00.000'.

SELECT *
FROM [TableName]
WHERE
    (
        convert(datetime,convert(varchar,GETDATE(),1)) 

        between 

        convert(datetime,convert(varchar,[StartDate],1)) 

        and  

        convert(datetime,convert(varchar,[EndDate],1))
    )

ERROR: Error 1005: Can't create table (errno: 121)

If you want to fix quickly, Forward Engineer again and check "Generate DROP SCHEMA" option and proceed.

I assume the database doesn't contain data, so dropping it won't affect.

Android Endless List

May be a little late but the following solution happened very useful in my case. In a way all you need to do is add to your ListView a Footer and create for it addOnLayoutChangeListener.

http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)

For example:

ListView listView1 = (ListView) v.findViewById(R.id.dialogsList); // Your listView
View loadMoreView = getActivity().getLayoutInflater().inflate(R.layout.list_load_more, null); // Getting your layout of FooterView, which will always be at the bottom of your listview. E.g. you may place on it the ProgressBar or leave it empty-layout.
listView1.addFooterView(loadMoreView); // Adding your View to your listview 

...

loadMoreView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
         Log.d("Hey!", "Your list has reached bottom");
    }
});

This event fires once when a footer becomes visible and works like a charm.

How to get a .csv file into R?

Since you say you want to access by position once your data is read in, you should know about R's subsetting/ indexing functions.

The easiest is

df[row,column]
#example
df[1:5,] #rows 1:5, all columns
df[,5] #all rows, column 5. 

Other methods are here. I personally use the dplyr package for intuitive data manipulation (not by position).

Check if a given key already exists in a dictionary

The ways in which you can get the results are:

Which is better is dependent on 3 things:

  1. Does the dictionary 'normally has the key' or 'normally does not have the key'.
  2. Do you intend to use conditions like if...else...elseif...else?
  3. How big is dictionary?

Read More: http://paltman.com/try-except-performance-in-python-a-simple-test/

Use of try/block instead of 'in' or 'if':

try:
    my_dict_of_items[key_i_want_to_check]
except KeyError:
    # Do the operation you wanted to do for "key not present in dict".
else:
    # Do the operation you wanted to do with "key present in dict."

How to jump to top of browser page

If you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Otherwise,

var scrollTop = function() {
    window.scrollTo(0, 0);
};

should do the trick.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

You should in fact do both, so that all browsers will find the icon.

Naming the file "favicon.ico" and putting it in the root of your website is the method "discouraged" by W3C:

Method 2 (Discouraged): Putting the favicon at a predefined URI
A second method for specifying a favicon relies on using a predefined URI to identify the image: "/favicon", which is relative to the server root. This method works because some browsers have been programmed to look for favicons using that URI.
W3C - How to add a favicon to your site

So, to cover all situations, I always do that in addition to the recommended method of adding a "rel" attribute and pointing it to the same .ico file.

MySQL/Writing file error (Errcode 28)

I had same problem but disk space was okay (only 40% full). Problem were inodes, I had too many small files and my inodes were full.

You can check inode status with df -i

Using Java to find substring of a bigger string using Regular Expression

I'd define that I want a maximum number of non-] characters between [ and ]. These need to be escaped with backslashes (and in Java, these need to be escaped again), and the definition of non-] is a character class, thus inside [ and ] (i.e. [^\\]]). The result:

FOO\\[([^\\]]+)\\]

How do I pass a value from a child back to the parent form?

If you are displaying child form as a modal dialog box, you can set DialogResult property of child form with a value from the DialogResult enumeration which in turn hides the modal dialog box, and returns control to the calling form. At this time parent can access child form's data to get the info that it need.

For more info check this link: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Open google-services.json in android studio we can see a json object, and contain following items in 'client' jsonarray

"client_id": "android:your package name", "package_name": "your package name",

Please verify your package and proceed.

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

Jenkins, specifying JAVA_HOME

For those of you coming to this issue and have access to configure your Jenkins Agents, you can set the JAVA_HOME from the Jenkins > Nodes > "the agent name" > Configure page:

Setting "per agent" environment variables

What do I do when my program crashes with exception 0xc0000005 at address 0?

Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

Replace \n with <br />

To handle many newline delimiters, including character combinations like \r\n, use splitlines (see this related post) use the following:

'<br />'.join(thatLine.splitlines())

How do I run Google Chrome as root?

First solution:
1. switch off Xorg access control: xhost +
2. Now start google chrome as normal user "anonymous" :
sudo -i -u anonymous /opt/google/chrome/chrome
3. When done browsing, re-enable Xorg access control:
xhost -
More info : Howto run google-chrome as root

Second solution:
1. Edit the file /opt/google/chrome/google-chrome
2. find exec -a "$0" "$HERE/chrome" "$@"
or exec -a "$0" "$HERE/chrome" "$PROFILE_DIRECTORY_FLAG" \ "$@"
3. change as
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir ”/root/.config/google-chrome”

Third solution:
Run Google Chrome Browser as Root on Ubuntu Linux systems

When is "java.io.IOException:Connection reset by peer" thrown?

It can also mean that the server is completely inaccessible - I was getting this when trying to hit a server that was offline

My client was configured to connect to localhost:3000, but no server was running on that port.

Django CSRF check failing with an Ajax POST request

If someone is strugling with axios to make this work this helped me:

import axios from 'axios';

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

Source: https://cbuelter.wordpress.com/2017/04/10/django-csrf-with-axios/

Conversion between UTF-8 ArrayBuffer and String

The main problem of programmers looking for conversion from byte array into a string is UTF-8 encoding (compression) of unicode characters. This code will help you:

var getString = function (strBytes) {

    var MAX_SIZE = 0x4000;
    var codeUnits = [];
    var highSurrogate;
    var lowSurrogate;
    var index = -1;

    var result = '';

    while (++index < strBytes.length) {
        var codePoint = Number(strBytes[index]);

        if (codePoint === (codePoint & 0x7F)) {

        } else if (0xF0 === (codePoint & 0xF0)) {
            codePoint ^= 0xF0;
            codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
            codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
            codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
        } else if (0xE0 === (codePoint & 0xE0)) {
            codePoint ^= 0xE0;
            codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
            codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
        } else if (0xC0 === (codePoint & 0xC0)) {
            codePoint ^= 0xC0;
            codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
        }

        if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || Math.floor(codePoint) != codePoint)
            throw RangeError('Invalid code point: ' + codePoint);

        if (codePoint <= 0xFFFF)
            codeUnits.push(codePoint);
        else {
            codePoint -= 0x10000;
            highSurrogate = (codePoint >> 10) | 0xD800;
            lowSurrogate = (codePoint % 0x400) | 0xDC00;
            codeUnits.push(highSurrogate, lowSurrogate);
        }
        if (index + 1 == strBytes.length || codeUnits.length > MAX_SIZE) {
            result += String.fromCharCode.apply(null, codeUnits);
            codeUnits.length = 0;
        }
    }

    return result;
}

All the best !

How do I find the width & height of a terminal window?

  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.

Deleting Objects in JavaScript

The delete command has no effect on regular variables, only properties. After the delete command the property doesn't have the value null, it doesn't exist at all.

If the property is an object reference, the delete command deletes the property but not the object. The garbage collector will take care of the object if it has no other references to it.

Example:

var x = new Object();
x.y = 42;

alert(x.y); // shows '42'

delete x; // no effect
alert(x.y); // still shows '42'

delete x.y; // deletes the property
alert(x.y); // shows 'undefined'

(Tested in Firefox.)

PHP cURL error code 60

The easiest solution to the problem is to add the below command in the field.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);

Using this will not need to add any certificate or anything.

How can I set the focus (and display the keyboard) on my EditText programmatically

Here is KeyboardHelper Class for hiding and showing keyboard

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by khanhamza on 06-Mar-17.
 */

public class KeyboardHelper {
public static void hideSoftKeyboard(final Context context, final View view) {
    if (context == null) {
        return;
    }
    view.requestFocus();
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}, 1000);
}

public static void hideSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}, 1000);
}


public static void openSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 1000);
}
}

Replacing blank values (white space) with NaN in pandas

I will did this:

df = df.apply(lambda x: x.str.strip()).replace('', np.nan)

or

df = df.apply(lambda x: x.str.strip() if isinstance(x, str) else x).replace('', np.nan)

You can strip all str, then replace empty str with np.nan.

jQuery scrollTop not working in Chrome but working in Firefox

Testing on Chrome, Firefox and Edge, the only solution that worked fine for me is using setTimeout with the solution of Aaron in this way:

setTimeout( function () {
    $('body, html').stop().animate({ scrollTop: 0 }, 100);
}, 500);

No one of the other solutions resetted the previuos scrollTop, when I reloaded the page, in Chrome and Edge for me. Unfortunately there is still a little "flick" in Edge.

How to get index in Handlebars each helper?

Arrays:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

If you have arrays of objects... you can iterate through the children:

{{#each array}}
    //each this = { key: value, key: value, ...}
    {{#each this}}
        //each key=@key and value=this of child object 
        {{@key}}: {{this}}
        //Or get index number of parent array looping
        {{@../index}}
    {{/each}}
{{/each}}

Objects:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

If you have nested objects you can access the key of parent object with {{@../key}}

How do I find the time difference between two datetime objects in python?

To just find the number of days: timedelta has a 'days' attribute. You can simply query that.

>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13

Print all key/value pairs in a Java ConcurrentHashMap

You can do something like

Iterator iterator = map.keySet().iterator();

while (iterator.hasNext()) {
   String key = iterator.next().toString();
   Integer value = map.get(key);

   System.out.println(key + " " + value);
}

Here 'map' is your concurrent HashMap.

Visual C++ executable and missing MSVCR100d.dll

Usually the application that misses the .dll indicates what version you need – if one does not work, simply download the Microsoft visual C++ 2010 x86 or x64 from this link:

For 32 bit OS:Here

For 64 bit OS:Here

How to convert WebResponse.GetResponseStream return into a string?

You can use StreamReader.ReadToEnd(),

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

How to write log to file

Building on Allison and Deepak's answer, I started using logrus and really like it:

var log = logrus.New()

func init() {

    // log to console and file
    f, err := os.OpenFile("crawler.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    wrt := io.MultiWriter(os.Stdout, f)

    log.SetOutput(wrt)
}

I have a defer f.Close() in the main function

Escape quote in web.config connection string

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

Since the web.config is XML, you need to escape the five special characters:

&amp; -> & ampersand, U+0026
&lt; -> < left angle bracket, less-than sign, U+003C
&gt; -> > right angle bracket, greater-than sign, U+003E
&quot; -> " quotation mark, U+0022
&apos; -> ' apostrophe, U+0027

+ is not a problem, I suppose.


Duc Filan adds: You should also wrap your password with single quote ':

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

How can I parse JSON with C#?

 using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(user)))
 {
    // Deserialization from JSON  
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UserListing))
    DataContractJsonSerializer(typeof(UserListing));
    UserListing response = (UserListing)deserializer.ReadObject(ms);

 }

 public class UserListing
 {
    public List<UserList> users { get; set; }      
 }

 public class UserList
 {
    public string FirstName { get; set; }       
    public string LastName { get; set; } 
 }

Twitter Bootstrap - add top space between rows

<div class="row row-padding">

simple code

Combining "LIKE" and "IN" for SQL Server

I know this is old but I got a kind of working solution

SELECT Tbla.* FROM Tbla
INNER JOIN Tblb ON
Tblb.col1 Like '%'+Tbla.Col2+'%'

You can expand it further with your where clause etc. I only answered this because this is what I was looking for and I had to figure out a way of doing it.

Why both no-cache and no-store should be used in HTTP response?

OWASP discusses this:

What's the difference between the cache-control directives: no-cache, and no-store?

The no-cache directive in a response indicates that the response must not be used to serve a subsequent request i.e. the cache must not display a response that has this directive set in the header but must let the server serve the request. The no-cache directive can include some field names; in which case the response can be shown from the cache except for the field names specified which should be served from the server. The no-store directive applies to the entire message and indicates that the cache must not store any part of the response or any request that asked for it.

Am I totally safe with these directives?

No. But generally, use both Cache-Control: no-cache, no-store and Pragma: no-cache, in addition to Expires: 0 (or a sufficiently backdated GMT date such as the UNIX epoch). Non-html content types like pdf, word documents, excel spreadsheets, etc often get cached even when the above cache control directives are set (although this varies by version and additional use of must-revalidate, pre-check=0, post-check=0, max-age=0, and s-maxage=0 in practice can sometimes result at least in file deletion upon browser closure in some cases due to browser quirks and HTTP implementations). Also, 'Autocomplete' feature allows a browser to cache whatever the user types in an input field of a form. To check this, the form tag or the individual input tags should include 'Autocomplete="Off" ' attribute. However, it should be noted that this attribute is non-standard (although it is supported by the major browsers) so it will break XHTML validation.

Source here.

Alternating Row Colors in Bootstrap 3 - No Table

You can use this code :

.row :nth-child(odd){
  background-color:red;
}
.row :nth-child(even){
  background-color:green;
}

Demo : http://codepen.io/mouhammed/pen/rblsC

How do you access the element HTML from within an Angular attribute directive?

So actually, my comment that you should do a console.log(el.nativeElement) should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element.

What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el) in your example, then you'll have access to the nativeElement object and will see a property called innerHTML.

Which will lead to the answer to your original question:

let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element

Update for better approach:

Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.

The best way to manipulate DOM Elements programmatically is using the Renderer:

constructor(private _elemRef: ElementRef, private _renderer: Renderer) { 
    this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}

Edit

Since Renderer is deprecated now, use Renderer2 instead with setProperty


Update:

This question with its answer explained the console.log behavior.

Which means that console.dir(el.nativeElement) would be the more direct way of accessing the DOM Element as an "inspectable" Object in your console for this situation.


Hope this helped.

Create Carriage Return in PHP String?

PHP_EOL returns a string corresponding to the line break on the platform(LF, \n ou #10 sur Unix, CRLF, \n\r ou #13#10 sur Windows).

echo "Hello World".PHP_EOL;

How do I print out the contents of an object in Rails for easy debugging?

I generally first try .inspect, if that doesn't give me what I want, I'll switch to .to_yaml.

class User
  attr_accessor :name, :age
end

user = User.new
user.name = "John Smith"
user.age = 30

puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith

Hope that helps.

Multiple REPLACE function in Oracle

The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE statements, and I don't think there is a better way.

If you are going to make heavy use of this, you could consider writing your own function:

CREATE TYPE t_text IS TABLE OF VARCHAR2(256);

CREATE FUNCTION multiple_replace(
  in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
  RETURN VARCHAR2
AS
  v_result VARCHAR2(32767);
BEGIN
  IF( in_old.COUNT <> in_new.COUNT ) THEN
    RETURN in_text;
  END IF;
  v_result := in_text;
  FOR i IN 1 .. in_old.COUNT LOOP
    v_result := REPLACE( v_result, in_old(i), in_new(i) );
  END LOOP;
  RETURN v_result;
END;

and then use it like this:

SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
                         NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
                         NEW t_text( 'text', 'tokens', 'replace' )
                       )
FROM dual

This is text with some tokens to replace

If all of your tokens have the same format ('#VAL' || i || '#'), you could omit parameter in_old and use your loop-counter instead.

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Using routes in Express-js

Seems that only index.js get loaded when you require("./routes") . I used the following code in index.js to load the rest of the routes:

var fs = require('fs')
  , path = require('path');

fs.readdirSync(__dirname).forEach(function(file){
  var route_fname = __dirname + '/' + file;
  var route_name = path.basename(route_fname, '.js');
  if(route_name !== 'index' && route_name[0] !== "."){ 
    exports[route_name] = require(route_fname)[route_name];
  }
});

Set selected item in Android BottomNavigationView

I hope this helps

//Setting default selected menu item and fragment
        bottomNavigationView.setSelectedItemId(R.id.action_home);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, new HomeFragment()).commit();

It is more of determining the default fragment loaded at the same time with the corresponding bottom navigation menu item. You can include the same in your OnResume callbacks

How do I display a wordpress page content?

This is more concise:

<?php echo get_post_field('post_content', $post->ID); ?>

and this even more:

<?= get_post_field('post_content', $post->ID) ?>

Check whether a variable is a string in Ruby

I think you are looking for instance_of?. is_a? and kind_of? will return true for instances from derived classes.

class X < String
end

foo = X.new

foo.is_a? String         # true
foo.kind_of? String      # true
foo.instance_of? String  # false
foo.instance_of? X       # true

How to empty the message in a text area with jquery?

for set empty all input such textarea select and input run this code:

$('#message').val('').change();

Missing Maven dependencies in Eclipse project

Below solution worked for me -
1- Go to project directory
2- run mvn eclipse:eclipse (Hope mvn is added in your path)
3- run mvn clean install

Refresh your project in Eclipse and check.

How to convert string to boolean in typescript Angular 4

Boolean("true") will do the work too

Java integer list

If you want to rewrite a line on console, print a control character \r (carriage return).

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = myCoords.iterator(); 
while (myListIterator.hasNext()) {
    Integer coord = myListIterator.next();     
    System.out.print("\r");
    System.out.print(coord);
    Thread.sleep(2000);
}

Twitter Bootstrap add active class to li

We managed to fix in the end:

/*menu handler*/
$(function(){
  function stripTrailingSlash(str) {
    if(str.substr(-1) == '/') {
      return str.substr(0, str.length - 1);
    }
    return str;
  }

  var url = window.location.pathname;  
  var activePage = stripTrailingSlash(url);

  $('.nav li a').each(function(){  
    var currentPage = stripTrailingSlash($(this).attr('href'));

    if (activePage == currentPage) {
      $(this).parent().addClass('active'); 
    } 
  });
});

Python: Continuing to next iteration in outer loop

Another way to deal with this kind of problem is to use Exception().

for ii in range(200):
    try:
        for jj in range(200, 400):
            ...block0...
            if something:
                raise Exception()
    except Exception:
        continue
    ...block1...

For example:

for n in range(1,4):
    for m in range(1,4):
        print n,'-',m

result:

    1-1
    1-2
    1-3
    2-1
    2-2
    2-3
    3-1
    3-2
    3-3

Assuming we want to jump to the outer n loop from m loop if m =3:

for n in range(1,4):
    try:
        for m in range(1,4):
            if m == 3:
                raise Exception()            
            print n,'-',m
    except Exception:
        continue

result:

    1-1
    1-2
    2-1
    2-2
    3-1
    3-2

Reference link:http://www.programming-idioms.org/idiom/42/continue-outer-loop/1264/python

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

const [name, setName] = useState()

generates error as soon as you type in the text field

const [name, setName] = useState('') // <-- by putting in quotes 

will fix the issue on this string example.

How to make a smaller RatingBar?

There is no need to add a listener to the ?android:attr/ratingBarStyleSmall. Just add android:isIndicator=false and it will capture click events, e.g.

<RatingBar
  android:id="@+id/myRatingBar"
  style="?android:attr/ratingBarStyleSmall"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:numStars="5"
  android:isIndicator="false" />

How to convert a std::string to const char* or char*?

Just see this:

string str1("stackoverflow");
const char * str2 = str1.c_str();

However, note that this will return a const char *.

For a char *, use strcpy to copy it into another char array.

PHP display current server path

php can call command line operations so

echo exec("pwd");

jQuery: select an element's class and id at the same time?

You can do:

$("#country.save")...

OR

$("a#country.save")...

OR

$("a.save#country")...

as you prefer.

So yes you can specify a selector that has to match ID and class (and potentially tag name and anything else you want to throw in).

Could not find method compile() for arguments Gradle

Wrong gradle file. The right one is build.gradle in your 'app' folder.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

SET @sql = 
CONCAT( 'INSERT INTO <table_name> (', 
    (
        SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') ) 
            FROM information_schema.columns 
            WHERE table_schema = <database_name>
                AND table_name = <table_name>
                AND column_name NOT IN ('id')
    ), ') SELECT ', 
    ( 
        SELECT GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`')) 
        FROM information_schema.columns 
        WHERE table_schema = <database_name>
            AND table_name = <table_source_name>
            AND column_name NOT IN ('id')  
    ),' from <table_source_name> WHERE <testcolumn> = <testvalue>' );  

PREPARE stmt1 FROM @sql; 
execute stmt1;

Of course replace <> values with real values, and watch your quotes.

Generate random int value from 3 to 6

Here is the simple and single line of code

For this use the SQL Inbuild RAND() function.

Here is the formula to generate random number between two number (RETURN INT Range)

Here a is your First Number (Min) and b is the Second Number (Max) in Range

SELECT FLOOR(RAND()*(b-a)+a)

Note: You can use CAST or CONVERT function as well to get INT range number.

( CAST(RAND()*(25-10)+10 AS INT) )

Example:

SELECT FLOOR(RAND()*(25-10)+10);

Here is the formula to generate random number between two number (RETURN DECIMAL Range)

SELECT RAND()*(b-a)+a;

Example:

SELECT RAND()*(25-10)+10;

More details check this: https://www.techonthenet.com/sql_server/functions/rand.php

dropping infinite values from dataframes in pandas?

The above solution will modify the infs that are not in the target columns. To remedy that,

lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

Make function wait until element exists

This will only work with modern browsers but I find it easier to just use a then so please test first but:

Code

function rafAsync() {
    return new Promise(resolve => {
        requestAnimationFrame(resolve); //faster than set time out
    });
}

function checkElement(selector) {
    if (document.querySelector(selector) === null) {
        return rafAsync().then(() => checkElement(selector));
    } else {
        return Promise.resolve(true);
    }
}

Or using generator functions

async function checkElement(selector) {
    const querySelector = null;
    while (querySelector === null) {
        await rafAsync();
        querySelector = document.querySelector(selector);
    }
    return querySelector;
}  

Usage

checkElement('body') //use whichever selector you want
.then((element) => {
     console.info(element);
     //Do whatever you want now the element is there
});

Map over object preserving keys

I think you want a mapValues function (to map a function over the values of an object), which is easy enough to implement yourself:

mapValues = function(obj, f) {
  var k, result, v;
  result = {};
  for (k in obj) {
    v = obj[k];
    result[k] = f(v);
  }
  return result;
};