Programs & Examples On #Python server pages

Error TF30063: You are not authorized to access ... \DefaultCollection

When Visual Studio prompted me for Visual Studio Team Services credentials there are two options:

  1. Use a "Work or School"
  2. Use a "Personal" account

In my situation I was using a work email address, however, I had to select "Personal" in order to get connected. Selecting "Work or School" gave me the "tf30063 you are not authorized to access..." error.

For some reason my email address appears to be registered as "personal" even though everything is setup in Office 365 / Azure as a company. I believe the Microsoft account was created prior to our Silver Partnership status with Microsoft.

Retrieve a Fragment from a ViewPager

The main answer relies on a name being generated by the framework. If that ever changes, then it will no longer work.

What about this solution, overriding instantiateItem() and destroyItem() of your Fragment(State)PagerAdapter:

public class MyPagerAdapter extends FragmentStatePagerAdapter {
    SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return ...;
    }

    @Override
    public Fragment getItem(int position) {
        return MyFragment.newInstance(...); 
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        registeredFragments.put(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        registeredFragments.remove(position);
        super.destroyItem(container, position, object);
    }

    public Fragment getRegisteredFragment(int position) {
        return registeredFragments.get(position);
    }
}

This seems to work for me when dealing with Fragments that are available. Fragments that have not yet been instantiated, will return null when calling getRegisteredFragment. But I've been using this mostly to get the current Fragment out of the ViewPager: adapater.getRegisteredFragment(viewPager.getCurrentItem()) and this won't return null.

I'm not aware of any other drawbacks of this solution. If there are any, I'd like to know.

How to check if user input is not an int value

Simply throw Exception if input is invalid

Scanner sc=new Scanner(System.in);
try
{
  System.out.println("Please input an integer");
  //nextInt will throw InputMismatchException
  //if the next token does not match the Integer
  //regular expression, or is out of range
  int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
  //Print "This is not an integer"
  //when user put other than integer
  System.out.println("This is not an integer");
}

Checking if a key exists in a JS object

Above answers are good. But this is good too and useful.

!obj['your_key']  // if 'your_key' not in obj the result --> true

It's good for short style of code special in if statements:

if (!obj['your_key']){
    // if 'your_key' not exist in obj
    console.log('key not in obj');
} else {
    // if 'your_key' exist in obj
    console.log('key exist in obj');
}

Note: If your key be equal to null or "" your "if" statement will be wrong.

obj = {'a': '', 'b': null, 'd': 'value'}
!obj['a']    // result ---> true
!obj['b']    // result ---> true
!obj['c']    // result ---> true
!obj['d']    // result ---> false

So, best way for checking if a key exists in a obj is:'a' in obj

multiple prints on the same line in Python

Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn't make use of the integer argument and could probably be done away with altogether.

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

Both have been tested and work.

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

Validating IPv4 addresses with regexp

I saw very bad regexes in this page.. so i came with my own:

\b((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b

Explanation:

num-group = (0-9|10-99|100-199|200-249|250-255)
<border> + { <num-group> + <dot-cahracter> }x3 + <num-group> + <border>

Here you can verify how it works here

How to Set Active Tab in jQuery Ui

Inside your function for the click action use

$( "#tabs" ).tabs({ active: # });

Where # is replaced by the tab index you want to select.

How to write an inline IF statement in JavaScript?

<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>

parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );

How to completely hide the navigation bar in iPhone / HTML5

Try the following:

  1. Add this meta tag in the head of your HTML file:

    <meta name="apple-mobile-web-app-capable" content="yes" />
    
  2. Open your site with Safari on iPhone, and use the bookmark feature to add your site to the home screen.

  3. Go back to home screen and open the bookmarked site. The URL and status bar will be gone.

As long as you only need to work with the iPhone, you should be fine with this solution.

In addition, your sample on the warnerbros.com site uses the Sencha touch framework. You can Google it for more information or check out their demos.

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

JavaScript: client-side vs. server-side validation

The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:

  • The end user could have javascript switched off
  • The data could be sent directly to your server by someone who's not even using your site, with a custom app designed to do so
  • A Javascript error on your page (caused by any number of things) could result in some, but not all, of your validation running

In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.

How to upload folders on GitHub

I've just gone through that process again. Always end up cloning the repo locally, upload the folder I want to have in that repo to that cloned location, commit the changes and then push it.

Note that if you're dealing with large files, you'll need to consider using something like Git LFS.

How do I format XML in Notepad++?

There is no such a thing like TextFX in Notepad++, not in the latest version at least. This is one of the reasons I'm still with DreamWeaver even if it is driving me insane being slow and unresponsive from time to time...

Lightweight Javascript DB for use in Node.js

Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...

https://github.com/btwael/locallydb

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How to programmatically close a JFrame

This answer was given by Alex and I would like to recommend it. It worked for me and another thing it's straightforward and so simple.

setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

Time stamp in the C programming language

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

If might be better off to use gettimeofday() as mentioned here

How can I check if a JSON is empty in NodeJS?

You can use either of these functions:

// This should work in node.js and other ES5 compliant implementations.
function isEmptyObject(obj) {
  return !Object.keys(obj).length;
}

// This should work both there and elsewhere.
function isEmptyObject(obj) {
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}

Example usage:

if (isEmptyObject(query)) {
  // There are no queries.
} else {
  // There is at least one query,
  // or at least the query object is not empty.
}

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Try this:

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

This work for me on Centos 6

Iterating through all the cells in Excel VBA or VSTO 2005

In Excel VBA, this function will give you the content of any cell in any worksheet.

Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
    getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function

So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.

did you register the component correctly? For recursive components, make sure to provide the "name" option

Since you have applied different name for the components:

components: {
      'i-tabs' : Tabs,
      'i-tab-pane': Tabpane
    }

You also need to have same name while you export: (Check to name in your Tabpane component)

name: 'Tabpane'

From the error, what I can say is you have not defined the name in your component Tabpane. Make sure to verify the name and it should work fine with no error.

Unix's 'ls' sort by name

For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort

To sort them in reverse order:
ls -1 | sort -r

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

In numpy, index and dimension numbering starts with 0. So axis 0 means the 1st dimension. Also in numpy a dimension can have length (size) 0. The simplest case is:

In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
...
IndexError: index 0 is out of bounds for axis 0 with size 0

I also get it if x = np.zeros((0,5), int), a 2d array with 0 rows, and 5 columns.

So someplace in your code you are creating an array with a size 0 first axis.

When asking about errors, it is expected that you tell us where the error occurs.

Also when debugging problems like this, the first thing you should do is print the shape (and maybe the dtype) of the suspected variables.

Applied to pandas

Resolving the error:

  1. Use a try-except block
  2. Verify the size of the array is not 0
    • if x.size != 0:

JSON library for C#

You should also try my ServiceStack JsonSerializer - it's the fastest .NET JSON serializer at the moment based on the benchmarks of the leading JSON serializers and supports serializing any POCO Type, DataContracts, Lists/Dictionaries, Interfaces, Inheritance, Late-bound objects including anonymous types, etc.

Basic Example

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>(); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

CentOS: Copy directory to another directory

This works for me.

cp -r /home/server/folder/test/. /home/server

Reading a JSP variable from JavaScript

The cleanest way, as far as I know:

  1. add your JSP variable to an HTML element's data-* attribute
  2. then read this value via Javascript when required

My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.

The HTML part without JSP:

<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
    Here is your regular page main content
</body>

The HTML part when using JSP:

<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
    Here is your regular page main content
</body>

The javascript part (using jQuery for simplicity):

<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
    jQuery(function(){
        var valuePassedFromJSP = $("body").attr("data-customvalueone");
        var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");

        alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>

And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/

Resources:

How to detect Windows 64-bit platform with .NET?

Microsoft has put a code sample for this:

http://1code.codeplex.com/SourceControl/changeset/view/39074#842775

It looks like this:

    /// <summary>
    /// The function determines whether the current operating system is a 
    /// 64-bit operating system.
    /// </summary>
    /// <returns>
    /// The function returns true if the operating system is 64-bit; 
    /// otherwise, it returns false.
    /// </returns>
    public static bool Is64BitOperatingSystem()
    {
        if (IntPtr.Size == 8)  // 64-bit programs run only on Win64
        {
            return true;
        }
        else  // 32-bit programs run on both 32-bit and 64-bit Windows
        {
            // Detect whether the current process is a 32-bit process 
            // running on a 64-bit system.
            bool flag;
            return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
                IsWow64Process(GetCurrentProcess(), out flag)) && flag);
        }
    }

    /// <summary>
    /// The function determins whether a method exists in the export 
    /// table of a certain module.
    /// </summary>
    /// <param name="moduleName">The name of the module</param>
    /// <param name="methodName">The name of the method</param>
    /// <returns>
    /// The function returns true if the method specified by methodName 
    /// exists in the export table of the module specified by moduleName.
    /// </returns>
    static bool DoesWin32MethodExist(string moduleName, string methodName)
    {
        IntPtr moduleHandle = GetModuleHandle(moduleName);
        if (moduleHandle == IntPtr.Zero)
        {
            return false;
        }
        return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
    }

    [DllImport("kernel32.dll")]
    static extern IntPtr GetCurrentProcess();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr GetModuleHandle(string moduleName);

    [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    static extern IntPtr GetProcAddress(IntPtr hModule,
        [MarshalAs(UnmanagedType.LPStr)]string procName);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);

There is a WMI version available as well (for testing remote machines).

Get the last day of the month in SQL

Here's my version. No string manipulation or casting required, just one call each to the DATEADD, YEAR and MONTH functions:

DECLARE @test DATETIME
SET @test = GETDATE()  -- or any other date

SELECT DATEADD(month, ((YEAR(@test) - 1900) * 12) + MONTH(@test), -1)

Is there a way to force npm to generate package-lock.json?

This is answered in the comments; package-lock.json is a feature in npm v5 and higher. npm shrinkwrap is how you create a lockfile in all versions of npm.

Multipart forms from C# client

Below is the code which I'm using

    //This URL not exist, it's only an example.
    string url = "http://myBox.s3.amazonaws.com/";
    //Instantiate new CustomWebRequest class
    CustomWebRequest wr = new CustomWebRequest(url);
    //Set values for parameters
    wr.ParamsCollection.Add(new ParamsStruct("key", "${filename}"));
    wr.ParamsCollection.Add(new ParamsStruct("acl", "public-read"));
    wr.ParamsCollection.Add(new ParamsStruct("success_action_redirect", "http://www.yahoo.com"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-uuid", "14365123651274"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-tag", ""));
    wr.ParamsCollection.Add(new ParamsStruct("AWSAccessKeyId", "zzzz"));            
    wr.ParamsCollection.Add(new ParamsStruct("Policy", "adsfadsf"));
    wr.ParamsCollection.Add(new ParamsStruct("Signature", "hH6lK6cA="));
    //For file type, send the inputstream of selected file
    StreamReader sr = new StreamReader(@"file.txt");
    wr.ParamsCollection.Add(new ParamsStruct("file", sr, ParamsStruct.ParamType.File, "file.txt"));

    wr.PostData();

from the following link I've downloaded the same code http://www.codeproject.com/KB/cs/multipart_request_C_.aspx

Any Help

Adding a 'share by email' link to website

Easiest: http://www.addthis.com/

Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...

CSS Animation and Display None

The following will get you to animate an element when

  1. Giving it a Display - None
  2. Giving it a Display - Block

CSS

.MyClass {
       opacity: 0;
       display:none;
       transition: opacity 0.5s linear;
       -webkit-transition: opacity 0.5s linear;
       -moz-transition: opacity 0.5s linear;
       -o-transition: opacity 0.5s linear;
       -ms-transition: opacity 0.5s linear;
 }

JavaScript

function GetThisHidden(){
    $(".MyClass").css("opacity", "0").on('transitionend webkitTransitionEnd oTransitionEnd otransitionend', HideTheElementAfterAnimation);
}

function GetThisDisplayed(){
    $(".MyClass").css("display", "block").css("opacity", "1").unbind("transitionend webkitTransitionEnd oTransitionEnd otransitionend");
}

function HideTheElementAfterAnimation(){
    $(".MyClass").css("display", "none");
}

Change a Nullable column to NOT NULL with Default Value

I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created

UPDATE MyTable SET Created = GetDate() where Created IS NULL

ALTER TABLE dbo.MyTable 
ALTER COLUMN Created DATETIME NOT NULL 

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The server at x3.chatforyoursite.com needs to output the following header:

Access-Control-Allow-Origin: http://www.example.com

Where http://www.example.com is your website address. You should check your settings on chatforyoursite.com to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

Convert JsonNode into POJO

This should do the trick:

mapper.readValue(fileReader, MyClass.class);

I say should because I'm using that with a String, not a BufferedReader but it should still work.

Here's my code:

String inputString = // I grab my string here
MySessionClass sessionObject;
try {
    ObjectMapper objectMapper = new ObjectMapper();
    sessionObject = objectMapper.readValue(inputString, MySessionClass.class);

Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Or you'll get an error that it can't find the property to set into.

Get user info via Google API

scope - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token

get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token

you will get json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}

To Tahir Yasin:

This is a php example.
You can use json_decode function to get userInfo array.

$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];

Rails Object to hash

Old question, but heavily referenced ... I think most people use other methods, but there is infact a to_hash method, it has to be setup right. Generally, pluck is a better answer after rails 4 ... answering this mainly because I had to search a bunch to find this thread or anything useful & assuming others are hitting the same problem...

Note: not recommending this for everyone, but edge cases!


From the ruby on rails api ... http://api.rubyonrails.org/classes/ActiveRecord/Result.html ...

This class encapsulates a result returned from calling #exec_query on any database connection adapter. For example:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>

...

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ] ...

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I researched online and saw that the Response.End() always throws an exception.

Replace this: HttpContext.Current.Response.End();

With this:

HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

How to Add a Dotted Underline Beneath HTML Text

It's not impossible without CSS. For example as a list item:

<li style="border-bottom: 1px dashed"><!--content --></li>

How to break out from a ruby block?

next and break seem to do the correct thing in this simplified example!

class Bar
  def self.do_things
      Foo.some_method(1..10) do |x|
            next if x == 2
            break if x == 9
            print "#{x} "
      end
  end
end

class Foo
    def self.some_method(targets, &block)
      targets.each do |target|
        begin
          r = yield(target)
        rescue  => x
          puts "rescue #{x}"
        end
     end
   end
end

Bar.do_things

output: 1 3 4 5 6 7 8

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

How to comment lines in rails html.erb files?

ruby on rails notes has a very nice blogpost about commenting in erb-files

the short version is

to comment a single line use

<%# commented line %>

to comment a whole block use a if false to surrond your code like this

<% if false %>
code to comment
<% end %>

Find object by its property in array of objects with AngularJS way

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

What's "this" in JavaScript onclick?

Here (this) is a object which contains all features/properties of the dom element. you can see by

console.log(this);

This will display all attributes properties of the dom element with hierarchy. You can manipulate the dom element by this.

Also describe on the below link:-

http://www.quirksmode.org/js/this.html

Mocking python function based on input arguments

You can also use partial from functools if you want to use a function that takes parameters but the function you are mocking does not. E.g. like this:

def mock_year(year):
    return datetime.datetime(year, 11, 28, tzinfo=timezone.utc)
@patch('django.utils.timezone.now', side_effect=partial(mock_year, year=2020))

This will return a callable that doesn't accept parameters (like Django's timezone.now()), but my mock_year function does.

html5: display video inside canvas

You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.

You can also use for ex. this plugin https://github.com/tstabla/stVideo

How to customize a Spinner in Android

I have build a small demo project on this you could have a look to it Link to project

Auto margins don't center image in page

img{display: flex; max-width: 80%; margin: auto;}

This is working for me. You can also use display: table in this case. Moreover, if you don't want to stick to this approach you can use the following:

img{position: relative; left: 50%;}

Extract time from moment js object

Use format method with a specific pattern to extract the time. Working example

_x000D_
_x000D_
var myDate = "2017-08-30T14:24:03";_x000D_
console.log(moment(myDate).format("HH:mm")); // 24 hour format_x000D_
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM_x000D_
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

Android turn On/Off WiFi HotSpot programmatically

I have publish unofficial api's for same, it's contains more than just hotspot turn on/off. link

For API's DOC - link.

size of struct in C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

Updating user data - ASP.NET Identity

I am using the new EF & Identity Core and I have the same issue, with the addition that I've got this error:

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked.

With the new DI model I added the constructor's Controller the context to the DB.

I tried to see what are the conflict with _conext.ChangeTracker.Entries() and adding AsNoTracking() to my calls without success.

I only need to change the state of my object (in this case Identity)

_context.Entry(user).State = EntityState.Modified;
var result = await _userManager.UpdateAsync(user);

And worked without create another store or object and mapping.

I hope someone else is useful my two cents.

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

How to change column datatype in SQL database without losing data

ALTER TABLE tablename
ALTER COLUMN columnname columndatatype(size)

Note: if there is a size of columns, just write the size also.

Grouping into interval of 5 minutes within a time range

How about this one:

select 
    from_unixtime(unix_timestamp(timestamp) - unix_timestamp(timestamp) mod 300) as ts,  
    sum(value)
from group_interval 
group by ts 
order by ts
;

Angular 2 Cannot find control with unspecified name attribute on formArrays

This happened to me because I left a formControlName empty (formControlName=""). Since I didn't need that extra form control, I deleted it and the error was resolved.

YAML Multi-Line Arrays

Following Works for me and its good from readability point of view when array element values are small:

key: [string1, string2, string3, string4, string5, string6]

Note:snakeyaml implementation used

How to remove from a map while iterating it?

Assuming C++11, here is a one-liner loop body, if this is consistent with your programming style:

using Map = std::map<K,V>;
Map map;

// Erase members that satisfy needs_removing(itr)
for (Map::const_iterator itr = map.cbegin() ; itr != map.cend() ; )
  itr = needs_removing(itr) ? map.erase(itr) : std::next(itr);

A couple of other minor style changes:

  • Show declared type (Map::const_iterator) when possible/convenient, over using auto.
  • Use using for template types, to make ancillary types (Map::const_iterator) easier to read/maintain.

XAMPP - Error: MySQL shutdown unexpectedly

This worked for me,

  1. quit the XAMPP
  2. cut the All files in C:\xampp\mysql\backup
  3. paste and replace files in C:\xampp\mysql\data
  4. run as administrator the XAMPP

How to display a confirmation dialog when clicking an <a> link?

Most browsers don't display the custom message passed to confirm().

With this method, you can show a popup with a custom message if your user changed the value of any <input> field.

You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  let unsaved = false;_x000D_
  // detect changes in all input fields and set the 'unsaved' flag_x000D_
  $(":input").change(() => unsaved = true);_x000D_
  // trigger popup on click_x000D_
  $('.dangerous-link').click(function() {_x000D_
    if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {_x000D_
      return; // user didn't confirm_x000D_
    }_x000D_
    // either there are no unsaved changes or the user confirmed_x000D_
    window.location.href = $(this).data('destination');_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<input type="text" placeholder="Nuclear code here" />_x000D_
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">_x000D_
    Launch nuke!_x000D_
</a>
_x000D_
_x000D_
_x000D_

Try changing the input value in the example to get a preview of how it works.

ActionBar text color

If you need to set the color programmatically this is the way to do it:

static void setActionBarTextColor(Activity activity, int color)
{
      ActionBar actionBar = activity instanceof AppCompatActivity
                    ? ((AppCompatActivity) activity).getSupportActionBar()
                    : activity.getActionBar();
      String title = activity.getTitle(); // or any title you want
      SpannableString ss = new SpannableString(title);
      ss.setSpan(new ForegroundColorSpan(color), 0, title.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
      actionBar.setTitle(ss);
}

How do I find if a string starts with another string in Ruby?

puts 'abcdefg'.start_with?('abc')  #=> true

[edit] This is something I didn't know before this question: start_with takes multiple arguments.

'abcdefg'.start_with?( 'xyz', 'opq', 'ab')

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

<root>
    <level value="ALL" />
    <appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />
</logger>

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This is documented behavior. From ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME).

changing source on html5 video tag

According to the spec

Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily complicated approach.

So what you are trying to do is apparently not supposed to work.

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.

Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close();  //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);

How do I install soap extension?

Please follow the below steps :

 1) Locate php.ini in your apache bin folder, I.e Apache/bin/php.ini
 2) Remove the ; from the beginning of extension=php_soap.dll
 3) Restart your Apache server (by using : 
    # /etc/init.d/apache2 restart OR 
    $ sudo /etc/init.d/apache2 restart OR 
    $ sudo service apache2 restart)
 4) Look up your phpinfo();

 you may check here as well,if this does not solve your issue:  
 https://www.php.net/manual/en/soap.requirements.php

Alternative to Intersect in MySQL

SELECT
  campo1,
  campo2,
  campo3,
  campo4
FROM tabela1
WHERE CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
NOT IN
(SELECT CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
FROM tabela2);

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

Where is svcutil.exe in Windows 7?

Type in the Microsoft Visual Studio Command Prompt: where svcutil.exe. On my machine it is in: C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcUtil.exe

How to write palindrome in JavaScript

function palindrome(str){
    for (var i = 0; i <= str.length; i++){ 
        if  (str[i] !== str[str.length - 1 - i]) {
            return "The string is not a palindrome";
        }
    }
return "The string IS a palindrome"
}

palindrome("abcdcba"); //"The string IS a palindrome"
palindrome("abcdcb"); //"The string is not a palindrome";

If you console.log this line: console.log(str[i] + " and " + str[str.length - 1 - i]), before the if statement, you'll see what (str[str.length - 1 - i]) is. I think this is the most confusing part but you'll get it easily when you check it out on your console.

How to get host name with port from a http or https request

You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.

StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
  host = host.substring(idx); //remove scheme if present
}

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

Swift: How to get substring from start to last index of character

Do you want to get a substring of a string from start index to the last index of one of its characters? If so, you may choose one of the following Swift 2.0+ methods.

Methods that require Foundation

Get a substring that includes the last index of a character:

import Foundation

let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
    print(string.substringToIndex(rangeOfIndex.endIndex))
}

// prints "www.stackoverflow."

Get a substring that DOES NOT include the last index of a character:

import Foundation

let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
    print(string.substringToIndex(rangeOfIndex.startIndex))
}

// prints "www.stackoverflow"

If you need to repeat those operations, extending String can be a good solution:

import Foundation

extension String {
    func substringWithLastInstanceOf(character: Character) -> String? {
        if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
            return self.substringToIndex(rangeOfIndex.endIndex)
        }
        return nil
    }
    func substringWithoutLastInstanceOf(character: Character) -> String? {
        if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
            return self.substringToIndex(rangeOfIndex.startIndex)
        }
        return nil
    }
}

print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))

/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/

Methods that DO NOT require Foundation

Get a substring that includes the last index of a character:

let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
    print(string[string.startIndex ..< reverseIndex.base])
}

// prints "www.stackoverflow."

Get a substring that DOES NOT include the last index of a character:

let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
    print(string[string.startIndex ..< reverseIndex.base.advancedBy(-1)])
}

// prints "www.stackoverflow"

If you need to repeat those operations, extending String can be a good solution:

extension String {
    func substringWithLastInstanceOf(character: Character) -> String? {
        if let reverseIndex = characters.reverse().indexOf(".") {
            return self[self.startIndex ..< reverseIndex.base]
        }
        return nil
    }
    func substringWithoutLastInstanceOf(character: Character) -> String? {
        if let reverseIndex = characters.reverse().indexOf(".") {
            return self[self.startIndex ..< reverseIndex.base.advancedBy(-1)]
        }
        return nil
    }
}

print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))

/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/

How do you add CSS with Javascript?

This is my solution to add a css rule at the end of the last style sheet list:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

Getting HTTP code in PHP using curl

curl_exec is necessary. Try CURLOPT_NOBODY to not download the body. That might be faster.

Do HttpClient and HttpClientHandler have to be disposed between requests?

If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.

Code:

// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
    HttpRequestHeaders DefaultRequestHeaders { get; }
    Uri BaseAddress { get; set; }
    // ...
    // All the other methods from peeking at HttpClient
}

public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
    public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
    public static HashSet<Uri> _uris;

    static HttpClientHander()
    {
        _httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
        _uris = new HashSet<Uri>();
        SetupGlobalPoolFinalizer();
    }

    private DateTime _delayFinalization = DateTime.MinValue;
    private bool _isDisposed = false;

    public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
    {
        HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
        _uris.Add(baseUrl);
        httpClient._delayFinalization = DateTime.MinValue;
        httpClient.BaseAddress = baseUrl;

        return httpClient;
    }

    void IDisposable.Dispose()
    {
        _isDisposed = true;
        GC.SuppressFinalize(this);

        base.Dispose();
    }

    ~HttpClientHander()
    {
        if (_delayFinalization == DateTime.MinValue)
            _delayFinalization = DateTime.UtcNow;
        if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
            GC.ReRegisterForFinalize(this);
    }

    private static void SetupGlobalPoolFinalizer()
    {
        AppDomain.CurrentDomain.ProcessExit +=
            (sender, eventArgs) => { FinalizeGlobalPool(); };
    }

    private static void FinalizeGlobalPool()
    {
        foreach (var key in _uris)
        {
            HttpClientHander value = null;
            if (_httpClientsPool.TryGetValue(key, out value))
                try { value.Dispose(); } catch { }
        }

        _uris.Clear();
        _httpClientsPool = null;
    }
}

var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).

  • HttpClient, as an interface, can't call Dispose().
  • Dispose() will be called in a delayed fashion by the Garbage Collector. Or when the program cleans up the object through its destructor.
  • Uses Weak References + delayed cleanup logic so it remains in use so long as it is being reused frequently.
  • It only allocates a new HttpClient for each base URL passed to it. Reasons explained by Ohad Schneider answer below. Bad behavior when changing base url.
  • HttpClientHandle allows for Mocking in tests

Get filename from input [type='file'] using jQuery

var file = $('#YOURID > input[type="file"]'); file.value; // filename will be,

In Chrome, it will be something like C:\fakepath\FILE_NAME or undefined if no file was selected.

It is a limitation or intention that the browser does not reveal the file structure of the local machine.

PHP removing a character in a string

$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
    $url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}

Align <div> elements side by side

Apply float:left; to both of your divs should make them stand side by side.

How to create a button programmatically?

    // UILabel:
    let label = UILabel()
    label.frame = CGRectMake(35, 100, 250, 30)
    label.textColor = UIColor.blackColor()
    label.textAlignment = NSTextAlignment.Center
    label.text = "Hello World"
    self.view.addSubview(label)

    // UIButton:
    let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
    btn.frame = CGRectMake(130, 70, 60, 20)
    btn.setTitle("Click", forState: UIControlState.Normal)
    btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
    btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
    view.addSubview(btn)


    // Button Action:
    @IBAction func clickAction(sender:AnyObject)
    {
        print("Click Action")
    }

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If your jar file already has an absolute pathname as shown, it is particularly easy:

cd /where/you/want/it; jar xf /path/to/jarfile.jar

That is, you have the shell executed by Python change directory for you and then run the extraction.

If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar can find it after the change of directory.

The only issues left to worry about are things like blanks in the path names.

How to select date without time in SQL

Convert it back to datetime after converting to date in order to keep same datatime if needed

select Convert(datetime, Convert(date, getdate())  )

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

Maybe you wrongly set permission on python3. For instance if for the file permission is set like

`os.chmod('spam.txt', 0777)` --> This will lead to SyntaxError 

This syntax was used in Python2. Now if you change like: os.chmod('spam.txt', 777) --> This is still worst!! Your permission will be set wrongly since are not on "octal" but on decimal.

Afterwards you will get permission Error if you try for instance to remove the file: PermissionError: [WinError 5] Access is denied:

Solution for python3 is quite easy: os.chmod('spam.txt', 0o777) --> The syntax is now ZERO and o "0o"

How does python numpy.where() work?

np.where returns a tuple of length equal to the dimension of the numpy ndarray on which it is called (in other words ndim) and each item of tuple is a numpy ndarray of indices of all those values in the initial ndarray for which the condition is True. (Please don't confuse dimension with shape)

For example:

x=np.arange(9).reshape(3,3)
print(x)
array([[0, 1, 2],
      [3, 4, 5],
      [6, 7, 8]])
y = np.where(x>4)
print(y)
array([1, 2, 2, 2], dtype=int64), array([2, 0, 1, 2], dtype=int64))


y is a tuple of length 2 because x.ndim is 2. The 1st item in tuple contains row numbers of all elements greater than 4 and the 2nd item contains column numbers of all items greater than 4. As you can see, [1,2,2,2] corresponds to row numbers of 5,6,7,8 and [2,0,1,2] corresponds to column numbers of 5,6,7,8 Note that the ndarray is traversed along first dimension(row-wise).

Similarly,

x=np.arange(27).reshape(3,3,3)
np.where(x>4)


will return a tuple of length 3 because x has 3 dimensions.

But wait, there's more to np.where!

when two additional arguments are added to np.where; it will do a replace operation for all those pairwise row-column combinations which are obtained by the above tuple.

x=np.arange(9).reshape(3,3)
y = np.where(x>4, 1, 0)
print(y)
array([[0, 0, 0],
   [0, 0, 1],
   [1, 1, 1]])

HTML Canvas Full Screen

The newest Chrome and Firefox support a fullscreen API, but setting to fullscreen is like a window resize. Listen to the onresize-Event of the window-object:

$(window).bind("resize", function(){
    var w = $(window).width();
    var h = $(window).height();

    $("#mycanvas").css("width", w + "px");
    $("#mycanvas").css("height", h + "px"); 
});

//using HTML5 for fullscreen (only newest Chrome + FF)
$("#mycanvas")[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); //Chrome
$("#mycanvas")[0].mozRequestFullScreen(); //Firefox

//...

//now i want to cancel fullscreen
document.webkitCancelFullScreen(); //Chrome
document.mozCancelFullScreen(); //Firefox

This doesn't work in every browser. You should check if the functions exist or it will throw an js-error.

for more info on html5-fullscreen check this: http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API

How to convert binary string value to decimal

private static int convertBinaryToDecimal(String strOfBinary){
        int flag = 1, binary=0;
        char binaryOne = '1';
        char[] charArray = strOfBinary.toCharArray();
        for(int i=charArray.length-1;i>=0;i--){
            if(charArray[i] == binaryOne){
                binary+=flag;
            }
            flag*=2;
        }
        return binary;
    }

How to add a button to UINavigationBar?

Sample code to set the rightbutton on a NavigationBar.

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
    style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Title"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[bar pushNavigationItem:item animated:NO];

But normally you would have a NavigationController, enabling you to write:

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
    style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;

How can I give eclipse more memory than 512M?

Here is how i increased the memory allocation of eclipse Juno:

enter image description here

I have a total of 4GB on my system and when im working on eclipse, i dont run any other heavy softwares along side it. So I allocated 2Gb.

The thing i noticed is that the difference between min and max values should be of 512. The next value should be let say 2048 min + 512 = 2560max

Here is the heap value inside eclipse after setting -Xms2048m -Xmx2560m:

enter image description here

How to remove element from array in forEach loop?

Use Array.prototype.filter instead of forEach:

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);

How To Set Text In An EditText

Use +, the string concatenation operator:

 ed = (EditText) findViewById (R.id.box);
    int x = 10;
    ed.setText(""+x);

or use

String.valueOf(int):
ed.setText(String.valueOf(x));

or use

Integer.toString(int):
ed.setText(Integer.toString(x));

ArrayList of int array in java

Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.

Using,

Arrays.toString(arl.get(0))

means splitting the String object into a substring if you want to insert anything in between, such as commas.

Here's what I think amv was looking for from an int array viewpoint.

System.out.println("Arraylist contains: " 
    + arl.get(0)[0] + ", " 
    + arl.get(0)[1] + ", " 
    + arl.get(0)[2]);

This answer is a little late for amv but still may be useful to others.

How to properly export an ES6 class in Node 4?

With ECMAScript 2015 you can export and import multiple classes like this

class Person
{
    constructor()
    {
        this.type = "Person";
    }
}

class Animal{
    constructor()
    {
        this.type = "Animal";
    }
}

module.exports = {
    Person,
    Animal
};

then where you use them:

const { Animal, Person } = require("classes");

const animal = new Animal();
const person = new Person();

In case of name collisions, or you prefer other names you can rename them like this:

const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");

const animal = new OtherAnimal();
const person = new OtherPerson();

Adobe Reader Command Line Reference

You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)

The FAQ notes that the use of the command line switches is unsupported.

To open a file it's:

AcroRd32.exe <filename>

The following switches are available:

  • /n - Launch a new instance of Reader even if one is already open
  • /s - Don't show the splash screen
  • /o - Don't show the open file dialog
  • /h - Open as a minimized window
  • /p <filename> - Open and go straight to the print dialog
  • /t <filename> <printername> <drivername> <portname> - Print the file the specified printer.

What is the best way to convert an array to a hash in Ruby

Update

Ruby 2.1.0 is released today. And I comes with Array#to_h (release notes and ruby-doc), which solves the issue of converting an Array to a Hash.

Ruby docs example:

[[:foo, :bar], [1, 2]].to_h    # => {:foo => :bar, 1 => 2}

TypeError : Unhashable type

You'll find that instances of list do not provide a __hash__ --rather, that attribute of each list is actually None (try print [].__hash__). Thus, list is unhashable.

The reason your code works with list and not set is because set constructs a single set of items without duplicates, whereas a list can contain arbitrary data.

Is nested function a good approach when required by only one function?

It's actually fine to declare one function inside another one. This is specially useful creating decorators.

However, as a rule of thumb, if the function is complex (more than 10 lines) it might be a better idea to declare it on the module level.

AngularJS - Create a directive that uses ng-model

You only need ng-model when you need to access the model's $viewValue or $modelValue. See NgModelController. And in that case, you would use require: '^ngModel'.

For the rest, see Roys answer.

Is there a "not equal" operator in Python?

Use != or <>. Both stands for not equal.

The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent. [Reference: Python language reference]

Select Multiple Fields from List in Linq

public class Student
{
    public string Name { set; get; }
    public int ID { set; get; }
}

class Program
{
  static void Main(string[] args)
    {
        Student[] students =
        {
        new Student { Name="zoyeb" , ID=1},
        new Student { Name="Siddiq" , ID=2},
        new Student { Name="sam" , ID=3},
        new Student { Name="james" , ID=4},
        new Student { Name="sonia" , ID=5}
        };

        var studentCollection = from s in students select new { s.ID , s.Name};

        foreach (var student in studentCollection)
        {
            Console.WriteLine(student.Name);
            Console.WriteLine(student.ID);
        }
    }
}

Java Code for calculating Leap Year

Pseudo code from Wikipedia translated into the most compact Java

(year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))

Differences between fork and exec

I think some concepts from "Advanced Unix Programming" by Marc Rochkind were helpful in understanding the different roles of fork()/exec(), especially for someone used to the Windows CreateProcess() model:

A program is a collection of instructions and data that is kept in a regular file on disk. (from 1.1.2 Programs, Processes, and Threads)

.

In order to run a program, the kernel is first asked to create a new process, which is an environment in which a program executes. (also from 1.1.2 Programs, Processes, and Threads)

.

It’s impossible to understand the exec or fork system calls without fully understanding the distinction between a process and a program. If these terms are new to you, you may want to go back and review Section 1.1.2. If you’re ready to proceed now, we’ll summarize the distinction in one sentence: A process is an execution environment that consists of instruction, user-data, and system-data segments, as well as lots of other resources acquired at runtime, whereas a program is a file containing instructions and data that are used to initialize the instruction and user-data segments of a process. (from 5.3 exec System Calls)

Once you understand the distinction between a program and a process, the behavior of fork() and exec() function can be summarized as:

  • fork() creates a duplicate of the current process
  • exec() replaces the program in the current process with another program

(this is essentially a simplified 'for dummies' version of paxdiablo's much more detailed answer)

"X does not name a type" error in C++

  1. Forward declare User
  2. Put the declaration of MyMessageBox before User

Vertically align text to top within a UILabel

Easiest approach using Storyboard:

Embed Label in a StackView and set the following two attributes of StackView in the Attribute Inspector:

1- Axis to Horizontal,

2- Alignment to Top

enter image description here

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOs) applications?

Ruby, Python, Lua, Scheme, Lisp, Smalltalk, C#, Haskell, ActionScript, JavaScript, Objective-C, C++, C. That's just the ones that pop into my head right now. I'm sure there's hundreds if not thousands of others. (E.g. there's no reason why you couldn't use any .NET language with MonoTouch, i.e. VB.NET, F#, Nemerle, Boo, Cobra, ...)

Also are there plans in the future to expand the amount of programming languages that iOs will support?

Sure. Pretty much every programming language community on this planet is currently working on getting their language to run on iOS.

Also, a lot of people are working on programming languages specifically designed for touch devices such as iPod touch, iPhone and iPad, e.g. Phil Mercurio's Thyrd language.

How to open/run .jar file (double-click not working)?

You must create a manifest file and specify your class that has the main method. you can build your jar file with manifest file as a parameter.

jar cfm MyJar.jar Manifest.txt MyPackage/*.class

Manifest-Version: 1.0

Archiver-Version: Plexus Archiver

Created-By: Apache Maven

Built-By: Cakes

Build-Jdk: 1.6.0_04

Main-Class: com.foo.App

Why does PEP-8 specify a maximum line length of 79 characters?

because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).

Java Hashmap: How to get key from value?

I think your choices are

  • Use a map implementation built for this, like the BiMap from google collections. Note that the google collections BiMap requires uniqueless of values, as well as keys, but it provides high performance in both directions performance
  • Manually maintain two maps - one for key -> value, and another map for value -> key
  • Iterate through the entrySet() and to find the keys which match the value. This is the slowest method, since it requires iterating through the entire collection, while the other two methods don't require that.

C non-blocking keyboard input

On UNIX systems, you can use sigaction call to register a signal handler for SIGINT signal which represents the Control+C key sequence. The signal handler can set a flag which will be checked in the loop making it to break appropriately.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Well, the <head> tag has nothing to do with the <header> tag. In the head comes all the metadata and stuff, while the header is just a layout component.
And layout comes into body. So I disagree with you.

how to change directory using Windows command line

cd has a parameter /d, which will change drive and path with one command:

cd /d d:\temp

( see cd /?)

How to find out whether a file is at its `eof`?

Get the EOF position of the file:

def get_eof_position(file_handle):
    original_position = file_handle.tell()
    eof_position = file_handle.seek(0, 2)
    file_handle.seek(original_position)
    return eof_position

and compare it with the current position: get_eof_position == file_handle.tell().

Take nth column in a text file

iirc :

cat filename.txt | awk '{ print $2 $4 }'

or, as mentioned in the comments :

awk '{ print $2 $4 }' filename.txt

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

Initially used only ViewDidLoad with tableView. On testing with loss of Wifi, by setting device to airplane mode, realized that the table did not refresh with return of Wifi. In fact, there appears to be no way to refresh tableView on the device even by hitting the home button with background mode set to YES in -Info.plist.

My solution:

-(void) viewWillAppear: (BOOL) animated { [self.tableView reloadData];}

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

SOAP client in .NET - references or examples?

If you can get it to run in a browser then something as simple as this would work

var webRequest = WebRequest.Create(@"http://webservi.se/year/getCurrentYear");

using (var response = webRequest.GetResponse())
{
    using (var rd = new StreamReader(response.GetResponseStream()))
    {
        var soapResult = rd.ReadToEnd();
    }
}

Start an Activity with a parameter

Kotlin code:

Start the SecondActivity:

startActivity(Intent(context, SecondActivity::class.java)
    .putExtra(SecondActivity.PARAM_GAME_ID, gameId))

Get the Id in SecondActivity:

class CaptureActivity : AppCompatActivity() {

    companion object {
        const val PARAM_GAME_ID = "PARAM_GAME_ID"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gameId = intent.getStringExtra(PARAM_GAME_ID)
        // TODO use gameId
    }
}

where gameId is String? (can be null)

How can I reorder my divs using only CSS?

This can be done with CSS only!

Please check my answer to this similar question:

https://stackoverflow.com/a/25462829/1077230

I don't want to double post my answer but the short of it is that the parent needs to become a flexbox element. Eg:

(only using the webkit vendor prefix here.)

#main {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
}

Then, swap divs around by indicating their order with:

#main > div#one{
    -webkit-box-ordinal-group: 2;
    -moz-box-ordinal-group: 2;
    -ms-flex-order: 2;
    -webkit-order: 2;
    order: 2;
    overflow:visible;
}

#main > div#two{
    -webkit-box-ordinal-group: 1;
    -moz-box-ordinal-group: 1;
    -ms-flex-order: 1;
    -webkit-order: 1;
    order: 1;
}

What is the preferred syntax for defining enums in JavaScript?

It's easy to use, I think. https://stackoverflow.com/a/32245370/4365315

var A = {a:11, b:22}, 
enumA = new TypeHelper(A);

if(enumA.Value === A.b || enumA.Key === "a"){ 
... 
}

var keys = enumA.getAsList();//[object, object]

//set
enumA.setType(22, false);//setType(val, isKey)

enumA.setType("a", true);

enumA.setTypeByIndex(1);

UPDATE:

There is my helper codes(TypeHelper).

_x000D_
_x000D_
var Helper = {_x000D_
    isEmpty: function (obj) {_x000D_
        return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;_x000D_
    },_x000D_
_x000D_
    isObject: function (obj) {_x000D_
        return (typeof obj === 'object');_x000D_
    },_x000D_
_x000D_
    sortObjectKeys: function (object) {_x000D_
        return Object.keys(object)_x000D_
            .sort(function (a, b) {_x000D_
                c = a - b;_x000D_
                return c_x000D_
            });_x000D_
    },_x000D_
    containsItem: function (arr, item) {_x000D_
        if (arr && Array.isArray(arr)) {_x000D_
            return arr.indexOf(item) > -1;_x000D_
        } else {_x000D_
            return arr === item;_x000D_
        }_x000D_
    },_x000D_
_x000D_
    pushArray: function (arr1, arr2) {_x000D_
        if (arr1 && arr2 && Array.isArray(arr1)) {_x000D_
            arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);_x000D_
        }_x000D_
    }_x000D_
};_x000D_
function TypeHelper() {_x000D_
    var _types = arguments[0],_x000D_
        _defTypeIndex = 0,_x000D_
        _currentType,_x000D_
        _value,_x000D_
        _allKeys = Helper.sortObjectKeys(_types);_x000D_
_x000D_
    if (arguments.length == 2) {_x000D_
        _defTypeIndex = arguments[1];_x000D_
    }_x000D_
_x000D_
    Object.defineProperties(this, {_x000D_
        Key: {_x000D_
            get: function () {_x000D_
                return _currentType;_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _currentType.setType(val, true);_x000D_
            },_x000D_
            enumerable: true_x000D_
        },_x000D_
        Value: {_x000D_
            get: function () {_x000D_
                return _types[_currentType];_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _value.setType(val, false);_x000D_
            },_x000D_
            enumerable: true_x000D_
        }_x000D_
    });_x000D_
    this.getAsList = function (keys) {_x000D_
        var list = [];_x000D_
        _allKeys.forEach(function (key, idx, array) {_x000D_
            if (key && _types[key]) {_x000D_
_x000D_
                if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {_x000D_
                    var json = {};_x000D_
                    json.Key = key;_x000D_
                    json.Value = _types[key];_x000D_
                    Helper.pushArray(list, json);_x000D_
                }_x000D_
            }_x000D_
        });_x000D_
        return list;_x000D_
    };_x000D_
_x000D_
    this.setType = function (value, isKey) {_x000D_
        if (!Helper.isEmpty(value)) {_x000D_
            Object.keys(_types).forEach(function (key, idx, array) {_x000D_
                if (Helper.isObject(value)) {_x000D_
                    if (value && value.Key == key) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (isKey) {_x000D_
                    if (value && value.toString() == key.toString()) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (value && value.toString() == _types[key]) {_x000D_
                    _currentType = key;_x000D_
                }_x000D_
            });_x000D_
        } else {_x000D_
            this.setDefaultType();_x000D_
        }_x000D_
        return isKey ? _types[_currentType] : _currentType;_x000D_
    };_x000D_
_x000D_
    this.setTypeByIndex = function (index) {_x000D_
        for (var i = 0; i < _allKeys.length; i++) {_x000D_
            if (index === i) {_x000D_
                _currentType = _allKeys[index];_x000D_
                break;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
_x000D_
    this.setDefaultType = function () {_x000D_
        this.setTypeByIndex(_defTypeIndex);_x000D_
    };_x000D_
_x000D_
    this.setDefaultType();_x000D_
}_x000D_
_x000D_
var TypeA = {_x000D_
    "-1": "Any",_x000D_
    "2": "2L",_x000D_
    "100": "100L",_x000D_
    "200": "200L",_x000D_
    "1000": "1000L"_x000D_
};_x000D_
_x000D_
var enumA = new TypeHelper(TypeA, 4);_x000D_
_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setType("200L", false);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
enumA.setDefaultType();_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setTypeByIndex(1);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
document.writeln("is equals = ", (enumA.Value == TypeA["2"]));
_x000D_
_x000D_
_x000D_

How do I get a python program to do nothing?

you can use pass inside if statement.

Instance member cannot be used on type

Your initial problem was:

class ReportView: NSView {
  var categoriesPerPage = [[Int]]()
  var numPages: Int = { return categoriesPerPage.count }
}

Instance member 'categoriesPerPage' cannot be used on type 'ReportView'

previous posts correctly point out, if you want a computed property, the = sign is errant.

Additional possibility for error:

If your intent was to "Setting a Default Property Value with a Closure or Function", you need only slightly change it as well. (Note: this example was obviously not intended to do that)

class ReportView: NSView {
  var categoriesPerPage = [[Int]]()
  var numPages: Int = { return categoriesPerPage.count }()
}

Instead of removing the =, we add () to denote a default initialization closure. (This can be useful when initializing UI code, to keep it all in one place.)

However, the exact same error occurs:

Instance member 'categoriesPerPage' cannot be used on type 'ReportView'

The problem is trying to initialize one property with the value of another. One solution is to make the initializer lazy. It will not be executed until the value is accessed.

class ReportView: NSView {
  var categoriesPerPage = [[Int]]()
  lazy var numPages: Int = { return categoriesPerPage.count }()
}

now the compiler is happy!

Pandas: Return Hour from Datetime Column Directly

Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:

sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour

How do I remove objects from an array in Java?

It depends on what you mean by "remove"? An array is a fixed size construct - you can't change the number of elements in it. So you can either a) create a new, shorter, array without the elements you don't want or b) assign the entries you don't want to something that indicates their 'empty' status; usually null if you are not working with primitives.

In the first case create a List from the array, remove the elements, and create a new array from the list. If performance is important iterate over the array assigning any elements that shouldn't be removed to a list, and then create a new array from the list. In the second case simply go through and assign null to the array entries.

find -exec with multiple commands

I don't know if you can do this with find, but an alternate solution would be to create a shell script and to run this with find.

lastline.sh:

echo $(tail -1 $1),$1

Make the script executable

chmod +x lastline.sh

Use find:

find . -name "*.txt" -exec ./lastline.sh {} \;

Android studio takes too much memory

I'm currently running Android Studio on Windows 8.1 machine with 6 gigs of RAM.

I found that disabling VCS in android studio and using an external program to handle VCS helped a lot. You can disable VCS by going to File->Settings->Plugins and disable the following:

  • CVS Integration
  • Git Integration
  • GitHub
  • Google Cloud Testing
  • Google Cloud Tools Core
  • Google Cloud Tools for Android Studio
  • hg4idea
  • Subversion Integration
  • Mercurial Integration
  • TestNG-J

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

How can I commit a single file using SVN over a network?

this should work:

svn commit -m "<Your message here>" path/to/your/file

you can also add multiple files like this:

svn commit -m "<Your message here>" path/to/your/file [path/to/your/file] [path/to/your/file]

How to view kafka message

You can use console consumer to view messages produced on some topic:

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

Using Case/Switch and GetType to determine the object

Depending on what you are doing in the switch statement, the correct answer is polymorphism. Just put a virtual function in the interface/base class and override for each node type.

Is there a difference between x++ and ++x in java?

In Java there is a difference between x++ and ++x

++x is a prefix form: It increments the variables expression then uses the new value in the expression.

For example if used in code:

int x = 3;

int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4

System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'

x++ is a postfix form: The variables value is first used in the expression and then it is incremented after the operation.

For example if used in code:

int x = 3;

int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4

System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4' 

Hope this is clear. Running and playing with the above code should help your understanding.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I had this problem with a fresh install of wamp and using only default settings without setting any passwords. I found an incorrect default setting and I solved it by the following steps:

  1. Go to C:\wamp\apps\phpmyadmin4.1.14 (Your phpmyadmin version# may differ)
  2. open the file config.inc in a text editor
  3. find the line: $cfg['Servers'][$i]['host'] = '127.0.0.1';
  4. change it to $cfg['Servers'][$i]['host'] = 'localhost';
  5. save the file
  6. restart all services in wamp

The problem seems to be that someone forgot to make the server and host match in the configuration files.

How do I configure Apache 2 to run Perl CGI scripts?

As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2 and mod-perl via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.

Reshaping data.frame from wide to long format

You can also use the cdata package, which uses the concept of (transformation) control table:

# data
wide <- read.table(text="Code Country        1950    1951    1952    1953    1954
AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
ALB  Albania        8,097   8,986   10,058  11,123  12,246", header=TRUE, check.names=FALSE)

library(cdata)
# build control table
drec <- data.frame(
    Year=as.character(1950:1954),
    Value=as.character(1950:1954),
    stringsAsFactors=FALSE
)
drec <- cdata::rowrecs_to_blocks_spec(drec, recordKeys=c("Code", "Country"))

# apply control table
cdata::layout_by(drec, wide)

I am currently exploring that package and find it quite accessible. It is designed for much more complicated transformations and includes the backtransformation. There is a tutorial available.

HTML 5 input type="number" element for floating point numbers on Chrome

Try this

_x000D_
_x000D_
<input onkeypress='return event.charCode >= 48 && _x000D_
                          event.charCode <= 57 || _x000D_
                          event.charCode == 46'>
_x000D_
_x000D_
_x000D_

Why do we have to normalize the input for an artificial neural network?

It's explained well here.

If the input variables are combined linearly, as in an MLP [multilayer perceptron], then it is rarely strictly necessary to standardize the inputs, at least in theory. The reason is that any rescaling of an input vector can be effectively undone by changing the corresponding weights and biases, leaving you with the exact same outputs as you had before. However, there are a variety of practical reasons why standardizing the inputs can make training faster and reduce the chances of getting stuck in local optima. Also, weight decay and Bayesian estimation can be done more conveniently with standardized inputs.

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

How to Update Multiple Array Elements in mongodb

With the release of MongoDB 3.6 ( and available in the development branch from MongoDB 3.5.12 ) you can now update multiple array elements in a single request.

This uses the filtered positional $[<identifier>] update operator syntax introduced in this version:

db.collection.update(
  { "events.profile":10 },
  { "$set": { "events.$[elem].handled": 0 } },
  { "arrayFilters": [{ "elem.profile": 10 }], "multi": true }
)

The "arrayFilters" as passed to the options for .update() or even .updateOne(), .updateMany(), .findOneAndUpdate() or .bulkWrite() method specifies the conditions to match on the identifier given in the update statement. Any elements that match the condition given will be updated.

Noting that the "multi" as given in the context of the question was used in the expectation that this would "update multiple elements" but this was not and still is not the case. It's usage here applies to "multiple documents" as has always been the case or now otherwise specified as the mandatory setting of .updateMany() in modern API versions.

NOTE Somewhat ironically, since this is specified in the "options" argument for .update() and like methods, the syntax is generally compatible with all recent release driver versions.

However this is not true of the mongo shell, since the way the method is implemented there ( "ironically for backward compatibility" ) the arrayFilters argument is not recognized and removed by an internal method that parses the options in order to deliver "backward compatibility" with prior MongoDB server versions and a "legacy" .update() API call syntax.

So if you want to use the command in the mongo shell or other "shell based" products ( notably Robo 3T ) you need a latest version from either the development branch or production release as of 3.6 or greater.

See also positional all $[] which also updates "multiple array elements" but without applying to specified conditions and applies to all elements in the array where that is the desired action.

Also see Updating a Nested Array with MongoDB for how these new positional operators apply to "nested" array structures, where "arrays are within other arrays".

IMPORTANT - Upgraded installations from previous versions "may" have not enabled MongoDB features, which can also cause statements to fail. You should ensure your upgrade procedure is complete with details such as index upgrades and then run

   db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } )

Or higher version as is applicable to your installed version. i.e "4.0" for version 4 and onwards at present. This enabled such features as the new positional update operators and others. You can also check with:

   db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )

To return the current setting

How can I tell AngularJS to "refresh"

Use

$route.reload();

remember to inject $route to your controller.

Laravel Eloquent compare date from datetime field

If you're still wondering how to solve it.

I use

$protected $dates = ['created_at','updated_at','aired'];

In my model and in my where i do

where('aired','>=',time())

So just use the unix to compaire in where.

In views on the otherhand you have to use the date object.

Hope it helps someone!

jQuery get the image src

src should be in quotes:

$('.img1 img').attr('src');

How does internationalization work in JavaScript?

Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript language spec that look like this:

Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString(). Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.

For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:

  • Chrome 24
  • Firefox 29
  • Internet Explorer 11
  • Opera 15

There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.

Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:

// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;

A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.

In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.

Various libraries and plugins for localization:

  • Others:

Feel free to add/edit.

How to get child element by class name?

Here is how I did it using the YUI selectors. Thanks to Hank Gay's suggestion.

notes = YAHOO.util.Dom.getElementsByClassName('four','span','test');

where four = classname, span = the element type/tag name, and test = the parent id.

Best data type for storing currency values in a MySQL database

You could use something like DECIMAL(19,2) by default for all of your monetary values, but if you'll only ever store values lower than $1,000, that's just going to be a waste of valuable database space.

For most implementations, DECIMAL(N,2) would be sufficient, where the value of N is at least the number of digits before the . of the greatest sum you ever expect to be stored in that field + 5. So if you don't ever expect to store any values greater than 999999.99, DECIMAL(11,2) should be more than sufficient (until expectations change).

If you want to be GAAP compliant, you could go with DECIMAL(N,4), where the value of N is at least the number of digits before the . of the greatest sum you ever expect to be stored in that field + 7.

Android Studio how to run gradle sync manually?

I presume it is referring to Tools > Android > "Sync Project with Gradle Files" from the Android Studio main menu.

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

How to delete a file via PHP?

$files = [
    './first.jpg',
    './second.jpg',
    './third.jpg'
];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
    } else {
        // File not found.
    }
}

Maven project.build.directory

It points to your top level output directory (which by default is target):

https://web.archive.org/web/20150527103929/http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:

http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html#resource-filtering-sect-project-properties

If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.

    project.build.sourceDirectory
    project.build.scriptSourceDirectory
    project.build.testSourceDirectory
    project.build.outputDirectory
    project.build.testOutputDirectory
    project.build.directory

sourceDirectory, scriptSourceDirectory, and testSourceDirectory provide access to the source directories for the project. outputDirectory and testOutputDirectory provide access to the directories where Maven is going to put bytecode or other build output. directory refers to the directory which contains all of these output directories.

How can I print each command before executing?

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

Generate a heatmap in MatPlotLib using a scatter data set

and the initial question was... how to convert scatter values to grid values, right? histogram2d does count the frequency per cell, however, if you have other data per cell than just the frequency, you'd need some additional work to do.

x = data_x # between -10 and 4, log-gamma of an svc
y = data_y # between -4 and 11, log-C of an svc
z = data_z #between 0 and 0.78, f1-values from a difficult dataset

So, I have a dataset with Z-results for X and Y coordinates. However, I was calculating few points outside the area of interest (large gaps), and heaps of points in a small area of interest.

Yes here it becomes more difficult but also more fun. Some libraries (sorry):

from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np
from scipy.interpolate import griddata

pyplot is my graphic engine today, cm is a range of color maps with some initeresting choice. numpy for the calculations, and griddata for attaching values to a fixed grid.

The last one is important especially because the frequency of xy points is not equally distributed in my data. First, let's start with some boundaries fitting to my data and an arbitrary grid size. The original data has datapoints also outside those x and y boundaries.

#determine grid boundaries
gridsize = 500
x_min = -8
x_max = 2.5
y_min = -2
y_max = 7

So we have defined a grid with 500 pixels between the min and max values of x and y.

In my data, there are lots more than the 500 values available in the area of high interest; whereas in the low-interest-area, there are not even 200 values in the total grid; between the graphic boundaries of x_min and x_max there are even less.

So for getting a nice picture, the task is to get an average for the high interest values and to fill the gaps elsewhere.

I define my grid now. For each xx-yy pair, i want to have a color.

xx = np.linspace(x_min, x_max, gridsize) # array of x values
yy = np.linspace(y_min, y_max, gridsize) # array of y values
grid = np.array(np.meshgrid(xx, yy.T))
grid = grid.reshape(2, grid.shape[1]*grid.shape[2]).T

Why the strange shape? scipy.griddata wants a shape of (n, D).

Griddata calculates one value per point in the grid, by a predefined method. I choose "nearest" - empty grid points will be filled with values from the nearest neighbor. This looks as if the areas with less information have bigger cells (even if it is not the case). One could choose to interpolate "linear", then areas with less information look less sharp. Matter of taste, really.

points = np.array([x, y]).T # because griddata wants it that way
z_grid2 = griddata(points, z, grid, method='nearest')
# you get a 1D vector as result. Reshape to picture format!
z_grid2 = z_grid2.reshape(xx.shape[0], yy.shape[0])

And hop, we hand over to matplotlib to display the plot

fig = plt.figure(1, figsize=(10, 10))
ax1 = fig.add_subplot(111)
ax1.imshow(z_grid2, extent=[x_min, x_max,y_min, y_max,  ],
            origin='lower', cmap=cm.magma)
ax1.set_title("SVC: empty spots filled by nearest neighbours")
ax1.set_xlabel('log gamma')
ax1.set_ylabel('log C')
plt.show()

Around the pointy part of the V-Shape, you see I did a lot of calculations during my search for the sweet spot, whereas the less interesting parts almost everywhere else have a lower resolution.

Heatmap of a SVC in high resolution

How do I check/uncheck all checkboxes with a button using jQuery?

Check All with uncheck/check controller if all items is/isnt checked

JS:

e = checkbox id t= checkbox (item) class n= checkbox check all class

function checkAll(e,t,n){jQuery("#"+e).click(function(e){if(this.checked){jQuery("."+t).each(function(){this.checked=true;jQuery("."+n).each(function(){this.checked=true})})}else{jQuery("."+t).each(function(){this.checked=false;jQuery("."+n).each(function(){this.checked=false})})}});jQuery("."+t).click(function(e){var r=jQuery("."+t).length;var i=0;var s=0;jQuery("."+t).each(function(){if(this.checked==true){i++}if(this.checked==false){s++}});if(r==i){jQuery("."+n).each(function(){this.checked=true})}if(i<r){jQuery("."+n).each(function(){this.checked=false})}})}

HTML:

Check ALL controle class : chkall_ctrl

<input type="checkbox"name="chkall" id="chkall_up" class="chkall_ctrl"/>
<br/>
1.<input type="checkbox" value="1" class="chkall" name="chk[]" id="chk1"/><br/>
2.<input type="checkbox" value="2" class="chkall" name="chk[]" id="chk2"/><br/>
3.<input type="checkbox" value="3" class="chkall" name="chk[]" id="chk3"/><br/>
<br/>
<input type="checkbox"name="chkall" id="chkall_down" class="chkall_ctrl"/>

<script>
jQuery(document).ready(function($)
{
  checkAll('chkall_up','chkall','chkall_ctrl');
  checkAll('chkall_down','chkall','chkall_ctrl');
});
 </script>

Checking if jquery is loaded using Javascript

You can check whether it exists and, if it does not exist, load it dynamically.

function loadScript(src) {
    return new Promise(function (resolve, reject) {
        var s;
        s = document.createElement('script');
        s.src = src;
        s.onload = resolve;
        s.onerror = reject;
        document.head.appendChild(s);
    });
}



async function load(){
if (!window.jQuery){
    await loadScript(`https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js`);
}

console.log(jQuery);

}

load();

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

It should be MM for months. You are asking for minutes.

DateTime.Now.ToString("dd/MM/yyyy");

See Custom Date and Time Format Strings on MSDN for details.

Directory Chooser in HTML page

If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.

String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

Get the length of a String

If you are just trying to see if a string is empty or not (checking for length of 0), Swift offers a simple boolean test method on String

myString.isEmpty

The other side of this coin was people asking in ObjectiveC how to ask if a string was empty where the answer was to check for a length of 0:

NSString is empty

Soft hyphen in HTML (<wbr> vs. &shy;)

There is an ongoing effort to standardize hyphenation in CSS3.

Some modern browsers, notably Safari and Firefox, already support this. Here is a good and up to date reference on browser support.

Once the CSS hyphenation gets implemented universally, that would be the best solution. In the meantime, I can recommend Hyphenator - a JS script that figures out how to hyphenate your text in the way most appropriate for a particular browser.

Hyphenator:

  • relies on Franklin M. Liangs hyphenation algorithm, commonly known from LaTeX and OpenOffice.
  • uses CSS3 hyphenation where it is available,
  • automatically inserts &shy; on most other browsers,
  • supports multiple languages,
  • is highly configurable,
  • gracefully falls back in case javascript is not enabled.

I've used it and it works great!

Align text in JLabel to the right

JLabel label = new JLabel("fax", SwingConstants.RIGHT);

java - iterating a linked list

iterate LinkedList by using iterator

LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add(“Mumbai”);
linkedList.add(“Delhi”);
linkedList.add(“Noida”);
linkedList.add(“Gao”);
linkedList.add(“Patna”);

Iterator<String>  itr = linkedList.iterator();
 while (itr.hasNext()) {
 System.out.println(“Element is =”+itr.next());

 }

Reference : Java Linkedlist Examples

How do you get a directory listing in C?

There is no standard C (or C++) way to enumerate files in a directory.

Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.

PHP cURL HTTP CODE return 0

If you connect with the server, then you can get a return code from it, otherwise it will fail and you get a 0. So if you try to connect to "www.google.com/lksdfk" you will get a return code of 400, if you go directly to google.com, you will get 302 (and then 200 if you forward to the next page... well I do because it forwards to google.com.br, so you might not get that), and if you go to "googlecom" you will get a 0 (host no found), so with the last one, there is nobody to send a code back.

Tested using the code below.

<?php

$html_brand = "www.google.com";
$ch = curl_init();

$options = array(
    CURLOPT_URL            => $html_brand,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER         => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING       => "",
    CURLOPT_AUTOREFERER    => true,
    CURLOPT_CONNECTTIMEOUT => 120,
    CURLOPT_TIMEOUT        => 120,
    CURLOPT_MAXREDIRS      => 10,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch); 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ( $httpCode != 200 ){
    echo "Return code is {$httpCode} \n"
        .curl_error($ch);
} else {
    echo "<pre>".htmlspecialchars($response)."</pre>";
}

curl_close($ch);

How to prevent a browser from storing passwords

It is working fine for a password field to prevent to remember its history:

_x000D_
_x000D_
$('#multi_user_timeout_pin').on('input keydown', function(e) {_x000D_
  if (e.keyCode == 8 && $(this).val().length == 1) {_x000D_
    $(this).attr('type', 'text');_x000D_
    $(this).val('');_x000D_
  } else {_x000D_
    if ($(this).val() !== '') {_x000D_
      $(this).attr('type', 'password');_x000D_
    } else {_x000D_
      $(this).attr('type', 'text');_x000D_
    }_x000D_
  }_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" id="multi_user_timeout_pin" name="multi_user_pin" autocomplete="off" class="form-control" placeholder="Type your PIN here" ng-model="logutUserPin">
_x000D_
_x000D_
_x000D_

Is CSS Turing complete?

This answer is not accurate because it mix description of UTM and UTM itself (Universal Turing Machine).

We have good answer but from different perspective and it do not show directly flaws in current top answer.


First of all we can agree that human can work as UTM. This mean if we do

CSS + Human == UTM

Then CSS part is useless because all work can be done by Human who will do UTM part. Act of clicking can be UTM, because you do not click at random but only in specific places.

Instead of CSS I could use this text (Rule 110):

000 -> 0
001 -> 1
010 -> 1
011 -> 1
100 -> 0
101 -> 1
110 -> 1
111 -> 0

To guide my actions and result will be same. This mean this text UTM? No this is only input (description) that other UTM (human or computer) can read and run. Clicking is enough to run any UTM.


Critical part that CSS lack is ability to change of it own state in arbitrary way, if CSS could generate clicks then it would be UTM. Argument that your clicks are "crank" for CSS is not accurate because real "crank" for CSS is Layout Engine that run it and it should be enough to prove that CSS is UTM.

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

How to use AND in IF Statement

If there are no typos in the question, you got the conditions wrong:

You said this:

IF cells (i,"A") contains the text 'Miami'

...but your code says:

If Cells(i, "A") <> "Miami"

--> <> means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.

I guess you want this instead:

If Cells(i, "A") like "*Miami*"

EDIT:

Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).

Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.

Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA" line?
Or is the If Cells(i, "A") like "*Miami*" stuff already False?
If yes, try checking just one cell and see if that works.

Why there is no ConcurrentHashSet against ConcurrentHashMap

Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

RuntimeError: module compiled against API version a but this version of numpy is 9

This worked for me:

sudo pip install numpy --upgrade --ignore-installed

How to Replace dot (.) in a string in Java

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

HorizontalScrollView within ScrollView Touch Handling

Neevek's solution works better than Joel's on devices running 3.2 and above. There is a bug in Android that will cause java.lang.IllegalArgumentException: pointerIndex out of range if a gesture detector is used inside a scollview. To duplicate the issue, implement a custom scollview as Joel suggested and put a view pager inside. If you drag (don't lift you figure) to one direction (left/right) and then to the opposite, you will see the crash. Also in Joel's solution, if you drag the view pager by moving your finger diagonally, once your finger leave the view pager's content view area, the pager will spring back to its previous position. All these issues are more to do with Android's internal design or lack of it than Joel's implementation, which itself is a piece of smart and concise code.

http://code.google.com/p/android/issues/detail?id=18990

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

Set angular scope variable in markup

If you not in a loop, you can use ng-init else you can use

{{var=foo;""}}

the "" alows not display your var

Explicitly set column value to null SQL Developer

You'll have to write the SQL DML yourself explicitly. i.e.

UPDATE <table>
   SET <column> = NULL;

Once it has completed you'll need to commit your updates

commit;

If you only want to set certain records to NULL use a WHERE clause in your UPDATE statement.

As your original question is pretty vague I hope this covers what you want.

Java getHours(), getMinutes() and getSeconds()

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

How to revert uncommitted changes including files and folders?

One non-trivial way is to run these two commands:

  1. git stash This will move your changes to the stash, bringing you back to the state of HEAD
  2. git stash drop This will delete the latest stash created in the last command.

How to fetch Java version using single line command in Linux

You can use --version and in that case it's not required to redirect to stdout

java --version | head -1 | cut -f2 -d' '

From java help

-version      print product version to the error stream and exit
--version     print product version to the output stream and exit

How to check a string for specific characters?

This will test if strings are made up of some combination or digits, the dollar sign, and a commas. Is that what you're looking for?

import re

s1 = 'Testing string'
s2 = '1234,12345$'

regex = re.compile('[0-9,$]+$')

if ( regex.match(s1) ):
   print "s1 matched"
else:
   print "s1 didn't match"

if ( regex.match(s2) ):
   print "s2 matched"
else:
   print "s2 didn't match"

Easy way to pull latest of all git submodules

Edit:

In the comments was pointed out (by philfreo ) that the latest version is required. If there is any nested submodules that need to be in their latest version :

git submodule foreach --recursive git pull

-----Outdated comment below-----

Isn't this the official way to do it ?

git submodule update --init

I use it every time. No problems so far.

Edit:

I just found that you can use:

git submodule foreach --recursive git submodule update --init 

Which will also recursively pull all of the submodules, i.e. dependancies.

How to hide the title bar for an Activity in XML with existing custom theme

This Solved my problem

In manifest my activity:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

In style under "AppTheme" name:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme"
        parent="Theme.AppCompat.Light.NoActionBar">
        **<item name="windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>**
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

Delete directory with files in it?

<?php
  function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir."/".$object) == "dir") 
           rrmdir($dir."/".$object); 
        else unlink   ($dir."/".$object);
      }
    }
    reset($objects);
    rmdir($dir);
  }
 }
?>

Have your tryed out the obove code from php.net

Work for me fine

Java - Create a new String instance with specified length and filled with specific character. Best solution?

One extra note: it seems that all public ways of creating a new String instance involves necessarily the copy of whatever buffer you are working with, be it a char[], a StringBuffer or a StringBuilder. From the String javadoc (and is repeated in the respective toString methods from the other classes):

The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

So you'll end up having a possibly big memory copy operation after the "fast filling" of the array. The only solution that may avoid this issue is the one from @mlk, if you can manage working directly with the proposed CharSequence implementation (what may be the case).

PS: I would post this as a comment but I don't have enough reputation to do that yet.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.

Git: Installing Git in PATH with GitHub client for Windows

Thanks everyone who have answered.I have seen all answers and to try to make it easy for everyone

Step 1: Type edit environment and select the option shown

enter image description here

Step 2: Select Path and click on edit

enter image description here

Step 3: In the end add the below statement(you can avoid the first ; if its already there)

;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd

enter image description here

Step 4:- Click on ok

enter image description here

Step 5 **:- One of the important step which is highlighted by one of the users. thanks to him. Please, **CLOSE command prompt and REOPEN then try to write git.

**

  • Close command prompt and restart before trying the below command

**

Here is the magic

enter image description here

How to check if any value is NaN in a Pandas DataFrame

df.isnull().sum()

This will give you count of all NaN values present in the respective coloums of the DataFrame.

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

Resolve issue Immediate, It's related to internal security

We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.

As investigate in server log found

[error] (13)Permission denied: proxy: AJP: attempt to connect to
   10.x.x.x:8069 (virtualhost.virtualdomain.com) failed

Audit log found similar port issue

type=AVC msg=audit(1265039669.305:14): avc:  denied  { name_connect } for  pid=4343 comm="httpd" dest=8069 
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket

Due to internal default security of linux, this cause, now to fix (temporary)

 /usr/sbin/setsebool httpd_can_network_connect 1

Resolve Permanent Issue

/usr/sbin/setsebool -P httpd_can_network_connect 1

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

How does the class_weight parameter in scikit-learn work?

The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.

SUMMARY

  • for moderately imbalanced data WITHOUT noise, there is not much of a difference in applying class weights
  • for moderately imbalanced data WITH noise and strongly imbalanced, it is better to apply class weights
  • param class_weight="balanced" works decent in the absence of you wanting to optimize manually
  • with class_weight="balanced" you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
    • as a result, the total % TRUE might be higher than actual because of all the false positives
    • AUC might misguide you here if the false alarms are an issue
  • no need to change decision threshold to the imbalance %, even for strong imbalance, ok to keep 0.5 (or somewhere around that depending on what you need)

NB

The result might differ when using RF or GBM. sklearn does not have class_weight="balanced" for GBM but lightgbm has LGBMClassifier(is_unbalance=False)

CODE

# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd

# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same

# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last

print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%

print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE

Removing "http://" from a string

Something like this ought to do:

$url = preg_replace("|^.+?://|", "", $url); 

Removes everything up to and including the ://

Javascript/Jquery to change class onclick?

For a super succinct with jQuery approach try:

<div onclick="$(this).toggleClass('newclass')">click me</div>

Or pure JS:

<div onclick="this.classList.toggle('newclass');">click me</div>

cannot find zip-align when publishing app

I decided to just make a video for this..I kept pasting it into tools but alas that was not working for me. I moved it to platform-tools and voila publishing right away..must restart eclipse afterwards.

Tutorial for fixing missing zipalign

Rails get index of "each" loop

<% @images.each_with_index do |page, index| %>

<% end %>

Switching to a TabBar tab view programmatically?

import UIKit

class TabbarViewController: UITabBarController,UITabBarControllerDelegate {

//MARK:- View Life Cycle

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
    yourView.popToRootViewController(animated:false)
}



}

Is there a REAL performance difference between INT and VARCHAR primary keys?

I was a bit annoyed by the lack of benchmarks for this online, so I ran a test myself.

Note though that I don't do it on a regular basic, so please check my setup and steps for any factors that could have influenced the results unintentionally, and post your concerns in comments.

The setup was as follows:

  • Intel® Core™ i7-7500U CPU @ 2.70GHz × 4
  • 15.6 GiB RAM, of which I ensured around 8 GB was free during the test.
  • 148.6 GB SSD drive, with plenty of free space.
  • Ubuntu 16.04 64-bit
  • MySQL Ver 14.14 Distrib 5.7.20, for Linux (x86_64)

The tables:

create table jan_int (data1 varchar(255), data2 int(10), myindex tinyint(4)) ENGINE=InnoDB;
create table jan_int_index (data1 varchar(255), data2 int(10), myindex tinyint(4), INDEX (myindex)) ENGINE=InnoDB;
create table jan_char (data1 varchar(255), data2 int(10), myindex char(6)) ENGINE=InnoDB;
create table jan_char_index (data1 varchar(255), data2 int(10), myindex char(6), INDEX (myindex)) ENGINE=InnoDB;
create table jan_varchar (data1 varchar(255), data2 int(10), myindex varchar(63)) ENGINE=InnoDB;
create table jan_varchar_index (data1 varchar(255), data2 int(10), myindex varchar(63), INDEX (myindex)) ENGINE=InnoDB;

Then, I filled 10 million rows in each table with a PHP script whose essence is like this:

$pdo = get_pdo();

$keys = [ 'alabam', 'massac', 'newyor', 'newham', 'delawa', 'califo', 'nevada', 'texas_', 'florid', 'ohio__' ];

for ($k = 0; $k < 10; $k++) {
    for ($j = 0; $j < 1000; $j++) {
        $val = '';
        for ($i = 0; $i < 1000; $i++) {
            $val .= '("' . generate_random_string() . '", ' . rand (0, 10000) . ', "' . ($keys[rand(0, 9)]) . '"),';
        }
        $val = rtrim($val, ',');
        $pdo->query('INSERT INTO jan_char VALUES ' . $val);
    }
    echo "\n" . ($k + 1) . ' millon(s) rows inserted.';
}

For int tables, the bit ($keys[rand(0, 9)]) was replaced with just rand(0, 9), and for varchar tables, I used full US state names, without cutting or extending them to 6 characters. generate_random_string() generates a 10-character random string.

Then I ran in MySQL:

  • SET SESSION query_cache_type=0;
  • For jan_int table:
    • SELECT count(*) FROM jan_int WHERE myindex = 5;
    • SELECT BENCHMARK(1000000000, (SELECT count(*) FROM jan_int WHERE myindex = 5));
  • For other tables, same as above, with myindex = 'califo' for char tables and myindex = 'california' for varchar tables.

Times of the BENCHMARK query on each table:

  • jan_int: 21.30 sec
  • jan_int_index: 18.79 sec
  • jan_char: 21.70 sec
  • jan_char_index: 18.85 sec
  • jan_varchar: 21.76 sec
  • jan_varchar_index: 18.86 sec

Regarding table & index sizes, here's the output of show table status from janperformancetest; (w/ a few columns not shown):

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Name              | Engine | Version | Row_format | Rows    | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Collation              |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| jan_int           | InnoDB |      10 | Dynamic    | 9739094 |             43 |   422510592 |               0 |            0 |   4194304 |           NULL | utf8mb4_unicode_520_ci |  
| jan_int_index     | InnoDB |      10 | Dynamic    | 9740329 |             43 |   420413440 |               0 |    132857856 |   7340032 |           NULL | utf8mb4_unicode_520_ci |   
| jan_char          | InnoDB |      10 | Dynamic    | 9726613 |             51 |   500170752 |               0 |            0 |   5242880 |           NULL | utf8mb4_unicode_520_ci |  
| jan_char_index    | InnoDB |      10 | Dynamic    | 9719059 |             52 |   513802240 |               0 |    202342400 |   5242880 |           NULL | utf8mb4_unicode_520_ci |  
| jan_varchar       | InnoDB |      10 | Dynamic    | 9722049 |             53 |   521142272 |               0 |            0 |   7340032 |           NULL | utf8mb4_unicode_520_ci |   
| jan_varchar_index | InnoDB |      10 | Dynamic    | 9738381 |             49 |   486539264 |               0 |    202375168 |   7340032 |           NULL | utf8mb4_unicode_520_ci | 
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

My conclusion is that there's no performance difference for this particular use case.

"starting Tomcat server 7 at localhost has encountered a prob"

Method 1:

  • type localhost:8080 in your browser to know which process is taking 8080 port
  • uninstall that program

Method 2:

re-install the apache tomcat BUT during installation change the port number. Watch carefully the installation process

What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

Viewing root access files/folders of android on windows

If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!