Programs & Examples On #Sqlxml

SQLXML is a feature in MS SQL (introduced in SQL Server 2000), that enables XML support for making queries and processing data.

How to query values from xml nodes?

This works, been tested...

SELECT  n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',  
        n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM    Batches t
Cross   Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)  

How to query for Xml values and attributes from table in SQL Server?

I don't understand why some people are suggesting using cross apply or outer apply to convert the xml into a table of values. For me, that just brought back way too much data.

Here's my example of how you'd create an xml object, then turn it into a table.

(I've added spaces in my xml string, just to make it easier to read.)

DECLARE @str nvarchar(2000)

SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mike</firstName>'
SET @str = @str + '     <lastName>Gledhill</lastName>'
SET @str = @str + '     <age>31</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mark</firstName>'
SET @str = @str + '     <lastName>Stevens</lastName>'
SET @str = @str + '     <age>42</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Sarah</firstName>'
SET @str = @str + '     <lastName>Brown</lastName>'
SET @str = @str + '     <age>23</age>'
SET @str = @str + '  </user>'
SET @str = @str + '</users>'

DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML) 

--  Iterate through each of the "users\user" records in our XML
SELECT 
    x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
    x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
    x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)

And here's the output:

enter image description here

Can you issue pull requests from the command line on GitHub?

With the Hub command-line wrapper you can link it to git and then you can do git pull-request

From the man page of hub:

   git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
          Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one  of  the  following  formats:  "branch",  "owner:branch",
          "owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.

          If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.

          If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.

Keyboard shortcuts are not active in Visual Studio with Resharper installed

In Visual Studio: Tools -> Options -> Environment -> Keyboard -> Reset

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

Your password does not satisfy the current policy requirements

Set password that satisfies 7 MySql validation rules

eg:- d_VX>N("xn_BrD2y

Making validation criteria bit more simple will solve the issue

SET GLOBAL validate_password_length = 6;
SET GLOBAL validate_password_number_count = 0;

But recommended a Strong password is a correct solution

Resize Google Maps marker icon image

If you are using vue2-google-maps like me, the code to set the size looks like this:

<gmap-marker
  ..
  :icon="{
    ..
    anchor: { x: iconSize, y: iconSize },
    scaledSize: { height: iconSize, width: iconSize },
  }"
>

The process cannot access the file because it is being used by another process (File is created but contains nothing)

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

Where can I find the API KEY for Firebase Cloud Messaging?

You can open the project in the firebase, then you should click on the project overview, then goto project settings you will see the web API Key there.

enter image description here

Order columns through Bootstrap4

This can also be achieved with the CSS "Order" property and a media query.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

Removing the title text of an iOS UIBarButtonItem

Non of the answers helped me. But a trick did - I just cleared the title of the view controller that pushed (where the back button is going to) just before pushing it.

So when the previous view doesn't have a title, on iOS 7 the back button will only have an arrow, without text.

On viewWillAppear of the pushing view, I placed back the original title.

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

To create both of the created_at and updated_at columns:

$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

You will need MySQL version >= 5.6.5 to have multiple columns with CURRENT_TIMESTAMP

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

This error can also occur in the normal situation when a database is starting or stopping. Normally on startup you can wait until the startup completes, then connect as usual. If the error persists, the service (on a Windows box) may be started without the database being started. This may be due to startup issues, or because the service is not configured to automatically start the database. In this case you will have to connect as sysdba and physically start the database using the "startup" command.

How can I change the color of my prompt in zsh (different from normal text)?

To complement all of the above answers another convenient trick is to place the coloured prompt settings into a zsh function. There you may define local variables to alias longer commands, e.g. rc=$reset_color or define your own colour variables. Don't forget to place it into your .zshrc file and call the function you have defined:

# Coloured prompt
autoload -U colors && colors
function myprompt {
  local rc=$reset_color
  export PS1="%F{cyan}%n%{$rc%}@%F{green}%m%{$rc%}:%F{magenta}%~%{$rc%}%# "
}
myprompt

How to Insert Double or Single Quotes

To Create New Quoted Values from Unquoted Values

  • Column A contains the names.
  • Put the following formula into Column B = """" & A1 & """"
  • Copy Column B and Paste Special -> Values

Using a Custom Function

Public Function Enquote(cell As Range, Optional quoteCharacter As String = """") As Variant
    Enquote = quoteCharacter & cell.value & quoteCharacter
End Function

=OfficePersonal.xls!Enquote(A1)

=OfficePersonal.xls!Enquote(A1, "'")

To get permanent quoted strings, you will have to copy formula values and paste-special-values.

Recursive directory listing in DOS

I like to use the following to get a nicely sorted listing of the current dir:

> dir . /s /b sortorder:N

React this.setState is not a function

You just need to bind your event

for ex-

// place this code to your constructor

this._handleDelete = this._handleDelete.bind(this);

// and your setState function will work perfectly

_handleDelete(id){

    this.state.list.splice(id, 1);

    this.setState({ list: this.state.list });

    // this.setState({list: list});

}

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

How to delete Certain Characters in a excel 2010 cell

If [John Smith] is in cell A1, then use this formula to do what you want:

=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")

The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.

How can I explicitly free memory in Python?

You can't explicitly free memory. What you need to do is to make sure you don't keep references to objects. They will then be garbage collected, freeing the memory.

In your case, when you need large lists, you typically need to reorganize the code, typically using generators/iterators instead. That way you don't need to have the large lists in memory at all.

http://www.prasannatech.net/2009/07/introduction-python-generators.html

Sending string via socket (python)

This piece of code is incorrect.

while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    r='REceieve'
    clientsocket.send(r.encode())

The call on accept() on the serversocket blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.

That's the reason the recv works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.

Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.

Removing u in list

The u means the strings are unicode. Translate all the strings to ascii to get rid of it:

a.encode('ascii', 'ignore')

Changing factor levels with dplyr mutate

I'm not quite sure I understand your question properly, but if you want to change the factor levels of cyl with mutate() you could do:

df <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))

You would get:

#> str(df$cyl)
# Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...

Styling of Select2 dropdown select boxes

Thanks for the suggestions in the comments. I made a bit of a dirty hack to get what I want without having to create my own image. With javascript I first hide the default tag that's being used for the down arrow, like so:

$('b[role="presentation"]').hide();

I then included font-awesome in my page and add my own down arrow, again with a line of javascript, to replace the default one:

$('.select2-arrow').append('<i class="fa fa-angle-down"></i>');

Then with CSS I style the select boxes. I set the height, change the background color of the arrow area to a gradient black, change the width, font-size and also the color of the down arrow to white:

.select2-container .select2-choice {
    padding: 5px 10px;
    height: 40px;
    width: 132px; 
    font-size: 1.2em;  
}

.select2-container .select2-choice .select2-arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
}

The result is the styling the way I want it:

screenshot

Update 5/6/2015 As @Katie Lacy mentioned in the other answer the classnames have been changed in version 4 of Select2. The updated CSS with the new classnames should look like this:

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

JS:

$('b[role="presentation"]').hide();
$('.select2-selection__arrow').append('<i class="fa fa-angle-down"></i>');

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

Parse usable Street Address, City, State, Zip from a string

I've been working in the address processing domain for about 5 years now, and there really is no silver bullet. The correct solution is going to depend on the value of the data. If it's not very valuable, throw it through a parser as the other answers suggest. If it's even somewhat valuable you'll definitely need to have a human evaluate/correct all the results of the parser. If you're looking for a fully automated, repeatable solution, you probably want to talk to a address correction vendor like Group1 or Trillium.

Printing integer variable and string on same line in SQL

Numbers have higher precedence than strings so of course the + operators want to convert your strings into numbers before adding.

You could do:

print 'There are ' + CONVERT(varchar(10),@Number) +
      ' alias combinations did not match a record'

or use the (rather limited) formatting facilities of RAISERROR:

RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT

Git - push current branch shortcut

If you are using git 1.7.x, you can run the following command to set the remote tracking branch.

git branch --set-upstream feature/123-sandbox-tests origin/feature/123-sandbox-tests

Then you can simply use git push to push all the changes. For a more complete answer, please see the accepted answer to a similar question here.

If you only want to push the current branch with the push command, then you can change the push behaviour to upstream:

git config --global push.default upstream

Routing HTTP Error 404.0 0x80070002

My solution, after trying EVERYTHING:

Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.

My final settings that worked:

  • IIS 7.5, Win2k8r2 x64,
  • Integrated mode application pool
  • Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authentication mode="None"/>
    
      <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
      <httpRuntime requestPathInvalidCharacters=""/>
    
      <httpModules>
        <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
      </httpModules>
    </system.web>
      <system.webServer>
        <!-- Modules for IIS 7.0 Integrated mode -->
        <modules>
          <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
        </modules>
    
        <!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
        <validation validateIntegratedModeConfiguration="false" />
      </system.webServer>
    
  • Global.ashx: (only method of any note)

    void Application_Start(object sender, EventArgs e) {
        // Register routes...
        System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
              "{*message}",
            //the default value for the message
              new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
            //any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
              new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
              new TestRoute.Handlers.PassthroughRouteHandler()
           );
    
        System.Web.Routing.RouteTable.Routes.Add(echoRoute);
    }
    
  • PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:

    public class PassthroughRouteHandler : IRouteHandler {
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
            requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
            return null;
        }
    }
    

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

ComboBox SelectedItem vs SelectedValue

I suspect that the SelectedItem property of the ComboBox does not change until the control has been validated (which occurs when the control loses focus), whereas the SelectedValue property changes whenever the user selects an item.

Here is a reference to the focus events that occur on controls:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

matplotlib does not show my drawings although I call pyplot.show()

For me the problem happens if I simply create an empty matplotlibrc file under ~/.matplotlib on macOS. Adding "backend: macosx" in it fixes the problem.

I think it is a bug: if backend is not specified in my matplotlibrc it should take the default value.

How to pass command line arguments to a rake task

I just wanted to be able to run:

$ rake some:task arg1 arg2

Simple, right? (Nope!)

Rake interprets arg1 and arg2 as tasks, and tries to run them. So we just abort before it does.

namespace :some do
  task task: :environment do
    arg1, arg2 = ARGV

    # your task...

    exit
  end
end

Take that, brackets!

Disclaimer: I wanted to be able to do this in a pretty small pet project. Not intended for "real world" usage since you lose the ability to chain rake tasks (i.e. rake task1 task2 task3). IMO not worth it. Just use the ugly rake task[arg1,arg2].

Android Camera Preview Stretched

You must set cameraView.getLayoutParams().height and cameraView.getLayoutParams().width according to the aspect ratio you want.

Join two sql queries

Try this:

select Activity, SUM(Incomes.Amount) as "Total Amount 2009", SUM(Incomes2008.Amount) 
as "Total Amount 2008" from
Activities, Incomes, Incomes2008
where Activities.UnitName = ?  AND
Incomes.ActivityId = Activities.ActivityID  AND
Incomes2008.ActivityId = Activities.ActivityID GROUP BY
Activity ORDER BY Activity;

Basically you have to JOIN Incomes2008 table with the output of your first query.

If '<selector>' is an Angular component, then verify that it is part of this module

Hope you are having app.module.ts. In your app.module.ts add below line-

 exports: [myComponentComponent],

Like this:

import { NgModule, Renderer } from '@angular/core';
import { HeaderComponent } from './headerComponent/header.component';
import { HeaderMainComponent } from './component';
import { RouterModule } from '@angular/router';

@NgModule({
    declarations: [
        HeaderMainComponent,
        HeaderComponent
    ],
    imports: [
        RouterModule,
    ],
    providers: [],
    bootstrap: [HeaderMainComponent],
    exports: [HeaderComponent],
})
export class HeaderModule { }

Javascript .querySelector find <div> by innerTEXT

You could use this pretty simple solution:

Array.from(document.querySelectorAll('div'))
  .find(el => el.textContent === 'SomeText, text continues.');
  1. The Array.from will convert the NodeList to an array (there are multiple methods to do this like the spread operator or slice)

  2. The result now being an array allows for using the Array.find method, you can then put in any predicate. You could also check the textContent with a regex or whatever you like.

Note that Array.from and Array.find are ES2015 features. Te be compatible with older browsers like IE10 without a transpiler:

Array.prototype.slice.call(document.querySelectorAll('div'))
  .filter(function (el) {
    return el.textContent === 'SomeText, text continues.'
  })[0];

How to clear/remove observable bindings in Knockout.js?

I have to call ko.applyBinding each time search button click, and filtered data is return from server, and in this case following work for me without using ko.cleanNode.

I experienced, if we replace foreach with template then it should work fine in case of collections/observableArray.

You may find this scenario useful.

<ul data-bind="template: { name: 'template', foreach: Events }"></ul>

<script id="template" type="text/html">
    <li><span data-bind="text: Name"></span></li>
</script>

SQL how to make null values come last when sorting ascending

(A "bit" late, but this hasn't been mentioned at all)

You didn't specify your DBMS.

In standard SQL (and most modern DBMS like Oracle, PostgreSQL, DB2, Firebird, Apache Derby, HSQLDB and H2) you can specify NULLS LAST or NULLS FIRST:

Use NULLS LAST to sort them to the end:

select *
from some_table
order by some_column DESC NULLS LAST

Bootstrap 3: how to make head of dropdown link clickable in navbar

Alternatively here's a simple jQuery solution:

$('#menu-main > li > .dropdown-toggle').click(function () {
    window.location = $(this).attr('href');
});

Click toggle with jQuery

Another alternative solution to toggle checkbox value:

<div id="parent">
    <img src="" class="avatar" />
    <input type="checkbox" name="" />
</div>


$("img.avatar").click(function(){

    var op = !$(this).parent().find(':checkbox').attr('checked');
    $(this).parent().find(':checkbox').attr('checked', op);

});

Wrapping a react-router Link in an html button

LinkButton component - a solution for React Router v4

First, a note about many other answers to this question.

?? Nesting <button> and <a> is not valid html. ??

Any answer here which suggests nesting a html button in a React Router Link component (or vice-versa) will render in a web browser, but it is not semantic, accessible, or valid html:

<a stuff-here><button>label text</button></a>
<button><a stuff-here>label text</a></button>

?Click to validate this markup with validator.w3.org ?

This can lead to layout/styling issues as buttons are not typically placed inside links.


Using an html <button> tag with React Router <Link> component.

If you only want an html button tag…

<button>label text</button>

…then, here's the right way to get a button that works like React Router’s Link component…

Use React Router’s withRouter HOC to pass these props to your component:

  • history
  • location
  • match
  • staticContext

LinkButton component

Here’s a LinkButton component for you to copy/pasta:

// file: /components/LinkButton.jsx
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

const LinkButton = (props) => {
  const {
    history,
    location,
    match,
    staticContext,
    to,
    onClick,
    // ? filtering out props that `button` doesn’t know what to do with.
    ...rest
  } = props
  return (
    <button
      {...rest} // `children` is just another prop!
      onClick={(event) => {
        onClick && onClick(event)
        history.push(to)
      }}
    />
  )
}

LinkButton.propTypes = {
  to: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired
}

export default withRouter(LinkButton)

Then import the component:

import LinkButton from '/components/LinkButton'

Use the component:

<LinkButton to='/path/to/page'>Push My Buttons!</LinkButton>

If you need an onClick method:

<LinkButton
  to='/path/to/page'
  onClick={(event) => {
    console.log('custom event here!', event)
  }}
>Push My Buttons!</LinkButton>

Update: If you're looking for another fun option made available after the above was written, check out this useRouter hook.

How to install maven on redhat linux

Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file

Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:

wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz

And then proceed to install it.

UPDATE: Adding complete instructions (copied from the comment below)

  1. Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  2. run the following to extract the tar:

    tar xvf apache-maven-3.2.1-bin.tar.gz
    
  3. Next add the env varibles such as

    export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1

    export M2=$M2_HOME/bin

    export PATH=$M2:$PATH

  4. Verify

    mvn -version
    

CSS selector for "foo that contains bar"?

No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.

Here are some similar questions with similar results:

Bash checking if string does not contain other string

Use !=.

if [[ ${testmystring} != *"c0"* ]];then
    # testmystring does not contain c0
fi

See help [[ for more information.

Restricting input to textbox: allowing only numbers and decimal point

If you want it for float values,

Here is the function I am using

_x000D_
_x000D_
<HTML>_x000D_
_x000D_
<HEAD>_x000D_
  <SCRIPT language=Javascript>_x000D_
    <!--_x000D_
    function check(e, value) {_x000D_
      //Check Charater_x000D_
      var unicode = e.charCode ? e.charCode : e.keyCode;_x000D_
      if (value.indexOf(".") != -1)_x000D_
        if (unicode == 46) return false;_x000D_
      if (unicode != 8)_x000D_
        if ((unicode < 48 || unicode > 57) && unicode != 46) return false;_x000D_
    }_x000D_
    //-->_x000D_
  </SCRIPT>_x000D_
</HEAD>_x000D_
_x000D_
<BODY>_x000D_
  <INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">_x000D_
</BODY>_x000D_
_x000D_
</HTML>
_x000D_
_x000D_
_x000D_

Explanation of the UML arrows

If you are more of a MOOC person, one free course that I'd recommend that teaches you all the in and outs of most UML diagrams is this one from Udacity: https://www.udacity.com/course/software-architecture-design--ud821

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

Update:

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

Older info: Python 3.7 and prior

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

Pronouncement on prod()

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

Alternative with reduce()

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

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

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

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

Specific case: Factorials

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

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

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

>>> from math import log, exp

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

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

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

React.createElement: type is invalid -- expected a string

It means your import/export is incorrect.

  • Check newly added import/exports.
  • In my case I was using curly brackets unnecessary. Issue got resolved automatically when I removed these curly brackets.
import { OverlayTrigger } from 'react-bootstrap/OverlayTrigger';

What does HTTP/1.1 302 mean exactly?

A simple way of looking at HTTP 301 vs. 302 redirects is:

Suppose you have a bookmark to "http://sample.com/sample". You use a browser to go there.

A 302 redirect to a different URL at this point would mean that you should keep your bookmark to "http://sample.com/sample". This is because the destination URL may change in the future.

A 301 redirect to a different URL would mean that your bookmark should change to point to the new URL as it is a permanent redirect.

How do I refresh a DIV content?

You can use jQuery to achieve this using simple $.get method. .html work like innerHtml and replace the content of your div.

$.get("/YourUrl", {},
      function (returnedHtml) {
      $("#here").html(returnedHtml);
});

And call this using javascript setInterval method.

Trigger to fire only if a condition is met in SQL Server

Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.

When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)

Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.

Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.

AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)

CURRENT_DATE/CURDATE() not working as default DATE value

----- 2016-07-04 MariaDB 10.2.1 -- Release Note -- -----

Support for DEFAULT with expressions (MDEV-10134).

----- 2018-10-22 8.0.13 General Availability -- -- -----

MySQL now supports use of expressions as default values in data type specifications. This includes the use of expressions as default values for the BLOB, TEXT, GEOMETRY, and JSON data types, which previously could not be assigned default values at all. For details, see Data Type Default Values.

Laravel - Form Input - Multiple select for a one to many relationship

Laravel 4.2

@SamMonk gave the best alternative, I followed his example and build the final piece of code

<select class="chosen-select" multiple="multiple" name="places[]" id="places">
    @foreach($places as $place)
        <option value="{{$place->id}}" @foreach($job->places as $p) @if($place->id == $p->id)selected="selected"@endif @endforeach>{{$place->name}}</option>
    @endforeach
</select>

In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php

// app/start/global.php
require app_path().'/macros.php';

// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){

    // For empty Input::old($name) session, $selected is an empty string
    if(!$selected) $selected = array();

    $opts = array(
        'class' => 'chosen-select',
        'id' => $name,
        'name' => $name . '[]',
        'multiple' => true
    );
    $options = array_merge($opts, $options);
    $attributes = HTML::attributes($options);

    // need an empty array to send if all values are unselected
    $ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
    $ret .= '<select ' . $attributes . '>';
    foreach($defaults as $def) {
        $ret .= '<option value="' . $def->id . '"';
        foreach($selected as $p) {
            // session array or passed stdClass obj
            $current = @$p->id ? $p->id: $p;
            if($def->id == $current) {
                $ret .= ' selected="selected"';
            }
        }
        $ret .= '>' . HTML::entities($def->name) . '</option>';
    }
    $ret .= '</select>';
    return $ret;
});

Usage

List without pre-selected items (create view)

{{ Form::chosen('places', $places, Input::old('places')) }}

Preselections (edit view)

{{ Form::chosen('places', $places, $job->places) }}

Complete usage

{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}

When do items in HTML5 local storage expire?

The lifecycle is controlled by the application/user.

From the standard:

User agents should expire data from the local storage areas only for security reasons or when requested to do so by the user. User agents should always avoid deleting data while a script that could access that data is running.

How do I select an element that has a certain class?

h2.myClass refers to all h2 with class="myClass".

.myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

If you want the h2 in your HTML to appear blue, change the CSS to the following:

.myClass h2 {
    color: blue;
}

If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

Programmatically switching between tabs within Swift

Just to update, following iOS 13, we now have SceneDelegates. So one might choose to put the desired tab selection in SceneDelegate.swift as follows:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, 
               willConnectTo session: UISceneSession, 
               options connectionOptions: UIScene.ConnectionOptions) {

        guard let _ = (scene as? UIWindowScene) else { return }

        if let tabBarController = self.window!.rootViewController as? UITabBarController {
            tabBarController.selectedIndex = 1
        }

    }

Jquery bind double click and single click separately

i am implementing this simple solution , http://jsfiddle.net/533135/VHkLR/5/
html code

<p>Click on this paragraph.</p>
<b> </b>

script code

var dbclick=false;    
$("p").click(function(){
setTimeout(function(){
if(dbclick ==false){
$("b").html("clicked")
}

},200)

}).dblclick(function(){
dbclick = true
$("b").html("dbclicked")
setTimeout(function(){
dbclick = false


},300)
});


its not much laggy

Android Studio - How to Change Android SDK Path

I noticed that the latest version of Android Studio doesn't seem to have the option "SDKs" path that's mentioned in many of the answers. I'm guessing that disappeared in one of the updates, somewhere down the line?

The way i solved this issue (osx) was:

  1. Go to Project Settings (Cmd + ;)
  2. In SDK Location make sure you're pointing to the correct SDK location (typically /Applications/Android Studio.app/sdk) then hit Apply
  3. Most important step - hit "Sync Project with Gradle files"

I wasn't doing Step 3 and that was throwing me off. After a sync all your source r belong to us....

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

Log4j output not displayed in Eclipse console

The Eclipse Console Window has a Filter Property (in some cases only system.err is active).

Rigt click into Eclipse console window -> Preferences -> Console and ensure that checkbox

Show when Program writes to standard out

is active.

Alternatively you can configure log4j to write alway to System.err like this:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="AppConsole" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.err" />
        <param name="Encoding" value="ISO-8859-15" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{dd.MM.yyyy HH:mm:ss} %5p kontext.%c{1}:%L - %m%n" />
        </layout>
    </appender>
    <root>
        <level value="debug" />
        <appender-ref ref="AppConsole" />
    </root>
</log4j:configuration> 

Best XML parser for Java

I wouldn't recommended this is you've got a lot of "thinking" in your app, but using XSLT could be better (and potentially faster with XSLT-to-bytecode compilation) than Java manipulation.

Python argparse: default value or specified value

The difference between:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

myscript.py => debug is 7 (from default) in the first case and "None" in the second

myscript.py --debug => debug is 1 in each case

myscript.py --debug 2 => debug is 2 in each case

non static method cannot be referenced from a static context

You're trying to invoke an instance method on the class it self.

You should do:

    Random rand = new Random();
    int a = 0 ; 
    while (!done) { 
        int a = rand.nextInt(10) ; 
    ....

Instead

As I told you here stackoverflow.com/questions/2694470/whats-wrong...

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

How do I use JDK 7 on Mac OSX?

How about Netbeans, here is an article how to set it up with NB7:

http://netbeanside61.blogspot.com/2011/06/downloading-openjdk7-binary-for-mac-os.html

Maybe similar steps for Eclipse.

What do curly braces mean in Verilog?

As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]} are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".

{16{a[15]}}

is the same as

{ 
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}

In bit-blasted form,

assign result = {{16{a[15]}}, {a[15:0]}};

is the same as:

assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];

Spring Could not Resolve placeholder

If your config file is in a different path than classpath, you can add the configuration file path as a system property:

java -Dapp.config.path=path_to_config_file -jar your.jar

Using colors with printf

man printf.1 has a note at the bottom: "...your shell may have its own version of printf...". This question is tagged for bash, but if at all possible, I try to write scripts portable to any shell. dash is usually a good minimum baseline for portability - so the answer here works in bash, dash, & zsh. If a script works in those 3, it's most likely portable to just about anywhere.

The latest implementation of printf in dash[1] doesn't colorize output given a %s format specifier with an ANSI escape character \e -- but, a format specifier %b combined with octal \033 (equivalent to an ASCII ESC) will get the job done. Please comment for any outliers, but AFAIK, all shells have implemented printf to use the ASCII octal subset at a bare minimum.

To the title of the question "Using colors with printf", the most portable way to set formatting is to combine the %b format specifier for printf (as referenced in an earlier answer from @Vlad) with an octal escape \033.


portable-color.sh

#/bin/sh
P="\033["
BLUE=34
printf "-> This is %s %-6s %s text \n" $P"1;"$BLUE"m" "blue" $P"0m"
printf "-> This is %b %-6s %b text \n" $P"1;"$BLUE"m" "blue" $P"0m"

Outputs:

$ ./portable-color.sh
-> This is \033[1;34m blue   \033[0m text
-> This is  blue    text

...and 'blue' is blue in the second line.

The %-6s format specifier from the OP is in the middle of the format string between the opening & closing control character sequences.


[1] Ref: man dash Section "Builtins" :: "printf" :: "Format"

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

What's the difference between a method and a function?

In C++, sometimes, method is used to reflect the notion of member function of a class. However, recently I found a statement in the book «The C++ Programming Language 4th Edition», on page 586 "Derived Classes"

A virtual function is sometimes called a method.

This is a little bit confusing, but he said sometimes, so it roughly makes sense, C++ creator tends to see methods as functions can be invoked on objects and can behave polymorphic.

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

Android Horizontal RecyclerView scroll Direction

Horizontal RecyclerView with imageview and textview

xml file

main.xml

<LinearLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginTop="5dp"
   android:orientation="vertical"
   android:background="#070e94">
<View
    android:background="#787878"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    />
<android.support.v7.widget.RecyclerView
    android:id="@+id/wallet"
    android:background="#070e94"
    android:layout_width="match_parent"
    android:layout_height="100dp"/>

item.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_marginTop="5dp">
<ImageView
    android:id="@+id/image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:scaleType="fitXY"
    android:src="@drawable/bus"
    android:layout_gravity="center"/>
<TextView
    android:textColor="#000"
    android:textSize="12sp"
    android:layout_gravity="center"
    android:padding="5dp"
    android:id="@+id/txtView"
    android:textAlignment="center"
    android:hint="Electronics"
    android:layout_width="80dp"
    android:layout_height="wrap_content" />

Java Class

ActivityMaim.java

public class MainActivity extends AppCompatActivity{
private  RecyclerView  horizontal_recycler_view;
private ArrayList<Arraylist> horizontalList;
private CustomAdapter horizontalAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    horizontal_recycler_view= (RecyclerView) findViewById(R.id.horizontal_recycler_view);
    horizontalList = new ArrayList<Arraylist>();
    for (int i = 0; i < MyData.nameArray.length; i++) {
        horizontalList.add(new Arraylist(
                MyData.nameArray[i],
                MyData.drawableArray[i]
        ));
    }
    horizontalAdapter=new CustomAdapter(horizontalList);
    LinearLayoutManager horizontalLayoutManagaer
            = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
    horizontal_recycler_view.setLayoutManager(horizontalLayoutManagaer);
    horizontal_recycler_view.setAdapter(horizontalAdapter);
}}

Adaper Class

CustomAdapter.java

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

private ArrayList<Arraylist> dataSet;

public static class MyViewHolder extends RecyclerView.ViewHolder {

    TextView textViewName;

    ImageView imageViewIcon;

    public MyViewHolder(View itemView) {
        super(itemView);
        this.textViewName = (TextView) itemView.findViewById(R.id.txtView);
        //this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
        this.imageViewIcon = (ImageView) itemView.findViewById(R.id.image);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if (getPosition()==0)
                {
                    Toast.makeText(v.getContext(), " On CLick one", Toast.LENGTH_SHORT).show();

                } if (getPosition()==1)
                {
                    Toast.makeText(v.getContext(), " On CLick Two", Toast.LENGTH_SHORT).show();

                } if (getPosition()==2)
                {
                    Toast.makeText(v.getContext(), " On CLick Three", Toast.LENGTH_SHORT).show();

                } if (getPosition()==3)
                {
                    Toast.makeText(v.getContext(), " On CLick Fore", Toast.LENGTH_SHORT).show();

                }

            }
        });
    }
}

public CustomAdapter(ArrayList<Arraylist> data) {
    this.dataSet = data;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                       int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view, parent, false);

    //view.setOnClickListener(MainActivity.myOnClickListener);

    MyViewHolder myViewHolder = new MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {

    TextView textViewName = holder.textViewName;
   // TextView textViewVersion = holder.textViewVersion;
    ImageView imageView = holder.imageViewIcon;

    textViewName.setText(dataSet.get(listPosition).getName());
    //textViewVersion.setText(dataSet.get(listPosition).getVersion());
    imageView.setImageResource(dataSet.get(listPosition).getImage());
}

@Override
public int getItemCount() {
    return dataSet.size();
}}

Arraylist.java

public class Arraylist{
String name;
int image;

public Arraylist(String name, int image) {
    this.name = name;
    this.image=image;
}
public String getName() {
    return name;
}
public int getImage() {
    return image;
}}

MyData.java

public class MyData {
static String[] nameArray = {"Gas", "Insurance", "Electronics", "Other Services"};
static Integer[] drawableArray = {R.drawable.gas_gas, R.drawable.insurance, R.drawable.electric, R.drawable.services};}

How can I recursively find all files in current and subfolders based on wildcard matching?

Default way to search for recursive file, and available in most cases is

find . -name "filepattern"

It starts recursive traversing for filename or pattern from within current directory where you are positioned. With find command, you can use wildcards, and various switches, to see full list of options, type

man find

or if man pages aren't available at your system

find --help

However, there are more modern and faster tools then find, which are traversing your whole filesystem and indexing your files, one such common tool is locate or slocate/mlocate, you should check manual of your OS on how to install it, and once it's installed it needs to initiate database, if install script don't do it for you, it can be done manually by typing

sudo updatedb

And, to use it to look for some particular file type

locate filename

Or, to look for filename or patter from within current directory, you can type:

 pwd | xargs -n 1 -I {} locate "filepattern"

It will look through its database of files and quickly print out path names that match pattern that you have typed. To see full list of locate's options, type: locate --help or man locate

Additionally you can configure locate to update it's database on scheduled times via cron job, so sample cron which updates db at 1AM would look like:

0 1 * * * updatedb

These cron jobs need to be configured by root, since updatedb needs root privilege to traverse whole filesystem.

Preventing form resubmission

There are two parts to the answer:

  1. Ensure duplicate posts don't mess with your data on the server side. To do this, embed a unique identifier in the post so that you can reject subsequent requests server side. This pattern is called Idempotent Receiver in messaging terms.

  2. Ensure the user isn't bothered by the possibility of duplicate submits by both

    • redirecting to a GET after the POST (POST redirect GET pattern)
    • disabling the button using javascript

Nothing you do under 2. will totally prevent duplicate submits. People can click very fast and hackers can post anyway. You always need 1. if you want to be absolutely sure there are no duplicates.

Using continue in a switch statement

Yes, it's OK - it's just like using it in an if statement. Of course, you can't use a break to break out of a loop from inside a switch.

Search input with an icon Bootstrap 4

Here's a fairly simple way to achieve it by enclosing both the magnifying glass icon and the input field inside a div with relative positioning.

Absolute positioning is applied to the icon, which takes it out of the normal document layout flow. The icon is then positioned inside the input. Left padding is applied to the input so that the user's input appears to the right of the icon.

Note that this example places the magnifying glass icon on the left instead of the right. This is recommended when using <input type="search"> as Chrome adds an X button in the right side of the searchbox. If we placed the icon there it would overlay the X button and look fugly.

Here is the needed Bootstrap markup.

<div class="position-relative">
    <i class="fa fa-search position-absolute"></i>
    <input class="form-control" type="search">
</div>

...and a couple CSS classes for the things which I couldn't do with Bootstrap classes:

i {
    font-size: 1rem;
    color: #333;
    top: .75rem;
    left: .75rem
}

input {
    padding-left: 2.5rem;
}

You may have to fiddle with the values for top, left, and padding-left.

Call web service in excel

For an updated answer see this SO question:

calling web service using VBA code in excel 2010

Both threads should be merged though.

Can't run Curl command inside my Docker Container

curl: command not found

is a big hint, you have to install it with :

apt-get update; apt-get install curl

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

Remove/ truncate leading zeros by javascript/jquery

One another way without regex:

function trimLeadingZerosSubstr(str) {
    var xLastChr = str.length - 1, xChrIdx = 0;
    while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
        xChrIdx++;
    }
    return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}

With short string it will be more faster than regex (jsperf)

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

I tried install a lib that depends lxml and nothing works. I see a message when build was started: "Building without Cython", so after install cython with apt-get install cython, lxml was installed.

How to find out if you're using HTTPS without $_SERVER['HTTPS']

If your are using Apache you may always count on

$_SERVER["REQUEST_SCHEME"]

to verify the scheme of the URL requested. But, as mentioned in other answers, it is prudent to verify other parameters before assuming SSL is really being used.

How to make return key on iPhone make keyboard disappear?

Implement the UITextFieldDelegate method like this:

- (BOOL)textFieldShouldReturn:(UITextField *)aTextField
{
    [aTextField resignFirstResponder];
    return YES;
}

How to change the default GCC compiler in Ubuntu?

Now, there is gcc-4.9 available for Ubuntu/precise.

Create a group of compiler alternatives where the distro compiler has a higher priority:

root$ VER=4.6 ; PRIO=60
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

root$ VER=4.9 ; PRIO=40
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

NOTE: g++ version is changed automatically with a gcc version switch. cpp-bin has to be done separately as there exists a "cpp" master alternative.

List available compiler alternatives:

root$ update-alternatives --list gcc
root$ update-alternatives --list cpp-bin

To select manually version 4.9 of gcc, g++ and cpp, do:

root$ update-alternatives --config gcc
root$ update-alternatives --config cpp-bin

Check compiler versions:

root$ for i in gcc g++ cpp ; do $i --version ; done

Restore distro compiler settings (here: back to v4.6):

root$ update-alternatives --auto gcc
root$ update-alternatives --auto cpp-bin

How to send a JSON object over Request with Android?

Android doesn't have special code for sending and receiving HTTP, you can use standard Java code. I'd recommend using the Apache HTTP client, which comes with Android. Here's a snippet of code I used to send an HTTP POST.

I don't understand what sending the object in a variable named "jason" has to do with anything. If you're not sure what exactly the server wants, consider writing a test program to send various strings to the server until you know what format it needs to be in.

int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);

How to delete only the content of file in python

What could be easier than something like this:

import tempfile

for i in range(400):
    with tempfile.TemporaryFile() as tf:
        for j in range(1000):
            tf.write('Line {} of file {}'.format(j,i))

That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.

Using tempfile is a lot better than trying to reinvent it.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

If you want the sum of all bars to be equal unity, weight each bin by the total number of values:

weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)

Hope that helps, although the thread is quite old...

Note for Python 2.x: add casting to float() for one of the operators of the division as otherwise you would end up with zeros due to integer division

what is the difference between const_iterator and iterator?

if you have a list a and then following statements

list<int>::iterator it; // declare an iterator
    list<int>::const_iterator cit; // declare an const iterator 
    it=a.begin();
    cit=a.begin();

you can change the contents of the element in the list using “it” but not “cit”, that is you can use “cit” for reading the contents not for updating the elements.

*it=*it+1;//returns no error
    *cit=*cit+1;//this will return error

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Given an array of numbers, return array of products of all other numbers (no division)

public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4, 5 };
    int[] result = { 1, 1, 1, 1, 1 };
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < i; j++) {
            result[i] *= arr[j];

        }
        for (int k = arr.length - 1; k > i; k--) {
            result[i] *= arr[k];
        }
    }
    for (int i : result) {
        System.out.println(i);
    }
}

This solution i came up with and i found it so clear what do you think!?

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

Static Block in Java

It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.

From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

If you have a class with a static look-up map it could look like this

class MyClass {
    static Map<Double, String> labels;
    static {
        labels = new HashMap<Double, String>();
        labels.put(5.5, "five and a half");
        labels.put(7.1, "seven point 1");
    }
    //...
}

It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.

What is the convention in JSON for empty vs. null?

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

What is the difference between Left, Right, Outer and Inner Joins?

There are only 4 kinds:

  1. Inner join: The most common type. An output row is produced for every pair of input rows that match on the join conditions.
  2. Left outer join: The same as an inner join, except that if there is any row for which no matching row in the table on the right can be found, a row is output containing the values from the table on the left, with NULL for each value in the table on the right. This means that every row from the table on the left will appear at least once in the output.
  3. Right outer join: The same as a left outer join, except with the roles of the tables reversed.
  4. Full outer join: A combination of left and right outer joins. Every row from both tables will appear in the output at least once.

A "cross join" or "cartesian join" is simply an inner join for which no join conditions have been specified, resulting in all pairs of rows being output.

Thanks to RusselH for pointing out FULL joins, which I'd omitted.

Java 8 List<V> into Map<K, V>

Map<String, Set<String>> collect = Arrays.asList(Locale.getAvailableLocales()).stream().collect(Collectors
                .toMap(l -> l.getDisplayCountry(), l -> Collections.singleton(l.getDisplayLanguage())));

python capitalize first letter only

You can replace the first letter (preceded by a digit) of each word using regex:

re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')

output:
 1Bob 5Sandy

Improving bulk insert performance in Entity framework

In Azure environment with Basic website that has 1 Instance.I tried to insert a Batch of 1000 records at a time out of 25000 records using for loop it took 11.5 min but in parallel execution it took less than a minute.So I recommend using TPL(Task Parallel Library).

         var count = (you collection / 1000) + 1;
         Parallel.For(0, count, x =>
        {
            ApplicationDbContext db1 = new ApplicationDbContext();
            db1.Configuration.AutoDetectChangesEnabled = false;

            var records = members.Skip(x * 1000).Take(1000).ToList();
            db1.Members.AddRange(records).AsParallel();

            db1.SaveChanges();
            db1.Dispose();
        });

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

Read CSV file column by column

I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/

Here is one example:

    Path currentRelativePath = Paths.get("");
    String currentPath = currentRelativePath.toAbsolutePath().toString();
    String csvFile = currentPath + "/pathInYourProject/test.csv";

    Reader in;
    Iterable<CSVRecord> records = null;
    try
    {
        in = new FileReader(csvFile);
        records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    for (CSVRecord record : records) {
        String line = "";
        for ( int i=0; i < record.size(); i++)
        {
            if ( line == "" )
                line = line.concat(record.get(i));
            else
                line = line.concat("," + record.get(i));
        }
        System.out.println("read line: " + line);
    }

It automaticly recognize , and " but not ; (maybe it can be configured...).

My example file is:

col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"

And output is:

read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"

Last line is considered like one value.

How to make Regular expression into non-greedy?

You are right that greediness is an issue:

--A--Z--A--Z--
  ^^^^^^^^^^
     A.*Z

If you want to match both A--Z, you'd have to use A.*?Z (the ? makes the * "reluctant", or lazy).

There are sometimes better ways to do this, though, e.g.

A[^Z]*+Z

This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.

In your case, the regex would be:

/(\[[^\]]++\])/

Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:

/(\[[^\]]+\])/

See also


Quick summary

*   Zero or more, greedy
*?  Zero or more, reluctant
*+  Zero or more, possessive

+   One or more, greedy
+?  One or more, reluctant
++  One or more, possessive

?   Zero or one, greedy
??  Zero or one, reluctant
?+  Zero or one, possessive

Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m} constructs.

Examples in Java:

System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!"));  // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"

System.out.println("xxxxxx".replaceAll("x{3,5}", "Y"));  // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"

How to pass parameters or arguments into a gradle task

You should consider passing the -P argument in invoking Gradle.

From Gradle Documentation :

--project-prop Sets a project property of the root project, for example -Pmyprop=myvalue. See Section 14.2, “Gradle properties and system properties”.

Considering this build.gradle

task printProp << {
    println customProp
}

Invoking Gradle -PcustomProp=myProp will give this output :

$ gradle -PcustomProp=myProp printProp
:printProp
myProp

BUILD SUCCESSFUL

Total time: 3.722 secs

This is the way I found to pass parameters.

Linux Process States

Generally the process will block. If the read operation is on a file descriptor marked as non-blocking or if the process is using asynchronous IO it won't block. Also if the process has other threads that aren't blocked they can continue running.

The decision as to which process runs next is up to the scheduler in the kernel.

What are unit tests, integration tests, smoke tests, and regression tests?

Everyone will have slightly different definitions, and there are often grey areas. However:

  • Unit test: does this one little bit (as isolated as possible) work?
  • Integration test: do these two (or more) components work together?
  • Smoke test: does this whole system (as close to being a production system as possible) hang together reasonably well? (i.e. are we reasonably confident it won't create a black hole?)
  • Regression test: have we inadvertently re-introduced any bugs we'd previously fixed?

Jquery Ajax Loading image

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information

How to change column datatype in SQL database without losing data

Replace datatype without losing data

alter table tablename modify columnn  newdatatype(size);

How to generate unique ID with node.js

used https://www.npmjs.com/package/uniqid in npm

npm i uniqid

It will always create unique id's based on the current time, process and machine name.

  • With the current time the ID's are always unique in a single process.
  • With the Process ID the ID's are unique even if called at the same time from multiple processes.
  • With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

Features:-

  • Very fast
  • Generates unique id's on multiple processes and machines even if called at the same time.
  • Shorter 8 and 12 byte versions with less uniqueness.

How to create strings containing double quotes in Excel formulas?

will this work for macros using .Formula = "=THEFORMULAFUNCTION("STUFF")" so it would be like: will this work for macros using .Formula = "=THEFORMULAFUNCTION(CHAR(34) & STUFF & CHAR(34))"

SQL Query for Student mark functionality

 select max(m.mark)  as maxMarkObtained,su.Subname from Student s 
  inner join Marks m on s.Stid=m.Stid inner join [Subject] su on
  su.Subid=m.Subid group by su.Subname

I have execute it , this should work.

How to set python variables to true or false?

you have to use capital True and False not true and false

'too many values to unpack', iterating over a dict. key=>string, value=>list

You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)

>>> for field, values in fields.iteritems():
...     print field, values
... 
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']

Your problem was that you were looping over fields, which returns the keys of the dictionary.

>>> for field in fields:
...     print field
... 
first_names
last_name

SQL Server IN vs. EXISTS Performance

So, IN is not the same as EXISTS nor it will produce the same execution plan.

Usually EXISTS is used in a correlated subquery, that means you will JOIN the EXISTS inner query with your outer query. That will add more steps to produce a result as you need to solve the outer query joins and the inner query joins then match their where clauses to join both.

Usually IN is used without correlating the inner query with the outer query, and that can be solved in only one step (in the best case scenario).

Consider this:

  1. If you use IN and the inner query result is millions of rows of distinct values, it will probably perform SLOWER than EXISTS given that the EXISTS query is performant (has the right indexes to join with the outer query).

  2. If you use EXISTS and the join with your outer query is complex (takes more time to perform, no suitable indexes) it will slow the query by the number of rows in the outer table, sometimes the estimated time to complete can be in days. If the number of rows is acceptable for your given hardware, or the cardinality of data is correct (for example fewer DISTINCT values in a large data set) IN can perform faster than EXISTS.

  3. All of the above will be noted when you have a fair amount of rows on each table (by fair I mean something that exceeds your CPU processing and/or ram thresholds for caching).

So the ANSWER is it DEPENDS. You can write a complex query inside IN or EXISTS, but as a rule of thumb, you should try to use IN with a limited set of distinct values and EXISTS when you have a lot of rows with a lot of distinct values.

The trick is to limit the number of rows to be scanned.

Regards,

MarianoC

How to read the value of a private field from a different class in Java?

You need to do the following:

private static Field getField(Class<?> cls, String fieldName) {
    for (Class<?> c = cls; c != null; c = c.getSuperclass()) {
        try {
            final Field field = c.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (final NoSuchFieldException e) {
            // Try parent
        } catch (Exception e) {
            throw new IllegalArgumentException(
                    "Cannot access field " + cls.getName() + "." + fieldName, e);
        }
    }
    throw new IllegalArgumentException(
            "Cannot find field " + cls.getName() + "." + fieldName);
}

Angularjs: Get element in controller

$element is one of four locals that $compileProvider gives to $controllerProvider which then gets given to $injector. The injector injects locals in your controller function only if asked.

The four locals are:

  • $scope
  • $element
  • $attrs
  • $transclude

The official documentation: AngularJS $compile Service API Reference - controller

The source code from Github angular.js/compile.js:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

Invalid length parameter passed to the LEFT or SUBSTRING function

That would only happen if PostCode is missing a space. You could add conditionality such that all of PostCode is retrieved should a space not be found as follows

select SUBSTRING(PostCode, 1 ,
case when  CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode) 
else CHARINDEX(' ', PostCode) -1 end)

How to Get JSON Array Within JSON Object?

Solved, use array list of string to get name from Ingredients. Use below code:

JSONObject jsonObj = new JSONObject(jsonStr);

//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();

//loop to get all json objects from data json array
for(int i=0; i<length; i++){
    JSONObject jObj = ja_data.getJSONObject(i);
    Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
    // getting inner array Ingredients
    JSONArray ja = jObj.getJSONArray("Ingredients");
    int len = ja.length();
    ArrayList<String> Ingredients_names = new ArrayList<>();
    for(int j=0; j<len; j++){
        JSONObject json = ja.getJSONObject(j);
        Ingredients_names.add(json.getString("name"));
    }
}

Go back button in a page

Here is the code

<input type="button" value="Back" onclick="window.history.back()" /> 

How to save a git commit message from windows cmd?

You can also commit with git commit -m "Message goes here" That's easier.

Getting attribute of element in ng-click function in angularjs

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value;

Which would return exampleData.

Here's a full jsFiddle.

How to reload the current route with the angular 2 router

Very frustrating that Angular still doesn't seem to include a good solution for this. I have raised a github issue here: https://github.com/angular/angular/issues/31843

In the meantime, this is my workaround. It builds on some of the other solutions suggested above, but I think it's a little more robust. It involves wrapping the Router service in a "ReloadRouter", which takes care of the reload functionality and also adds a RELOAD_PLACEHOLDER to the core router configuration. This is used for the interim navigation and avoids triggering any other routes (or guards).

Note: Only use the ReloadRouter in those cases when you want the reload functionality. Use the normal Router otherwise.

import { Injectable } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class ReloadRouter {
  constructor(public readonly router: Router) {
    router.config.unshift({ path: 'RELOAD_PLACEHOLDER' });
  }

  public navigate(commands: any[], extras?: NavigationExtras): Promise<boolean> {
    return this.router
      .navigateByUrl('/RELOAD_PLACEHOLDER', {skipLocationChange: true})
      .then(() => this.router.navigate(commands, extras));
  }
}

Trim spaces from start and end of string

var word = " testWord ";   //add here word or space and test

var x = $.trim(word);

if(x.length > 0)
    alert('word');
else
    alert('spaces');

How to do HTTP authentication in android?

For me, it worked,

final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);

Apache HttpCLient:

request.setHeader("Authorization", basicAuth);

HttpUrlConnection:

connection.setRequestProperty ("Authorization", basicAuth);

Getting Java version at runtime

Just a note that in Java 9 and above, the naming convention is different. System.getProperty("java.version") returns "9" rather than "1.9".

jquery .html() vs .append()

Well, .html() uses .innerHTML which is faster than DOM creation.

How to exit a function in bash

Use:

return [n]

From help return

return: return [n]

Return from a shell function.

Causes a function or sourced script to exit with the return value
specified by N.  If N is omitted, the return status is that of the
last command executed within the function or script.

Exit Status:
Returns N, or failure if the shell is not executing a function or script.

Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))


if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)
    print(output)

JavaScript - get the first day of the week from current date

I'm using this

function get_next_week_start() {
   var now = new Date();
   var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
   return next_week_start;
}

Force LF eol in git repo and working copy

Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)

Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....

However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.

As you're partially working on Linux and Windows, make sure core.eol is set to native and core.autocrlf is set to true.

Then, replace the content of your .gitattributes file with the following

* text=auto

This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.

However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.

Provided you work on a C based image processing project, replace the content of your .gitattributes file with the following

* text=auto
*.txt text
*.c text
*.h text
*.jpg binary

This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.

In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.

As a real world example, you can also peek at this commit where those changes to a .gitattributes file are demonstrated.

UPDATE to the answer considering the following comment

I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory

Makes sense. Thanks for the clarification. In this specific context, the .gitattributes file by itself won't be enough.

Run the following commands against your repository

$ git config core.eol lf
$ git config core.autocrlf input

As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol will make sure text files bear LF line endings on checkouts. core.autocrlf will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.

Optionally, you can help Git distinguish what is a text file by creating a .gitattributes file containing something similar to the following:

# Autodetect text files
* text=auto

# ...Unless the name matches the following
# overriding patterns

# Definitively text files 
*.txt text
*.c text
*.h text

# Ensure those won't be messed up with
*.jpg binary
*.data binary

If you decided to create a .gitattributes file, commit it.

Lastly, ensure git status mentions "nothing to commit (working directory clean)", then perform the following operation

$ git checkout-index --force --all

This will recreate your files in your working directory, taking into account your config changes and the .gitattributes file and replacing any potential overlooked CRLF in your text files.

Once this is done, every text file in your working directory WILL bear LF line endings and git status should still consider the workdir as clean.

Convert numpy array to tuple

Here's a function that'll do it:

def totuple(a):
    try:
        return tuple(totuple(i) for i in a)
    except TypeError:
        return a

And an example:

>>> array = numpy.array(((2,2),(2,-2)))
>>> totuple(array)
((2, 2), (2, -2))

What regular expression will match valid international phone numbers?

This will work for international numbers;

C#:

@"^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$"

JS:

/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/

error: src refspec master does not match any

It happened to me and I discovered that github was trying to verify my account. So you need these 2 commands:

git config --global user.email <your github email>
git config --global user.name <your github username>

How to install ADB driver for any android device?

UNIVERSAL ADB DRIVER

I have thesame issue before but i solved it easily by just following this steps:

*connect your android phone in a debugging mode (to enable debugging mode goto settings scroll down About Phone scroll down tap seven times Build Number and it will automatically enable developer option turn on developer options and check USB debugging)

download Universal ADB Driver Installer

*choose Adb Driver Installer (Universal)

*install it *it will automatically detect your android device(any kind of brand) *chose the device and install

How can I selectively merge or pick changes from another branch in Git?

You can use read-tree to read or merge a given remote tree into the current index, for example:

git remote add foo [email protected]/foo.git
git fetch foo
git read-tree --prefix=my-folder/ -u foo/master:trunk/their-folder

To perform the merge, use -m instead.

See also: How do I merge a sub directory in Git?

How to get current memory usage in android?

I looked at Android Source Tree.

Inside com.android.server.am.ActivityManagerService.java (internal service exposed by android.app.ActivityManager).

public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
    final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
    final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
    outInfo.availMem = Process.getFreeMemory();
    outInfo.totalMem = Process.getTotalMemory();
    outInfo.threshold = homeAppMem;
    outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
    outInfo.hiddenAppThreshold = hiddenAppMem;
    outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
            ProcessList.SERVICE_ADJ);
    outInfo.visibleAppThreshold = mProcessList.getMemLevel(
            ProcessList.VISIBLE_APP_ADJ);
    outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
            ProcessList.FOREGROUND_APP_ADJ);
}

Inside android.os.Process.java

/** @hide */
public static final native long getFreeMemory();

/** @hide */
public static final native long getTotalMemory();

It calls JNI method from android_util_Process.cpp

Conclusion

MemoryInfo.availMem = MemFree + Cached in /proc/meminfo.

Notes

Total Memory is added in API level 16.

Oracle SQL escape character (for a '&')

The real answer is you need to set the escape character to '\': SET ESCAPE ON

The problem may have occurred either because escaping was disabled, or the escape character was set to something other than '\'. The above statement will enable escaping and set it to '\'.


None of the other answers previously posted actually answer the original question. They all work around the problem but don't resolve it.

Display all post meta keys and meta values of the same post ID in wordpress

To get all rows, don't specify the key. Try this:

$meta_values = get_post_meta( get_the_ID() );

var_dump( $meta_values );

Hope it helps!

Remove all constraints affecting a UIView

Details

  • Xcode 10.2.1 (10E1001), Swift 5

Solution

import UIKit

extension UIView {

    func removeConstraints() { removeConstraints(constraints) }
    func deactivateAllConstraints() { NSLayoutConstraint.deactivate(getAllConstraints()) }
    func getAllSubviews() -> [UIView] { return UIView.getAllSubviews(view: self) }

    func getAllConstraints() -> [NSLayoutConstraint] {
        var subviewsConstraints = getAllSubviews().flatMap { $0.constraints }
        if let superview = self.superview {
            subviewsConstraints += superview.constraints.compactMap { (constraint) -> NSLayoutConstraint? in
                if let view = constraint.firstItem as? UIView, view == self { return constraint }
                return nil
            }
        }
        return subviewsConstraints + constraints
    }

    class func getAllSubviews(view: UIView) -> [UIView] {
        return view.subviews.flatMap { [$0] + getAllSubviews(view: $0) }
    }
}

Usage

print("constraints: \(view.getAllConstraints().count), subviews: \(view.getAllSubviews().count)")
view.deactivateAllConstraints()

'MOD' is not a recognized built-in function name

In TSQL, the modulo is done with a percent sign.

SELECT 38 % 5 would give you the modulo 3

Reporting Services permissions on SQL Server R2 SSRS

This problem occurs because of UAC and only when you are running IE on the same computer SSRS is on.

To fix it, you have to add an AD group of the users with read priviledges to the actual SSRS website directories and push the security down. UAC is dumb in how if you are an admin on the box. It won't let you access the data unless you also have access to the data through other means such as a non-administrator AD group that is applied to the files.

In Python, how do I iterate over a dictionary in sorted key order?

If you want to sort by the order that items were inserted instead of of the order of the keys, you should have a look to Python's collections.OrderedDict. (Python 3 only)

Get the first element of an array

This is not so simple response in the real world. Suppose that we have these examples of possible responses that you can find in some libraries.

$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;

var_dump('reset1', reset($array1));
var_dump('reset2', reset($array2));
var_dump('reset3', reset($array3));
var_dump('reset4', reset($array4)); // Warning

var_dump('array_shift1', array_shift($array1));
var_dump('array_shift2', array_shift($array2));
var_dump('array_shift3', array_shift($array3));
var_dump('array_shift4', array_shift($array4)); // Warning

var_dump('each1', each($array1));
var_dump('each2', each($array2));
var_dump('each3', each($array3));
var_dump('each4', each($array4)); // Warning

var_dump('array_values1', array_values($array1)[0]); // Notice
var_dump('array_values2', array_values($array2)[0]);
var_dump('array_values3', array_values($array3)[0]);
var_dump('array_values4', array_values($array4)[0]); // Warning

var_dump('array_slice1', array_slice($array1, 0, 1));
var_dump('array_slice2', array_slice($array2, 0, 1));
var_dump('array_slice3', array_slice($array3, 0, 1));
var_dump('array_slice4', array_slice($array4, 0, 1)); // Warning

list($elm) = $array1; // Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);

Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.

In my opinion, you have should that handler only with arrays.

Now talking about performance, assuming that we have always array, like this:

$elm = empty($array) ? null : ...($array);

...you would use without errors:
$array[count($array)-1];
array_shift
reset
array_values
array_slice

array_shift is faster than reset, that is more fast than [count()-1], and these three are faster than array_values and array_slice.

Convert a object into JSON in REST service by Spring MVC

Finally I got solution using Jackson library along with Spring MVC. I got this solution from an example of Journal Dev( http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program )

So, the code changes I have done are:

  • Include the library in Maven.
  • Add JSON conversion Servlet into servlet-context.xml.
  • Change the Model into Serializable.

I didn't made any changes to my REST service controller. By default it converts into JSON.

Compare two files and write it to "match" and "nomatch" files

//STEP01   EXEC SORT90MB                        
//SORTJNF1 DD DSN=INPUTFILE1,   
//            DISP=SHR                          
//SORTJNF2 DD DSN=INPUTFILE2,   
//            DISP=SHR                          
//SORTOUT  DD DSN=MISMATCH_OUTPUT_FILE, 
//            DISP=(,CATLG,DELETE),             
//            UNIT=TAPE,                        
//            DCB=(RECFM=FB,BLKSIZE=0),         
//            DSORG=PS                          
//SYSOUT   DD SYSOUT=*                          
//SYSIN    DD *                                 
  JOINKEYS FILE=F1,FIELDS=(1,79,A)              
  JOINKEYS FILE=F2,FIELDS=(1,79,A)              
  JOIN UNPAIRED,F1,ONLY                         
  SORT FIELDS=COPY                              
/*                                              

How to generate a random integer number from within a range

For those who understand the bias problem but can't stand the unpredictable run-time of rejection-based methods, this series produces a progressively less biased random integer in the [0, n-1] interval:

r = n / 2;
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
...

It does so by synthesising a high-precision fixed-point random number of i * log_2(RAND_MAX + 1) bits (where i is the number of iterations) and performing a long multiplication by n.

When the number of bits is sufficiently large compared to n, the bias becomes immeasurably small.

It does not matter if RAND_MAX + 1 is less than n (as in this question), or if it is not a power of two, but care must be taken to avoid integer overflow if RAND_MAX * n is large.

Iterating over arrays in Python 3

The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:

When you iterate over it with for i in ar: the values of i will be 2, 4 and 6. So, when you try to access ar[i] for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.

If you intend to use indexes anyhow, try using for index, value in enumerate(ar):, then theSum = theSum + ar[index] should work just fine.

How do I tell Maven to use the latest version of a dependency?

Are you possibly depending on development versions that obviously change a lot during development?

Instead of incrementing the version of development releases, you could just use a snapshot version that you overwrite when necessary, which means you wouldn't have to change the version tag on every minor change. Something like 1.0-SNAPSHOT...

But maybe you are trying to achieve something else ;)

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

How can I remount my Android/system as read-write in a bash script using adb?

I could not get the mount command to work without specifying the dev block to mount as /system

#cat /proc/mounts returns ( only the system line here )
/dev/stl12 /system rfs ro,relatime,vfat,log_off,check=no,gid/uid/rwx,iocharset=utf8 0 0

so my working command is
mount -o rw,remount -t rfs /dev/stl12 /system

ERROR 1049 (42000): Unknown database

Its a common error which happens when we try to access a database which doesn't exist. So create the database using

CREATE DATABASE blog_development;

The error commonly occours when we have dropped the database using

DROP DATABASE blog_development;

and then try to access the database.

How to catch all exceptions in c# using try and catch?

I catch all the exceptions and store it in database, so errors can be corrected easily - the page, place, date etc stored

try
{     
   Cart = DB.BuyOnlineCartMasters.Where(c => c.CmpyID == LoginID && c.Active == true).FirstOrDefault();
}
catch (Exception e)
{
    ErrorReport.StoreError("CartMinifiedPartial-Company", e);  
    -- storing the error for reference
}

Storing

public static void StoreError(string ErrorPage, Exception e)
    {
        try
        {
            eDurar.Models.db_edurarEntities1 DB = new Models.db_edurarEntities1();
            eDurar.Models.ErrorTable Err = new eDurar.Models.ErrorTable();
            Err.ErrorPage = ErrorPage;
            if (e.Message != null)
            {
                Err.ErrorDetails = e.Message;
            }
            if (e.InnerException != null)
            {
                Err.InnerException = e.InnerException.Message.ToString();
            }

            Err.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
            DB.ErrorTables.AddObject(Err);
            DB.SaveChanges();
}

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

I suggest you do some experiments using "make". Here is a simple demo, showing the difference between = and :=.

/* Filename: Makefile*/
x := foo
y := $(x) bar
x := later

a = foo
b = $(a) bar
a = later

test:
    @echo x - $(x)
    @echo y - $(y)
    @echo a - $(a)
    @echo b - $(b)

make test prints:

x - later
y - foo bar
a - later
b - later bar

Check more elaborate explanation here

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The first error

java.lang.Exception; must be caught or declared to be thrown byte[] encrypted = encrypt(concatURL);

means that your encrypt method throws an exception that is not being handled or declared by the actionPerformed method where you are calling it. Read all about it at the Java Exceptions Tutorial.

You have a couple of choices that you can pick from to get the code to compile.

  • You can remove throws Exception from your encrypt method and actually handle the exception inside encrypt.
  • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.

It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.

The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt, as I mentioned before.

Test if remote TCP port is open from a shell script

This uses telnet behind the scenes, and seems to work fine on mac/linux. It doesn't use netcat because of the differences between the versions on linux/mac, and this works with a default mac install.

Example:

$ is_port_open.sh 80 google.com
OPEN

$ is_port_open.sh 8080 google.com
CLOSED

is_port_open.sh

PORT=$1
HOST=$2
TIMEOUT_IN_SEC=${3:-1}
VALUE_IF_OPEN=${4:-"OPEN"}
VALUE_IF_CLOSED=${5:-"CLOSED"}

function eztern()
{
  if [ "$1" == "$2" ]
  then
    echo $3
  else
    echo $4
  fi
}

# cross platform timeout util to support mac mostly
# https://gist.github.com/jaytaylor/6527607
function eztimeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }

function testPort()
{
  OPTS=""

  # find out if port is open using telnet
  # by saving telnet output to temporary file
  # and looking for "Escape character" response
  # from telnet
  FILENAME="/tmp/__port_check_$(uuidgen)"
  RESULT=$(eztimeout $TIMEOUT_IN_SEC telnet $HOST $PORT &> $FILENAME; cat $FILENAME | tail -n1)
  rm -f $FILENAME;
  SUCCESS=$(eztern "$RESULT" "Escape character is '^]'." "$VALUE_IF_OPEN" "$VALUE_IF_CLOSED")

  echo "$SUCCESS"
}

testPort 

Maintain the aspect ratio of a div with CSS

If you want to fit a square inside the viewport on either portrait or landscape view (as big as possible, but nothing sticking outside), switch between using vw/vh on orientation portrait/landscape:

@media (orientation:portrait ) {
  .square {
    width :100vw;
    height:100vw;
  }
} 
@media (orientation:landscape) {
  .square {
    width :100vh;
    height:100vh;
  }
} 

Append Char To String in C?

I do not think you can declare a string like that in c. You may only do that for const char* and of course you can not modify a const char * as it is const.

You may use dynamic char array but you will have to take care of the reallocation.

EDIT: in fact this syntax compiles correctly. Still you can should not modify what str points to if it is initialized in the way you do it (from string literal)

How an 'if (A && B)' statement is evaluated?

yes, if( (A) && (B) ) will fail on the first clause, if (A) evaluates false.

this applies to any language btw, not just C derivatives. For threaded and parallel processing this is a different story ;)

Bash syntax error: unexpected end of file

I had the problem when I wrote "if - fi" statement in one line:

if [ -f ~/.git-completion.bash ]; then . ~/.git-completion.bash fi

Write multiline solved my problem:

if [ -f ~/.git-completion.bash ]; then 
    . ~/.git-completion.bash
 fi

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

+(False) converts to 0 and +(True) converts to 1

How do I detect unsigned integer multiply overflow?

Clang 3.4+ and GCC 5+ offer checked arithmetic builtins. They offer a very fast solution to this problem, especially when compared to bit-testing safety checks.

For the example in OP's question, it would work like this:

unsigned long b, c, c_test;
if (__builtin_umull_overflow(b, c, &c_test))
{
    // Returned non-zero: there has been an overflow
}
else
{
    // Return zero: there hasn't been an overflow
}

The Clang documentation doesn't specify whether c_test contains the overflowed result if an overflow occurred, but the GCC documentation says that it does. Given that these two like to be __builtin-compatible, it's probably safe to assume that this is how Clang works too.

There is a __builtin for each arithmetic operation that can overflow (addition, subtraction, multiplication), with signed and unsigned variants, for int sizes, long sizes, and long long sizes. The syntax for the name is __builtin_[us](operation)(l?l?)_overflow:

  • u for unsigned or s for signed;
  • operation is one of add, sub or mul;
  • no l suffix means that the operands are ints; one l means long; two ls mean long long.

So for a checked signed long integer addition, it would be __builtin_saddl_overflow. The full list can be found on the Clang documentation page.

GCC 5+ and Clang 3.8+ additionally offer generic builtins that work without specifying the type of the values: __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow. These also work on types smaller than int.

The builtins lower to what's best for the platform. On x86, they check the carry, overflow and sign flags.

Visual Studio's cl.exe doesn't have direct equivalents. For unsigned additions and subtractions, including <intrin.h> will allow you to use addcarry_uNN and subborrow_uNN (where NN is the number of bits, like addcarry_u8 or subborrow_u64). Their signature is a bit obtuse:

unsigned char _addcarry_u32(unsigned char c_in, unsigned int src1, unsigned int src2, unsigned int *sum);
unsigned char _subborrow_u32(unsigned char b_in, unsigned int src1, unsigned int src2, unsigned int *diff);

c_in/b_in is the carry/borrow flag on input, and the return value is the carry/borrow on output. It does not appear to have equivalents for signed operations or multiplications.

Otherwise, Clang for Windows is now production-ready (good enough for Chrome), so that could be an option, too.

How do I Convert DateTime.now to UTC in Ruby?

DateTime.now.new_offset(0)

will work in standard Ruby (i.e. without ActiveSupport).

Check if current date is between two dates Oracle SQL

You don't need to apply to_date() to sysdate. It is already there:

select 1
from dual 
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');

If you are concerned about the time component on the date, then use trunc():

select 1
from dual 
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
                             TO_DATE('20/06/2014', 'DD/MM/YYYY');

Is there a C# case insensitive equals operator?

Try this:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

How to fast get Hardware-ID in C#?

I got here looking for the same thing and I found another solution. If you guys are interested I share this class:

using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
    /// <summary>
    /// Generates a 16 byte Unique Identification code of a computer
    /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
    /// </summary>
    public class FingerPrint  
    {
        private static string fingerPrint = string.Empty;
        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " + 
            biosId() + "\nBASE >> " + baseId() +
                            //"\nDISK >> "+ diskId() + "\nVIDEO >> " + 
            videoId() +"\nMAC >> "+ macId()
                                     );
            }
            return fingerPrint;
        }
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier
        (string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
        private static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
        //BIOS Identifier
        private static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
        //Main physical hard drive ID
        private static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
        //Motherboard ID
        private static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
        //Primary video controller ID
        private static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
        //First enabled network card ID
        private static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration", 
                "MACAddress", "IPEnabled");
        }
        #endregion
    }
}

I won't take any credit for this because I found it here It worked faster than I expected for me. Without the graphic card, mac and drive id's I got the unique ID in about 2-3 seconds. With those above included I got it in about 4-5 seconds.

Note: Add reference to System.Management.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

In your ASPX page you've got the list like this:

    <asp:CheckBoxList ID="YrChkBox" runat="server" 
        onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
    <asp:Button ID="button" runat="server" Text="Submit" />

In your code behind aspx.cs page, you have this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Populate the CheckBoxList items only when it's not a postback.
            YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
            YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
        }
    }

    protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Create the list to store.
        List<String> YrStrList = new List<string>();
        // Loop through each item.
        foreach (ListItem item in YrChkBox.Items)
        {
            if (item.Selected)
            {
                // If the item is selected, add the value to the list.
                YrStrList.Add(item.Value);
            }
            else
            {
                // Item is not selected, do something else.
            }
        }
        // Join the string together using the ; delimiter.
        String YrStr = String.Join(";", YrStrList.ToArray());

        // Write to the page the value.
        Response.Write(String.Concat("Selected Items: ", YrStr));
    }

Ensure you use the if (!IsPostBack) { } condition because if you load it every page refresh, it's actually destroying the data.

Service Temporarily Unavailable Magento?

Check if there is a file called maintenance.flag and if so delete it.

Magento 1.x : maintenance.flag file is in : magento root directory

Magento 2.x : maintenance.flag file is in : var folder

When Magento is performing certain tasks it temporarily creates this file. Magento checks for its existence and if it's there will send users to the page you described.

It's supposed to automatically delete this file when done processing whatever task it was doing, but I've experienced occasions where something went wrong and it failed to delete it.

Unstaged changes left after git reset --hard

Okay, I've kind of solved the problem.

It seemed that the .gitattributes file, containing:

*.sln        eol=crlf
*.vcproj     eol=crlf
*.vcxproj*   eol=crlf

made the project files appear unstaged. I am clueless why that is, and I'm really hoping that someone privy to the ways of git will give us a nice explanation.

My fix was to remove these files, and to add autocrlf = false under [core] in .git/config.

This does not amount to exactly the same thing as the previous configuration, as it requires every dev to have autocrlf = false. I'd like to find a better fix.

EDIT:

I commented the incriminating lines, uncommented them and it worked. What the ... I don't even ... !

document.createElement("script") synchronously

I had the following problem(s) with the existing answers to this question (and variations of this question on other stackoverflow threads):

  • None of the loaded code was debuggable
  • Many of the solutions required callbacks to know when loading was finished instead of truly blocking, meaning I would get execution errors from immediately calling loaded (ie loading) code.

Or, slightly more accurately:

  • None of the loaded code was debuggable (except from the HTML script tag block, if and only if the solution added a script elements to the dom, and never ever as individual viewable scripts.) => Given how many scripts I have to load (and debug), this was unacceptable.
  • Solutions using 'onreadystatechange' or 'onload' events failed to block, which was a big problem since the code originally loaded dynamic scripts synchronously using 'require([filename, 'dojo/domReady']);' and I was stripping out dojo.

My final solution, which loads the script before returning, AND has all scripts properly accessible in the debugger (for Chrome at least) is as follows:

WARNING: The following code should PROBABLY be used only in 'development' mode. (For 'release' mode I recommend prepackaging and minification WITHOUT dynamic script loading, or at least without eval).

//Code User TODO: you must create and set your own 'noEval' variable

require = function require(inFileName)
{
    var aRequest
        ,aScript
        ,aScriptSource
        ;

    //setup the full relative filename
    inFileName = 
        window.location.protocol + '//'
        + window.location.host + '/'
        + inFileName;

    //synchronously get the code
    aRequest = new XMLHttpRequest();
    aRequest.open('GET', inFileName, false);
    aRequest.send();

    //set the returned script text while adding special comment to auto include in debugger source listing:
    aScriptSource = aRequest.responseText + '\n////# sourceURL=' + inFileName + '\n';

    if(noEval)//<== **TODO: Provide + set condition variable yourself!!!!**
    {
        //create a dom element to hold the code
        aScript = document.createElement('script');
        aScript.type = 'text/javascript';

        //set the script tag text, including the debugger id at the end!!
        aScript.text = aScriptSource;

        //append the code to the dom
        document.getElementsByTagName('body')[0].appendChild(aScript);
    }
    else
    {
        eval(aScriptSource);
    }
};

HttpClient.GetAsync(...) never returns when using await/async

Since you are using .Result or .Wait or await this will end up causing a deadlock in your code.

you can use ConfigureAwait(false) in async methods for preventing deadlock

like this:

var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead)
                             .ConfigureAwait(false);

you can use ConfigureAwait(false) wherever possible for Don't Block Async Code .

Strip off URL parameter with PHP

very simple

$link = "http://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0"
echo substr($link, 0, strpos($link, "return") - 1);
//output : http://example.com/index.php?id=115&Itemid=283

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

How could others, on a local network, access my NodeJS app while it's running on my machine?

Make sure the server is running, either by using 'npm start', or 'nodemon' in the command line window.

PadLeft function in T-SQL

-- Please look into these.

select FORMAT(1, 'd4');
select FORMAT(2, 'd4');
select FORMAT(12, 'd4');
select FORMAT(123, 'd4');
select FORMAT(1234, 'd4');

-- I hope these would help you

Inline elements shifting when made bold on hover

I use text-shadow solution as some others mentioned here:

text-shadow: 0 0 0.01px;

the difference is that I do not specify shadow color, so this solution is universal for all font colors.

Customize UITableView header section

Swift 4.2

In Swift 4.2 the name of table is a little changed.

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 18))
        let label = UILabel(frame: CGRect(x: 10, y: 5, width: tableView.frame.size.width, height: 18))
        label.font = UIFont.systemFont(ofSize: 14)
        label.text = list.objectAtIndex(section) as! String
        view.addSubview(label)
        view.backgroundColor = UIColor.gray // Set your background color

        return view
    }

Use a JSON array with objects with javascript

By 'JSON array containing objects' I guess you mean a string containing JSON?

If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.

After that you just iterate over the array as normal.

for (var i = 0; i < myArray.length; i++) {
    alert(myArray[i].Title);
}

Run cron job only if it isn't already running

I do this for a print spooler program that I wrote, it's just a shell script:

#!/bin/sh
if ps -ef | grep -v grep | grep doctype.php ; then
        exit 0
else
        /home/user/bin/doctype.php >> /home/user/bin/spooler.log &
        #mailing program
        /home/user/bin/simplemail.php "Print spooler was not running...  Restarted." 
        exit 0
fi

It runs every two minutes and is quite effective. I have it email me with special information if for some reason the process is not running.

Cannot find "Package Explorer" view in Eclipse

The simplest, and best long-term solution

Go to the main menu on top of Eclipse and locate Window next to Run and expand it.

 Window->Reset Perspective... to restore all views to their defaults

It will reset the default setting.

Why is the console window closing immediately once displayed my output?

if your program requires you to press enter to continue like you have to enter a value and continue, then add a new double or int and type write before retunr(0); scanf_s("%lf",&the variable);

Run all SQL files in a directory

@echo off
cd C:\Program Files (x86)\MySQL\MySQL Workbench 6.0 CE

for %%a in (D:\abc\*.sql) do (
echo %%a
mysql --host=ip --port=3306 --user=uid--password=ped < %%a
)

Step1: above lines copy into note pad save it as bat.

step2: In d drive abc folder in all Sql files in queries executed in sql server.

step3: Give your ip, user id and password.

Why doesn't JavaScript support multithreading?

It's the implementations that doesn't support multi-threading. Currently Google Gears is providing a way to use some form of concurrency by executing external processes but that's about it.

The new browser Google is supposed to release today (Google Chrome) executes some code in parallel by separating it in process.

The core language, of course can have the same support as, say Java, but support for something like Erlang's concurrency is nowhere near the horizon.

Check if string contains \n Java

For portability, you really should do something like this:

public static final String NEW_LINE = System.getProperty("line.separator")
.
.
.
word.contains(NEW_LINE);

unless you're absolutely certain that "\n" is what you want.

How do I create a comma-separated list from an array in PHP?

Sometimes you don't even need php for this in certain instances (List items each are in their own generic tag on render for example) You can always add commas to all elements but last-child via css if they are separate elements after being rendered from the script.

I use this a lot in backbone apps actually to trim some arbitrary code fat:

.likers a:not(:last-child):after { content: ","; }

Basically looks at the element, targets all except it's last element, and after each item it adds a comma. Just an alternative way to not have to use script at all if the case applies.

Extract hostname name from string

// use this if you know you have a subdomain
// www.domain.com -> domain.com
function getDomain() {
  return window.location.hostname.replace(/([a-zA-Z0-9]+.)/,"");
}

Distinct() with lambda?

If Distinct() doesn't produce unique results, try this one:

var filteredWC = tblWorkCenter.GroupBy(cc => cc.WCID_I).Select(grp => grp.First()).Select(cc => new Model.WorkCenter { WCID = cc.WCID_I }).OrderBy(cc => cc.WCID); 

ObservableCollection<Model.WorkCenter> WorkCenter = new ObservableCollection<Model.WorkCenter>(filteredWC);

What is the best method of handling currency/money?

Use money-rails gem. It nicely handles money and currencies in your model and also has a bunch of helpers to format your prices.

VBScript How can I Format Date?

For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.

Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)

Which will result in 11-22-2019 (depending on the current date)

Escaping quotation marks in PHP

Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"

Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.

'typeid' versus 'typeof' in C++

You can use Boost demangle to accomplish a nice looking name:

#include <boost/units/detail/utility.hpp>

and something like

To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

How to check if PHP array is associative or sequential?

This question is actually useless when it comes to array of php because with the nature of php an array should not have to be fully associative or indexing, it can be combination of both, the way user have define and assigned the value an array can be a combination of both. see the example below

$y= array(5);
$y["0x"]="n";
$y["vbg"]="12132";
$y[1] = "k";

var_dump($y); //this will output 4 element array

echo "</br>" .$y["0x"]."</br>".$y[0];

for($x=0;$x<sizeof($y);$x++){ // this will output all index elements & gives error after that
    echo "</br> index elements ".$y[$x];
}

so the correct question that has to ask is , is all the element in array are associative or index. if you really know that it will only be either associative or indexing not a combination of these two, you can just simply use this method to find wether it is an index or associative array.

function AssocTest(&$arr){
    if(is_array($arr)){

        reset($arr); // reset pointer to first element of array

        if(gettype(key($arr)) == "string"){ //get the type(nature) of first element key 
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

you can use it as normal function

echo(AssocTest($y)?  "Associative array": "Not an Associative array/ Not an array at all");

and important thing to remember evan you have initialize an array as associative but the names that you have gave the associative array is just numbers it will treat as an index array when it being read by php if you have not explicitly gave the string names. take a look at the example below.

$y["0"]="n";
$y["1"]="12132";
$y["22"] = "k";

//both will get the same output
echo "<br/> s0 ".$y["22"];
echo "<br/> s0 ".$y[22];

for($x=0;$x<count($y);$x++){
   echo "<br/> arr ".$y[$x]; // this will output up to 2nd element and give an error after

}

so if you need to be sure all the elements of the array to be exactly indexed or either associative , there is no other way but go true all the elements and check each and every element key by generated index array as post by many people here.

function fullAssocTest(&$arr)
{
    if(is_array($arr)){
        return (array_keys($arr) !== range(0, count($arr) - 1));
    }
}

its less coding, but this thing is really process intensive and really un-necessary work.

How can I specify a local gem in my Gemfile?

In order to use local gem repository in a Rails project, follow the steps below:

  1. Check if your gem folder is a git repository (the command is executed in the gem folder)

    git rev-parse --is-inside-work-tree
    
  2. Getting repository path (the command is executed in the gem folder)

    git rev-parse --show-toplevel
    
  3. Setting up a local override for the rails application

    bundle config local.GEM_NAME /path/to/local/git/repository
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository is the output of the command in point 2

  4. In your application Gemfile add the following line:

    gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    
  5. Running bundle install should give something like this:

    Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository) 
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository from point 2

  6. Finally, run bundle list, not gem list and you should see something like this:

    GEM_NAME (0.0.1 5a68b88)
    

    where GEM_NAME is the name of your gem


A few important cases I am observing using:

Rails 4.0.2  
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 
Ubuntu 13.10  
RubyMine 6.0.3
  • It seems RubyMine is not showing local gems as an external library. More information about the bug can be found here and here
  • When I am changing something in the local gem, in order to be loaded in the rails application I should stop/start the rails server
  • If I am changing the version of the gem, stopping/starting the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile like this:

    gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    

Unit Testing C Code

Cmockery is a recently launched project that consists on a very simple to use C library for writing unit tests.

Sprintf equivalent in Java

// Store the formatted string in 'result'
String result = String.format("%4d", i * j);

// Write the result to standard output
System.out.println( result );

See format and its syntax

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

How can I generate an apk that can run without server with react-native?

Try below, it will generate an app-debug.apk on your root/android/app/build/outputs/apk/debug folder

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

then go to android folder and run

./gradlew assembleDebug

Mockito matcher and array of primitives

I would try any(byte[].class)

PHP Pass by reference in foreach

I had to spend a few hours to figure out why a[3] is changing on each iteration. This is the explanation at which I arrived.

There are two types of variables in PHP: normal variables and reference variables. If we assign a reference of a variable to another variable, the variable becomes a reference variable.

for example in

$a = array('zero', 'one', 'two', 'three');

if we do

$v = &$a[0]

the 0th element ($a[0]) becomes a reference variable. $v points towards that variable; therefore, if we make any change to $v, it will be reflected in $a[0] and vice versa.

now if we do

$v = &$a[1]

$a[1] will become a reference variable and $a[0] will become a normal variable (Since no one else is pointing to $a[0] it is converted to a normal variable. PHP is smart enough to make it a normal variable when no one else is pointing towards it)

This is what happens in the first loop

foreach ($a as &$v) {

}

After the last iteration $a[3] is a reference variable.

Since $v is pointing to $a[3] any change to $v results in a change to $a[3]

in the second loop,

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

in each iteration as $v changes, $a[3] changes. (because $v still points to $a[3]). This is the reason why $a[3] changes on each iteration.

In the iteration before the last iteration, $v is assigned the value 'two'. Since $v points to $a[3], $a[3] now gets the value 'two'. Keep this in mind.

In the last iteration, $v (which points to $a[3]) now has the value of 'two', because $a[3] was set to two in the previous iteration. two is printed. This explains why 'two' is repeated when $v is printed in the last iteration.